<commit_before>//===- Disassembler.cpp - Disassembler for hex strings --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//

#include "Disassembler.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;

typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;

namespace {
class VectorMemoryObject : public MemoryObject {
private:
  const ByteArrayTy &Bytes;
public:
  VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}

  uint64_t getBase() const { return 0; }
  uint64_t getExtent() const { return Bytes.size(); }

  int readByte(uint64_t Addr, uint8_t *Byte) const {
    if (Addr > getExtent())
      return -1;
    *Byte = Bytes[Addr].first;
    return 0;
  }
};
}

static bool PrintInsts(const llvm::MCDisassembler &DisAsm,
                      llvm::MCInstPrinter &Printer, const ByteArrayTy &Bytes,
                      SourceMgr &SM) {
  // Wrap the vector in a MemoryObject.
  VectorMemoryObject memoryObject(Bytes);

  // Disassemble it to strings.
  uint64_t Size;
  uint64_t Index;

  for (Index = 0; Index < Bytes.size(); Index += Size) {
    MCInst Inst;

    if (DisAsm.getInstruction(Inst, Size, memoryObject, Index,
                               /*REMOVE*/ nulls())) {
      Printer.printInst(&Inst);
      outs() << "\n";
    }
    else {
      SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
                      "invalid instruction encoding", "warning");
      if (Size == 0)
        Size = 1; // skip illegible bytes
    }
  }

  return false;
}

int Disassembler::disassemble(const Target &T, const std::string &Triple,
                                 MemoryBuffer &Buffer) {
  // Set up disassembler.
  llvm::OwningPtr<const llvm::MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));

  if (!AsmInfo) {
    errs() << "error: no assembly info for target " << Triple << "\n";
    return -1;
  }

  llvm::OwningPtr<const llvm::MCDisassembler> DisAsm(T.createMCDisassembler());
  if (!DisAsm) {
    errs() << "error: no disassembler for target " << Triple << "\n";
    return -1;
  }

  llvm::MCInstPrinter *InstPrinter = T.createMCInstPrinter(0, *AsmInfo, outs());

  if (!InstPrinter) {
    errs() << "error: no instruction printer for target " << Triple << '\n';
    return -1;
  }

  bool ErrorOccurred = false;

  SourceMgr SM;
  SM.AddNewSourceBuffer(&Buffer, SMLoc());

  // Convert the input to a vector for disassembly.
  ByteArrayTy ByteArray;

  StringRef Str = Buffer.getBuffer();
  while (!Str.empty()) {
    // Strip horizontal whitespace.
    if (size_t Pos = Str.find_first_not_of(" \t\r")) {
      Str = Str.substr(Pos);
      continue;
    }

    // If this is the end of a line or start of a comment, remove the rest of
    // the line.
    if (Str[0] == '\n' || Str[0] == '#') {
      // Strip to the end of line if we already processed any bytes on this
      // line.  This strips the comment and/or the \n.
      if (Str[0] == '\n')
        Str = Str.substr(1);
      else {
        Str = Str.substr(Str.find_first_of('\n'));
        if (!Str.empty())
          Str = Str.substr(1);
      }
      continue;
    }

    // Get the current token.
    size_t Next = Str.find_first_of(" \t\n\r#");
    StringRef Value = Str.substr(0, Next);

    // Convert to a byte and add to the byte vector.
    unsigned ByteVal;
    if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
      // If we have an error, print it and skip to the end of line.
      SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
                                 "invalid input token", "error");
      ErrorOccurred = true;
      Str = Str.substr(Str.find('\n'));
      ByteArray.clear();
      continue;
    }

    ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
    Str = Str.substr(Next);
  }

  if (!ByteArray.empty())
    ErrorOccurred |= PrintInsts(*DisAsm, *InstPrinter, ByteArray, SM);

  return ErrorOccurred;
}
<commit_msg>llvm-mc: Fix MCInstPrinter memory leaks.<commit_after>//===- Disassembler.cpp - Disassembler for hex strings --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements the disassembler of strings of bytes written in
// hexadecimal, from standard input or from a file.
//
//===----------------------------------------------------------------------===//

#include "Disassembler.h"

#include "llvm/ADT/OwningPtr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;

typedef std::vector<std::pair<unsigned char, const char*> > ByteArrayTy;

namespace {
class VectorMemoryObject : public MemoryObject {
private:
  const ByteArrayTy &Bytes;
public:
  VectorMemoryObject(const ByteArrayTy &bytes) : Bytes(bytes) {}

  uint64_t getBase() const { return 0; }
  uint64_t getExtent() const { return Bytes.size(); }

  int readByte(uint64_t Addr, uint8_t *Byte) const {
    if (Addr > getExtent())
      return -1;
    *Byte = Bytes[Addr].first;
    return 0;
  }
};
}

static bool PrintInsts(const MCDisassembler &DisAsm,
                      MCInstPrinter &Printer, const ByteArrayTy &Bytes,
                      SourceMgr &SM) {
  // Wrap the vector in a MemoryObject.
  VectorMemoryObject memoryObject(Bytes);

  // Disassemble it to strings.
  uint64_t Size;
  uint64_t Index;

  for (Index = 0; Index < Bytes.size(); Index += Size) {
    MCInst Inst;

    if (DisAsm.getInstruction(Inst, Size, memoryObject, Index,
                               /*REMOVE*/ nulls())) {
      Printer.printInst(&Inst);
      outs() << "\n";
    }
    else {
      SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
                      "invalid instruction encoding", "warning");
      if (Size == 0)
        Size = 1; // skip illegible bytes
    }
  }

  return false;
}

int Disassembler::disassemble(const Target &T, const std::string &Triple,
                              MemoryBuffer &Buffer) {
  // Set up disassembler.
  OwningPtr<const MCAsmInfo> AsmInfo(T.createAsmInfo(Triple));

  if (!AsmInfo) {
    errs() << "error: no assembly info for target " << Triple << "\n";
    return -1;
  }

  OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler());
  if (!DisAsm) {
    errs() << "error: no disassembler for target " << Triple << "\n";
    return -1;
  }

  OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(0, *AsmInfo, outs()));
  if (!IP) {
    errs() << "error: no instruction printer for target " << Triple << '\n';
    return -1;
  }

  bool ErrorOccurred = false;

  SourceMgr SM;
  SM.AddNewSourceBuffer(&Buffer, SMLoc());

  // Convert the input to a vector for disassembly.
  ByteArrayTy ByteArray;

  StringRef Str = Buffer.getBuffer();
  while (!Str.empty()) {
    // Strip horizontal whitespace.
    if (size_t Pos = Str.find_first_not_of(" \t\r")) {
      Str = Str.substr(Pos);
      continue;
    }

    // If this is the end of a line or start of a comment, remove the rest of
    // the line.
    if (Str[0] == '\n' || Str[0] == '#') {
      // Strip to the end of line if we already processed any bytes on this
      // line.  This strips the comment and/or the \n.
      if (Str[0] == '\n')
        Str = Str.substr(1);
      else {
        Str = Str.substr(Str.find_first_of('\n'));
        if (!Str.empty())
          Str = Str.substr(1);
      }
      continue;
    }

    // Get the current token.
    size_t Next = Str.find_first_of(" \t\n\r#");
    StringRef Value = Str.substr(0, Next);

    // Convert to a byte and add to the byte vector.
    unsigned ByteVal;
    if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
      // If we have an error, print it and skip to the end of line.
      SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
                                 "invalid input token", "error");
      ErrorOccurred = true;
      Str = Str.substr(Str.find('\n'));
      ByteArray.clear();
      continue;
    }

    ByteArray.push_back(std::make_pair((unsigned char)ByteVal, Value.data()));
    Str = Str.substr(Next);
  }

  if (!ByteArray.empty())
    ErrorOccurred |= PrintInsts(*DisAsm, *IP, ByteArray, SM);

  return ErrorOccurred;
}
<|endoftext|>


<commit_before>/* nuklear - v1.09 - public domain */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <math.h>
#include <limits.h>
#include <time.h>

#include "no_rt_util.h"

#include <GL/glew.h>
#include "glfw3.h"

#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_GLFW_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_glfw_gl3.h"

#define WINDOW_WIDTH 1200
#define WINDOW_HEIGHT 800

#define MAX_VERTEX_BUFFER 512 * 1024
#define MAX_ELEMENT_BUFFER 128 * 1024

#define UNUSED(a) (void)a
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) < (b) ? (b) : (a))
#define LEN(a) (sizeof(a)/sizeof(a)[0])

/* ===============================================================
 *
 *                          EXAMPLE
 *
 * ===============================================================*/
/* This are some code examples to provide a small overview of what can be
 * done with this library. To try out an example uncomment the include
 * and the corresponding function. */
#include "style.c"
#include "calculator.c"
#include "overview.c"
#include "node_editor.c"

/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
static void error_callback(int e, const char *d)
{printf("Error %d: %s\n", e, d);}

//int CALLBACK WinMain(
//  _In_ HINSTANCE hInstance,
//  _In_ HINSTANCE hPrevInstance,
//  _In_ LPSTR     lpCmdLine,
//  _In_ int       nCmdShow
//)
int main(void)
{
    /* Platform */
    static GLFWwindow *win;
    int width = 0, height = 0;
    struct nk_context *ctx;
    struct nk_color background;

    /* GLFW */
    glfwSetErrorCallback(error_callback);
    if (!glfwInit()) {
        fprintf(stdout, "[GFLW] failed to init!\n");
        exit(1);
    }
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL);
    glfwMakeContextCurrent(win);
    glfwGetWindowSize(win, &width, &height);

    /* OpenGL */
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    glewExperimental = 1;
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to setup GLEW\n");
        exit(1);
    }

    /* Vertex Array Object */
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // An array of 3 vectors which represents 3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
    };

    // This will identify our vertex buffer
    GLuint vertexbuffer;
    // Generate 1 buffer, put the resulting identifier in vertexbuffer
    glGenBuffers(1, &vertexbuffer);
    // The following commands will talk about our 'vertexbuffer' buffer
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    // Give our vertices to OpenGL.
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    /* nuklear */
    ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS);
    /* Load Fonts: if none of these are loaded a default font will be used  */
    /* Load Cursor: if you uncomment cursor loading please hide the cursor */
    {struct nk_font_atlas *atlas;
    nk_glfw3_font_stash_begin(&atlas);
    /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
    /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
    /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
    /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
    /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
    /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
    nk_glfw3_font_stash_end();
    /*nk_style_load_all_cursors(ctx, atlas->cursors);*/
    /*nk_style_set_font(ctx, &droid->handle);*/}

    /* style.c */
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/

    background = nk_rgb(28,48,62);
    while (!glfwWindowShouldClose(win))
    {
        /* Input */
        glfwPollEvents();
        nk_glfw3_new_frame();

        /* GUI */
        {struct nk_panel layout;
        if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 230, 250),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
            NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
        {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;
            nk_layout_row_static(ctx, 30, 80, 1);
            if(nk_button_label(ctx, "button"))
                fprintf(stdout, "button pressed\n");

            nk_layout_row_dynamic(ctx, 30, 2);
            if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;

            nk_layout_row_dynamic(ctx, 25, 1);
            nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);

            {struct nk_panel combo;
            nk_layout_row_dynamic(ctx, 20, 1);
            nk_label(ctx, "background:", NK_TEXT_LEFT);
            nk_layout_row_dynamic(ctx, 25, 1);
            if (nk_combo_begin_color(ctx, &combo, background, nk_vec2(nk_widget_width(ctx), 400))) {
                nk_layout_row_dynamic(ctx, 120, 1);
                background = nk_color_picker(ctx, background, NK_RGBA);
                nk_layout_row_dynamic(ctx, 25, 1);
                background.r = (nk_byte)nk_propertyi(ctx, "#R:", 0, background.r, 255, 1,1);
                background.g = (nk_byte)nk_propertyi(ctx, "#G:", 0, background.g, 255, 1,1);
                background.b = (nk_byte)nk_propertyi(ctx, "#B:", 0, background.b, 255, 1,1);
                background.a = (nk_byte)nk_propertyi(ctx, "#A:", 0, background.a, 255, 1,1);
                nk_combo_end(ctx);
            }}
        }
        nk_end(ctx);}

        /* -------------- EXAMPLES ---------------- */
        /*calculator(ctx);*/
        /*overview(ctx);*/
        node_editor(ctx);
        /* ----------------------------------------- */

        /* Draw */
        {float bg[4];
        nk_color_fv(bg, background);
        glfwGetWindowSize(win, &width, &height);
        glViewport(0, 0, width, height);

        /* Draw opneGL triangle */
        // 1rst attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
            0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
            );
        // Draw the triangle !
        glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
        glDisableVertexAttribArray(0);

        glClear(GL_COLOR_BUFFER_BIT);
        glClearColor(bg[0], bg[1], bg[2], bg[3]);
        /* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
         * with blending, scissor, face culling, depth test and viewport and
         * defaults everything back into a default state.
         * Make sure to either a.) save and restore or b.) reset your own state after
         * rendering the UI. */
        nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
        glfwSwapBuffers(win);}
    }
    nk_glfw3_shutdown();
    glfwTerminate();
    return 0;
}

<commit_msg>Can use modern OpenGL with nuklear<commit_after>/* nuklear - v1.09 - public domain */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <math.h>
#include <limits.h>
#include <time.h>

#include "no_rt_util.h"

#include <GL/glew.h>
#include "glfw3.h"

#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_GLFW_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_glfw_gl3.h"

#define WINDOW_WIDTH 1200
#define WINDOW_HEIGHT 800

#define MAX_VERTEX_BUFFER 512 * 1024
#define MAX_ELEMENT_BUFFER 128 * 1024

#define UNUSED(a) (void)a
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) < (b) ? (b) : (a))
#define LEN(a) (sizeof(a)/sizeof(a)[0])

/* ===============================================================
 *
 *                          EXAMPLE
 *
 * ===============================================================*/
/* This are some code examples to provide a small overview of what can be
 * done with this library. To try out an example uncomment the include
 * and the corresponding function. */
// #include "style.c"
// #include "calculator.c"
// #include "overview.c"
#include "node_editor.c"

/* ===============================================================
 *
 *                          DEMO
 *
 * ===============================================================*/
static void error_callback(int e, const char *d)
{printf("Error %d: %s\n", e, d);}

//int CALLBACK WinMain(
//  _In_ HINSTANCE hInstance,
//  _In_ HINSTANCE hPrevInstance,
//  _In_ LPSTR     lpCmdLine,
//  _In_ int       nCmdShow
//)
int main(void)
{
    /* Platform */
    static GLFWwindow *win;
    int width = 0, height = 0;
    struct nk_context *ctx;
    struct nk_color background;

    /* GLFW */
    glfwSetErrorCallback(error_callback);
    if (!glfwInit()) {
        fprintf(stdout, "[GFLW] failed to init!\n");
        exit(1);
    }
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL);
    glfwMakeContextCurrent(win);
    glfwGetWindowSize(win, &width, &height);

    /* OpenGL */
    glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    glewExperimental = 1;
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to setup GLEW\n");
        exit(1);
    }

    /* Vertex Array Object */
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // An array of 3 vectors which represents 3 vertices
    static const GLfloat g_vertex_buffer_data[] = {
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
    };

    // This will identify our vertex buffer
    GLuint vertexbuffer;
    // Generate 1 buffer, put the resulting identifier in vertexbuffer
    glGenBuffers(1, &vertexbuffer);
    // The following commands will talk about our 'vertexbuffer' buffer
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    // Give our vertices to OpenGL.
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    /* nuklear */
    ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS);
    /* Load Fonts: if none of these are loaded a default font will be used  */
    /* Load Cursor: if you uncomment cursor loading please hide the cursor */
    {struct nk_font_atlas *atlas;
    nk_glfw3_font_stash_begin(&atlas);
    /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, "../../../extra_font/DroidSans.ttf", 14, 0);*/
    /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
    /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
    /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyClean.ttf", 12, 0);*/
    /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
    /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/
    nk_glfw3_font_stash_end();
    /*nk_style_load_all_cursors(ctx, atlas->cursors);*/
    /*nk_style_set_font(ctx, &droid->handle);*/}

    /* style.c */
    /*set_style(ctx, THEME_WHITE);*/
    /*set_style(ctx, THEME_RED);*/
    /*set_style(ctx, THEME_BLUE);*/
    /*set_style(ctx, THEME_DARK);*/

    background = nk_rgb(28,48,62);
    while (!glfwWindowShouldClose(win))
    {
        /* Input */
        glfwPollEvents();
        nk_glfw3_new_frame();

        /* GUI */
        {struct nk_panel layout;
        if (nk_begin(ctx, &layout, "Demo", nk_rect(50, 50, 230, 250),
            NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
            NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
        {
            enum {EASY, HARD};
            static int op = EASY;
            static int property = 20;
            nk_layout_row_static(ctx, 30, 80, 1);
            if(nk_button_label(ctx, "button"))
                fprintf(stdout, "button pressed\n");

            nk_layout_row_dynamic(ctx, 30, 2);
            if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
            if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;

            nk_layout_row_dynamic(ctx, 25, 1);
            nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);

            {struct nk_panel combo;
            nk_layout_row_dynamic(ctx, 20, 1);
            nk_label(ctx, "background:", NK_TEXT_LEFT);
            nk_layout_row_dynamic(ctx, 25, 1);
            if (nk_combo_begin_color(ctx, &combo, background, nk_vec2(nk_widget_width(ctx), 400))) {
                nk_layout_row_dynamic(ctx, 120, 1);
                background = nk_color_picker(ctx, background, NK_RGBA);
                nk_layout_row_dynamic(ctx, 25, 1);
                background.r = (nk_byte)nk_propertyi(ctx, "#R:", 0, background.r, 255, 1,1);
                background.g = (nk_byte)nk_propertyi(ctx, "#G:", 0, background.g, 255, 1,1);
                background.b = (nk_byte)nk_propertyi(ctx, "#B:", 0, background.b, 255, 1,1);
                background.a = (nk_byte)nk_propertyi(ctx, "#A:", 0, background.a, 255, 1,1);
                nk_combo_end(ctx);
            }}
        }
        nk_end(ctx);}

        /* -------------- EXAMPLES ---------------- */
        /*calculator(ctx);*/
        /*overview(ctx);*/
        node_editor(ctx);
        /* ----------------------------------------- */

        /* Draw */
        {float bg[4];
        nk_color_fv(bg, background);
        glfwGetWindowSize(win, &width, &height);
        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(bg[0], bg[1], bg[2], bg[3]);

        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDisableVertexAttribArray(0);

        /* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
         * with blending, scissor, face culling, depth test and viewport and
         * defaults everything back into a default state.
         * Make sure to either a.) save and restore or b.) reset your own state after
         * rendering the UI. */
        nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
        glfwSwapBuffers(win);}
    }
    nk_glfw3_shutdown();
    glfwTerminate();
    return 0;
}

<|endoftext|>


<commit_before>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"

using namespace lsh;

std::vector<bool> c(128);

BENCHMARK(vector, vector, 10000, 1000) {
  lsh::vector v(c);
}
<commit_msg>Add all vector benchmarks<commit_after>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"

using namespace lsh;

std::vector<bool> c(128);

vector u = vector::random(128);
vector v = vector::random(128);

BENCHMARK(vector, vector, 10000, 200) {
  lsh::vector v(c);
}

BENCHMARK(vector, size, 10000, 75000) {
  v.size();
}

BENCHMARK(vector, get, 10000, 18000) {
  v.get(64);
}

BENCHMARK(vector, equals, 10000, 10000) {
  bool f = v == u;
}

BENCHMARK(vector, dot_product, 10000, 10000) {
  v * u;
}

BENCHMARK(vector, and, 10000, 500) {
  v & u;
}

BENCHMARK(vector, hash, 10000, 28000) {
  v.hash();
}

BENCHMARK(vector, distance, 10000, 9000) {
  vector::distance(u, v);
}

BENCHMARK(vector, random, 10000, 10) {
  vector::random(128);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include <QtCore>
#include <QApplication>
#include <QtQuick>

#include "../src/cplugin.h"
#include "../src/cordova_config.hpp"

TEST(CordovaInternal, format_double_int_int) {
    auto t = std::make_tuple(1.1, 2, 3);
    auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
    EXPECT_EQ(doc.isArray(), true);
    EXPECT_EQ(doc.array().size(), 3);
    EXPECT_EQ(doc.array().at(1).toInt(), 2);
    EXPECT_EQ(doc.array().at(2).toInt(), 3);
    EXPECT_EQ(doc.array().at(0).toDouble(), 1.1);
}

TEST(CordovaInternal, format_obj_bool) {
    QVariantMap obj;
    obj.insert("a", 1);
    obj.insert("b", 2);
    obj.insert("c", "string");

    auto t = std::make_tuple(obj, true);
    auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());

    EXPECT_EQ(doc.isArray(), true);
    EXPECT_EQ(doc.array().size(), 2);
    EXPECT_EQ(doc.array().at(1).toBool(), true);

    auto o = doc.array().at(0).toObject();

    EXPECT_EQ(o.size(), 3);
    EXPECT_EQ(o.value("a").toInt(), 1);
    EXPECT_EQ(o.value("b").toInt(), 2);
    EXPECT_EQ(o.value("c").toString(), "string");
}

TEST(CordovaInternal, config) {
    CordovaInternal::Config config("../xml/config.xml");

    EXPECT_EQ(config.content(), "index.html");
    EXPECT_EQ(config.appId(), "io.cordova.helloCordova");
    EXPECT_EQ(config.appVersion(), "2.0.0");
    EXPECT_EQ(config.fullscreen(), false);
}

TEST(Cordova, WhiteList) {
    int argc = 0;
    QApplication app(argc, NULL);
    QQmlApplicationEngine view;
    view.addImportPath(QDir("./cordova_ubuntu/").absolutePath());

    QDir wwwDir("../tests/data/www");
    QDir workingDir = QApplication::applicationDirPath();
    view.rootContext()->setContextProperty("www", wwwDir.absolutePath());

    view.load(QUrl(QString("%1/cordova_ubuntu/qml/main.qml").arg(workingDir.absolutePath())));

    QTimer timer;
    timer.connect(&timer, &QTimer::timeout, [&]() {
        QApplication::quit();
    });
    timer.start(1000);

    EXPECT_EQ(app.exec(), 0);
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>add missing license header<commit_after>/*
 *  Copyright 2014 Canonical Ltd.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <iostream>
#include <gtest/gtest.h>
#include <QtCore>
#include <QApplication>
#include <QtQuick>

#include "../src/cplugin.h"
#include "../src/cordova_config.hpp"

TEST(CordovaInternal, format_double_int_int) {
    auto t = std::make_tuple(1.1, 2, 3);
    auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());
    EXPECT_EQ(doc.isArray(), true);
    EXPECT_EQ(doc.array().size(), 3);
    EXPECT_EQ(doc.array().at(1).toInt(), 2);
    EXPECT_EQ(doc.array().at(2).toInt(), 3);
    EXPECT_EQ(doc.array().at(0).toDouble(), 1.1);
}

TEST(CordovaInternal, format_obj_bool) {
    QVariantMap obj;
    obj.insert("a", 1);
    obj.insert("b", 2);
    obj.insert("c", "string");

    auto t = std::make_tuple(obj, true);
    auto doc = QJsonDocument().fromJson(QString("[ %1 ]").arg(CordovaInternal::tuple2str(t)).toUtf8());

    EXPECT_EQ(doc.isArray(), true);
    EXPECT_EQ(doc.array().size(), 2);
    EXPECT_EQ(doc.array().at(1).toBool(), true);

    auto o = doc.array().at(0).toObject();

    EXPECT_EQ(o.size(), 3);
    EXPECT_EQ(o.value("a").toInt(), 1);
    EXPECT_EQ(o.value("b").toInt(), 2);
    EXPECT_EQ(o.value("c").toString(), "string");
}

TEST(CordovaInternal, config) {
    CordovaInternal::Config config("../xml/config.xml");

    EXPECT_EQ(config.content(), "index.html");
    EXPECT_EQ(config.appId(), "io.cordova.helloCordova");
    EXPECT_EQ(config.appVersion(), "2.0.0");
    EXPECT_EQ(config.fullscreen(), false);
}

TEST(Cordova, WhiteList) {
    int argc = 0;
    QApplication app(argc, NULL);
    QQmlApplicationEngine view;
    view.addImportPath(QDir("./cordova_ubuntu/").absolutePath());

    QDir wwwDir("../tests/data/www");
    QDir workingDir = QApplication::applicationDirPath();
    view.rootContext()->setContextProperty("www", wwwDir.absolutePath());

    view.load(QUrl(QString("%1/cordova_ubuntu/qml/main.qml").arg(workingDir.absolutePath())));

    QTimer timer;
    timer.connect(&timer, &QTimer::timeout, [&]() {
        QApplication::quit();
    });
    timer.start(1000);

    EXPECT_EQ(app.exec(), 0);
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "MeshSprLoader.h"
#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "MeshIO.h"

#include <sprite2/Mesh.h>
#include <sprite2/MeshSprite.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MeshTriangle.h>
#include <simp/NodeMeshSpr.h>
#include <simp/from_int.h>

#include <assert.h>

namespace gum
{

MeshSprLoader::MeshSprLoader(s2::MeshSprite* spr)
	: m_spr(spr)
{
	if (m_spr) {
		m_spr->AddReference();
	}
}

MeshSprLoader::~MeshSprLoader()
{
	if (m_spr) {
		m_spr->RemoveReference();
	}
}

void MeshSprLoader::LoadJson(const Json::Value& val, const std::string& dir)
{
	if (!m_spr || !val.isMember("mesh")) {
		return;
	}

	const Json::Value& mesh_val = val["mesh"];

	s2::MeshTransform2& trans = m_spr->GetMeshTrans();
	const s2::Mesh* mesh = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol())->GetMesh();
	MeshIO::Load(mesh_val, trans, *mesh);
	trans.StoreToMesh(mesh);

	if (mesh_val.isMember("base_symbol")) {
		std::string base_path = FilepathHelper::Absolute(dir, mesh_val["base_symbol"].asString());
		s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
		m_spr->SetBaseSym(base_sym);
		base_sym->RemoveReference();
	}
}

void MeshSprLoader::LoadBin(const simp::NodeMeshSpr* node)
{
	if (!m_spr) {
		return;
	}

	s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
	m_spr->SetBaseSym(base_sym);
	base_sym->RemoveReference();

	assert(m_spr->GetSymbol()->Type() == s2::SYM_MESH);
	s2::MeshSymbol* mesh_sym = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol());
	s2::Mesh* mesh = mesh_sym->GetMesh();
	if (!mesh) {
		return;
	}

	s2::MeshTransform2& trans = m_spr->GetMeshTrans();
	trans.Clear();

	const std::vector<s2::MeshTriangle*>& tris = mesh->GetTriangles();
	int idx =0;
	for (int i = 0; i < node->n; ++i)
	{
		sm::vec2 f, t;
		f.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
		f.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
		t.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
		t.y = simp::int2float(int16_t(node->vertices[idx++]), 16);

		int idx = 0;
		sm::vec2 pos = t - f;
		for (int j = 0, m = tris.size(); j < m; ++j) {
			for (int k = 0; k < 3; ++k) {
				if (f == tris[j]->nodes[k]->ori_xy) {
					trans.Add(idx, pos);
				}
				++idx;
			}
		}
	}
	trans.StoreToMesh(mesh);
}

}<commit_msg>[FIXED] mesh spr trans loader<commit_after>#include "MeshSprLoader.h"
#include "MeshSymLoader.h"
#include "FilepathHelper.h"
#include "SymbolPool.h"
#include "MeshIO.h"

#include <sprite2/Mesh.h>
#include <sprite2/MeshSprite.h>
#include <sprite2/MeshSymbol.h>
#include <sprite2/MeshTriangle.h>
#include <simp/NodeMeshSpr.h>
#include <simp/from_int.h>

#include <assert.h>

namespace gum
{

MeshSprLoader::MeshSprLoader(s2::MeshSprite* spr)
	: m_spr(spr)
{
	if (m_spr) {
		m_spr->AddReference();
	}
}

MeshSprLoader::~MeshSprLoader()
{
	if (m_spr) {
		m_spr->RemoveReference();
	}
}

void MeshSprLoader::LoadJson(const Json::Value& val, const std::string& dir)
{
	if (!m_spr || !val.isMember("mesh")) {
		return;
	}

	const Json::Value& mesh_val = val["mesh"];

	s2::MeshTransform2& trans = m_spr->GetMeshTrans();
	const s2::Mesh* mesh = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol())->GetMesh();
	MeshIO::Load(mesh_val, trans, *mesh);
	trans.StoreToMesh(mesh);

	if (mesh_val.isMember("base_symbol")) {
		std::string base_path = FilepathHelper::Absolute(dir, mesh_val["base_symbol"].asString());
		s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(base_path);
		m_spr->SetBaseSym(base_sym);
		base_sym->RemoveReference();
	}
}

void MeshSprLoader::LoadBin(const simp::NodeMeshSpr* node)
{
	if (!m_spr) {
		return;
	}

	s2::Symbol* base_sym = SymbolPool::Instance()->Fetch(node->base_id);
	m_spr->SetBaseSym(base_sym);
	base_sym->RemoveReference();

	assert(m_spr->GetSymbol()->Type() == s2::SYM_MESH);
	s2::MeshSymbol* mesh_sym = VI_DOWNCASTING<s2::MeshSymbol*>(m_spr->GetSymbol());
	s2::Mesh* mesh = mesh_sym->GetMesh();
	if (!mesh) {
		return;
	}

	s2::MeshTransform2& trans = m_spr->GetMeshTrans();
	trans.Clear();

	const std::vector<s2::MeshTriangle*>& tris = mesh->GetTriangles();
	std::multimap<sm::vec2, int, sm::Vector2Cmp> map2idx;
	int idx = 0;
	for (int i = 0, n = tris.size(); i < n; ++i) {
		s2::MeshTriangle* tri = tris[i];
		for (int j = 0; j < 3; ++j) {
			map2idx.insert(std::make_pair(tri->nodes[j]->ori_xy, idx++));
		}
	}

	idx = 0;
	for (int i = 0, n = node->n / 2; i < n; ++i)
	{
		sm::vec2 f, t;
		f.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
		f.y = simp::int2float(int16_t(node->vertices[idx++]), 16);
		t.x = simp::int2float(int16_t(node->vertices[idx++]), 16);
		t.y = simp::int2float(int16_t(node->vertices[idx++]), 16);

		sm::vec2 pos = f - t;
		std::multimap<sm::vec2, int, sm::Vector2Cmp>::const_iterator
			itr_begin = map2idx.lower_bound(f),
			itr_end = map2idx.upper_bound(f);
		assert(itr_begin != map2idx.end());
		std::multimap<sm::vec2, int, sm::Vector2Cmp>::const_iterator itr = itr_begin;
		for ( ; itr != itr_end; ++itr) {
			trans.Add(itr->second, pos);
			break;	// todo
		}
	}
	trans.StoreToMesh(mesh);
}

}<|endoftext|>


<commit_before>#include <iostream>
#ifndef ELEMENTS_HYDROGEN_TO_OXYGEN_H
#define ELEMENTS_TO_HYDROHEN_TO_OXYGEN_H

/**denotes elements hrgrogen to argon starting with hydrogen=1
 /*takes enum and string file to do if and else work about number of bonds*/

    enum elements_hydrogen_to_argon t //element assignments std=c++11
    {
      HYDROGEN = 1,
      HELIUM,
      LITHIUM,
      BERRLYIUM,
      BORON,
      CARBON,
      NITROGEN,
      OXYGEN,
      FLUORINE,
      NEON,
      SODIUM,
      MAGNESIUM,
      ALUMINUM,
      SILICON,
      PHOSPHOROUS,
      SULFUR,
      CHLORINE,
      ARGON
    };

    string elements_to_string (elements_hydrogen_to_argon d) //numbers to element assignments
    {
    if (element == Hydrogen    ) return "Hydrogen";
    if (element == Helium      ) return "Helium";
    if (element == Lithium     ) return "Lithium";
    if (element == Berrylium   ) return "Berrylium";
    if (element == Boron       ) return "Boron";
    if (element == Carbon      ) return "Carbon";
    if (element == Nitrogen    ) return "Nitrogen";
    if (element == Oxygen      ) return "Oxygen";
    if (element == Fluorine    ) return "Fluorine";
    if (element == Neon        ) return "Neon";
    if (element == Sodium      ) return "Sodium";
    if (element == Magenesium  ) return "Magnesium";
    if (element == Aluminum    ) return "Aluminum";
    if (element == Silicon     ) return "Silicon";
    if (element == Phosphourous) return "Phosphorous";
    if (element == Sulfur      ) return "Sulfur";
    if (element == Chlorine    ) return "Chlorine";
    if (element == Argon       ) return "Argon"
    }
<commit_msg>Delete number_bonds.cpp<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief application simple user and session management feature
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "ApplicationAdminServer.h"

#include "build.h"

#include "Admin/RestAdminFeConfigurationHandler.h"
#include "Admin/RestAdminLogHandler.h"
#include "Admin/RestHandlerCreator.h"
#include "Basics/ProgramOptionsDescription.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "HttpServer/PathHandler.h"
#include "Logger/Logger.h"
#include "Rest/HttpResponse.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;

// -----------------------------------------------------------------------------
// --SECTION--                                             static public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new feature
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer* ApplicationAdminServer::create (ApplicationServer*) {
  return new ApplicationAdminServer();
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer::ApplicationAdminServer ()
  : _allowLogViewer(false),
    _allowAdminDirectory(false),
    _allowFeConfiguration(false),
    _allowVersion(false),
    _adminDirectory(),
    _pathOptions(0),
    _feConfiguration(),
    _name(),
    _version(),
    _versionDataDirect(0),
    _versionDataQueued(0) {
  _pathOptions = new PathHandler::Options();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer::~ApplicationAdminServer () {
  delete reinterpret_cast<PathHandler::Options*>(_pathOptions);

  if (_versionDataDirect != 0) {
    delete _versionDataDirect;
  }

  if (_versionDataQueued != 0) {
    delete _versionDataQueued;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief add a log viewer
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowLogViewer () {
  _allowLogViewer = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowAdminDirectory () {
  _allowAdminDirectory = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowAdminDirectory (string const& adminDirectory) {
  _allowAdminDirectory = true;
  _adminDirectory = adminDirectory;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a front-end configuration
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowFeConfiguration () {
  _allowFeConfiguration = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler using the default version
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowVersion () {
  _allowVersion = true;
  _version = TRIAGENS_VERSION;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowVersion (string name, string version) {
  _allowVersion = true;
  _name = name;
  _version = version;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::addBasicHandlers (HttpHandlerFactory* factory, string const& prefix) {
  if (_allowVersion) {
    if (!_versionDataDirect) {
      _versionDataDirect = new RestVersionHandler::version_options_t;
      _versionDataDirect->_name = _name;
      _versionDataDirect->_version = _version;
      _versionDataDirect->_isDirect = true;
    }

    factory->addHandler(prefix + "/version",
                        RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
                        (void*) _versionDataDirect);

    if (!_versionDataQueued) {
      _versionDataQueued = new RestVersionHandler::version_options_t;
      _versionDataQueued->_name = _name;
      _versionDataQueued->_version = _version;
      _versionDataQueued->_isDirect = false;
      _versionDataQueued->_queue = "STANDARD";
    }

    factory->addHandler(prefix + "/queued/version",
                        RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
                        (void*) _versionDataQueued);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers for administration
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::addHandlers (HttpHandlerFactory* factory, string const& prefix) {

  // .............................................................................
  // add log viewer
  // .............................................................................

  if (_allowLogViewer) {
    factory->addHandler(prefix + "/log", RestHandlerCreator<RestAdminLogHandler>::createNoData, 0);
  }

  // .............................................................................
  // add a web-admin directory
  // .............................................................................

  if (_allowAdminDirectory) {
    if (! _adminDirectory.empty()) {
      LOGGER_INFO << "using JavaScript front-end files stored at '" << _adminDirectory << "'";

      reinterpret_cast<PathHandler::Options*>(_pathOptions)->path = _adminDirectory;
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->contentType = "text/plain";
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->allowSymbolicLink = false;
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->defaultFile = "index.html";

      factory->addPrefixHandler(prefix + "/html", RestHandlerCreator<PathHandler>::createData<PathHandler::Options*>, _pathOptions);
    }
  }

  // .............................................................................
  // add a front-end configuration
  // .............................................................................

  if (_allowFeConfiguration) {
    factory->addHandler(prefix + "/fe-configuration",
                        RestHandlerCreator<RestAdminFeConfigurationHandler>::createData<char const*>,
                        (void*) _feConfiguration.c_str());
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                        ApplicationFeature methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::setupOptions (map<string, basics::ProgramOptionsDescription>& options) {
  if (_allowAdminDirectory) {
    options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
      ("server.admin-directory", &_adminDirectory, "directory containing the ADMIN front-end")
    ;
  }

  if (_allowFeConfiguration) {
    options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
      ("server.fe-configuration", &_feConfiguration, "file to store the front-end preferences")
    ;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>added /queued-version<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief application simple user and session management feature
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2011-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "ApplicationAdminServer.h"

#include "build.h"

#include "Admin/RestAdminFeConfigurationHandler.h"
#include "Admin/RestAdminLogHandler.h"
#include "Admin/RestHandlerCreator.h"
#include "Basics/ProgramOptionsDescription.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "HttpServer/PathHandler.h"
#include "Logger/Logger.h"
#include "Rest/HttpResponse.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;

// -----------------------------------------------------------------------------
// --SECTION--                                             static public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief creates a new feature
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer* ApplicationAdminServer::create (ApplicationServer*) {
  return new ApplicationAdminServer();
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer::ApplicationAdminServer ()
  : _allowLogViewer(false),
    _allowAdminDirectory(false),
    _allowFeConfiguration(false),
    _allowVersion(false),
    _adminDirectory(),
    _pathOptions(0),
    _feConfiguration(),
    _name(),
    _version(),
    _versionDataDirect(0),
    _versionDataQueued(0) {
  _pathOptions = new PathHandler::Options();
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

ApplicationAdminServer::~ApplicationAdminServer () {
  delete reinterpret_cast<PathHandler::Options*>(_pathOptions);

  if (_versionDataDirect != 0) {
    delete _versionDataDirect;
  }

  if (_versionDataQueued != 0) {
    delete _versionDataQueued;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief add a log viewer
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowLogViewer () {
  _allowLogViewer = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowAdminDirectory () {
  _allowAdminDirectory = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a webadmin directory
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowAdminDirectory (string const& adminDirectory) {
  _allowAdminDirectory = true;
  _adminDirectory = adminDirectory;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a front-end configuration
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowFeConfiguration () {
  _allowFeConfiguration = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler using the default version
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowVersion () {
  _allowVersion = true;
  _version = TRIAGENS_VERSION;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief allows for a version handler
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::allowVersion (string name, string version) {
  _allowVersion = true;
  _name = name;
  _version = version;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::addBasicHandlers (HttpHandlerFactory* factory, string const& prefix) {
  if (_allowVersion) {
    if (!_versionDataDirect) {
      _versionDataDirect = new RestVersionHandler::version_options_t;
      _versionDataDirect->_name = _name;
      _versionDataDirect->_version = _version;
      _versionDataDirect->_isDirect = true;
    }

    factory->addHandler(prefix + "/version",
                        RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
                        (void*) _versionDataDirect);

    if (!_versionDataQueued) {
      _versionDataQueued = new RestVersionHandler::version_options_t;
      _versionDataQueued->_name = _name;
      _versionDataQueued->_version = _version;
      _versionDataQueued->_isDirect = false;
      _versionDataQueued->_queue = "STANDARD";
    }

    factory->addHandler(prefix + "/queued-version",
                        RestHandlerCreator<RestVersionHandler>::createData<RestVersionHandler::version_options_t const*>,
                        (void*) _versionDataQueued);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief adds the http handlers for administration
///
/// Note that the server does not claim ownership of the factory.
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::addHandlers (HttpHandlerFactory* factory, string const& prefix) {

  // .............................................................................
  // add log viewer
  // .............................................................................

  if (_allowLogViewer) {
    factory->addHandler(prefix + "/log", RestHandlerCreator<RestAdminLogHandler>::createNoData, 0);
  }

  // .............................................................................
  // add a web-admin directory
  // .............................................................................

  if (_allowAdminDirectory) {
    if (! _adminDirectory.empty()) {
      LOGGER_INFO << "using JavaScript front-end files stored at '" << _adminDirectory << "'";

      reinterpret_cast<PathHandler::Options*>(_pathOptions)->path = _adminDirectory;
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->contentType = "text/plain";
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->allowSymbolicLink = false;
      reinterpret_cast<PathHandler::Options*>(_pathOptions)->defaultFile = "index.html";

      factory->addPrefixHandler(prefix + "/html", RestHandlerCreator<PathHandler>::createData<PathHandler::Options*>, _pathOptions);
    }
  }

  // .............................................................................
  // add a front-end configuration
  // .............................................................................

  if (_allowFeConfiguration) {
    factory->addHandler(prefix + "/fe-configuration",
                        RestHandlerCreator<RestAdminFeConfigurationHandler>::createData<char const*>,
                        (void*) _feConfiguration.c_str());
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                        ApplicationFeature methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup RestServer
/// @{
////////////////////////////////////////////////////////////////////////////////

void ApplicationAdminServer::setupOptions (map<string, basics::ProgramOptionsDescription>& options) {
  if (_allowAdminDirectory) {
    options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
      ("server.admin-directory", &_adminDirectory, "directory containing the ADMIN front-end")
    ;
  }

  if (_allowFeConfiguration) {
    options[ApplicationServer::OPTIONS_SERVER + ":help-admin"]
      ("server.fe-configuration", &_feConfiguration, "file to store the front-end preferences")
    ;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//

#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "AlphaTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include <iostream>
using namespace llvm;

namespace {
  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");

  struct VISIBILITY_HIDDEN AlphaAsmPrinter : public AsmPrinter {

    /// Unique incrementer for label values for referencing Global values.
    ///
    unsigned LabelNumber;

    AlphaAsmPrinter(std::ostream &o, TargetMachine &tm, const TargetAsmInfo *T)
       : AsmPrinter(o, tm, T), LabelNumber(0) {
    }

    /// We name each basic block in a Function with a unique number, so
    /// that we can consistently refer to them later. This is cleared
    /// at the beginning of each call to runOnMachineFunction().
    ///
    typedef std::map<const Value *, unsigned> ValueMapTy;
    ValueMapTy NumberForBB;
    std::string CurSection;

    virtual const char *getPassName() const {
      return "Alpha Assembly Printer";
    }
    bool printInstruction(const MachineInstr *MI);
    void printOp(const MachineOperand &MO, bool IsCallOp = false);
    void printOperand(const MachineInstr *MI, int opNum);
    void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
    void printMachineInstruction(const MachineInstr *MI);
    bool runOnMachineFunction(MachineFunction &F);
    bool doInitialization(Module &M);
    bool doFinalization(Module &M);

    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
                         unsigned AsmVariant, const char *ExtraCode);
    bool PrintAsmMemoryOperand(const MachineInstr *MI,
			       unsigned OpNo,
			       unsigned AsmVariant,
			       const char *ExtraCode);
  };
} // end of anonymous namespace

/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description.  This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o,
                                                  TargetMachine &tm) {
  return new AlphaAsmPrinter(o, tm, tm.getTargetAsmInfo());
}

#include "AlphaGenAsmWriter.inc"

void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum)
{
  const MachineOperand &MO = MI->getOperand(opNum);
  if (MO.getType() == MachineOperand::MO_Register) {
    assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
    O << TM.getRegisterInfo()->get(MO.getReg()).Name;
  } else if (MO.isImmediate()) {
    O << MO.getImmedValue();
    assert(MO.getImmedValue() < (1 << 30));
  } else {
    printOp(MO);
  }
}

void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
  const MRegisterInfo &RI = *TM.getRegisterInfo();
  int new_symbol;

  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    O << RI.get(MO.getReg()).Name;
    return;

  case MachineOperand::MO_Immediate:
    std::cerr << "printOp() does not handle immediate values\n";
    abort();
    return;

  case MachineOperand::MO_MachineBasicBlock:
    printBasicBlockLabel(MO.getMachineBasicBlock());
    return;

  case MachineOperand::MO_ConstantPoolIndex:
    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
      << MO.getConstantPoolIndex();
    return;

  case MachineOperand::MO_ExternalSymbol:
    O << MO.getSymbolName();
    return;

  case MachineOperand::MO_GlobalAddress:
    O << Mang->getValueName(MO.getGlobal());
    return;

  case MachineOperand::MO_JumpTableIndex:
    O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
      << '_' << MO.getJumpTableIndex();
    return;

  default:
    O << "<unknown operand type: " << MO.getType() << ">";
    return;
  }
}

/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
  ++EmittedInsts;
  if (printInstruction(MI))
    return; // Printer was automatically generated

  assert(0 && "Unhandled instruction in asm writer!");
  abort();
  return;
}

/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  SetupMachineFunction(MF);
  O << "\n\n";

  // Print out constants referenced by the function
  EmitConstantPool(MF.getConstantPool());

  // Print out jump tables referenced by the function
  EmitJumpTableInfo(MF.getJumpTableInfo());

  // Print out labels for the function.
  const Function *F = MF.getFunction();
  SwitchToTextSection(".text", F);
  EmitAlignment(4, F);
  switch (F->getLinkage()) {
  default: assert(0 && "Unknown linkage type!");
  case Function::InternalLinkage:  // Symbols default to internal.
    break;
   case Function::ExternalLinkage:
     O << "\t.globl " << CurrentFnName << "\n";
     break;
  case Function::WeakLinkage:
  case Function::LinkOnceLinkage:
    O << "\t.weak " << CurrentFnName << "\n";
    break;
  }

  O << "\t.ent " << CurrentFnName << "\n";

  O << CurrentFnName << ":\n";

  // Print out code for the function.
  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
       I != E; ++I) {
    printBasicBlockLabel(I, true);
    O << '\n';
    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
         II != E; ++II) {
      // Print the assembly for the instruction.
      O << "\t";
      printMachineInstruction(II);
    }
  }
  ++LabelNumber;

  O << "\t.end " << CurrentFnName << "\n";

  // We didn't modify anything.
  return false;
}

bool AlphaAsmPrinter::doInitialization(Module &M)
{
  AsmPrinter::doInitialization(M);
  if(TM.getSubtarget<AlphaSubtarget>().hasF2I()
     || TM.getSubtarget<AlphaSubtarget>().hasCT())
    O << "\t.arch ev6\n";
  else
    O << "\t.arch ev56\n";
  O << "\t.set noat\n";
  return false;
}

bool AlphaAsmPrinter::doFinalization(Module &M) {
  const TargetData *TD = TM.getTargetData();

  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    if (I->hasInitializer()) {   // External global require no code
      // Check to see if this is a special global used by LLVM, if so, emit it.
      if (EmitSpecialLLVMGlobal(I))
        continue;

      O << "\n\n";
      std::string name = Mang->getValueName(I);
      Constant *C = I->getInitializer();
      unsigned Size = TD->getTypeSize(C->getType());
      //      unsigned Align = TD->getTypeAlignmentShift(C->getType());
      unsigned Align = getPreferredAlignmentLog(I);

      if (C->isNullValue() &&
          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
        SwitchToDataSection("\t.section .data", I);
        if (I->hasInternalLinkage())
          O << "\t.local " << name << "\n";

        O << "\t.comm " << name << "," << TD->getTypeSize(C->getType())
          << "," << (1 << Align)
          <<  "\n";
      } else {
        switch (I->getLinkage()) {
        case GlobalValue::LinkOnceLinkage:
        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
          // Nonnull linkonce -> weak
          O << "\t.weak " << name << "\n";
          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
          SwitchToDataSection("", I);
          break;
        case GlobalValue::AppendingLinkage:
          // FIXME: appending linkage variables should go into a section of
          // their name or something.  For now, just emit them as external.
        case GlobalValue::ExternalLinkage:
          // If external or appending, declare as a global symbol
          O << "\t.globl " << name << "\n";
          // FALL THROUGH
        case GlobalValue::InternalLinkage:
          SwitchToDataSection(C->isNullValue() ? "\t.section .bss" :
                              "\t.section .data", I);
          break;
        case GlobalValue::GhostLinkage:
          std::cerr << "GhostLinkage cannot appear in AlphaAsmPrinter!\n";
          abort();
        case GlobalValue::DLLImportLinkage:
          std::cerr << "DLLImport linkage is not supported by this target!\n";
          abort();
        case GlobalValue::DLLExportLinkage:
          std::cerr << "DLLExport linkage is not supported by this target!\n";
          abort();
        default:
          assert(0 && "Unknown linkage type!");
        }

        EmitAlignment(Align);
        O << "\t.type " << name << ",@object\n";
        O << "\t.size " << name << "," << Size << "\n";
        O << name << ":\n";
        EmitGlobalConstant(C);
      }
    }

  AsmPrinter::doFinalization(M);
  return false;
}

/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool AlphaAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
                                    unsigned AsmVariant,
                                    const char *ExtraCode) {
  printOperand(MI, OpNo);
  return false;
}

bool AlphaAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
					    unsigned OpNo,
					    unsigned AsmVariant,
					    const char *ExtraCode) {
  if (ExtraCode && ExtraCode[0])
    return true; // Unknown modifier.
  O << "0(";
  printOperand(MI, OpNo);
  O << ")";
  return false;
}
<commit_msg>use getSectionForFunction to decide which section to emit code into<commit_after>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//

#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "AlphaTargetMachine.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include <iostream>
using namespace llvm;

namespace {
  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");

  struct VISIBILITY_HIDDEN AlphaAsmPrinter : public AsmPrinter {

    /// Unique incrementer for label values for referencing Global values.
    ///
    unsigned LabelNumber;

    AlphaAsmPrinter(std::ostream &o, TargetMachine &tm, const TargetAsmInfo *T)
       : AsmPrinter(o, tm, T), LabelNumber(0) {
    }

    /// We name each basic block in a Function with a unique number, so
    /// that we can consistently refer to them later. This is cleared
    /// at the beginning of each call to runOnMachineFunction().
    ///
    typedef std::map<const Value *, unsigned> ValueMapTy;
    ValueMapTy NumberForBB;
    std::string CurSection;

    virtual const char *getPassName() const {
      return "Alpha Assembly Printer";
    }
    bool printInstruction(const MachineInstr *MI);
    void printOp(const MachineOperand &MO, bool IsCallOp = false);
    void printOperand(const MachineInstr *MI, int opNum);
    void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
    void printMachineInstruction(const MachineInstr *MI);
    bool runOnMachineFunction(MachineFunction &F);
    bool doInitialization(Module &M);
    bool doFinalization(Module &M);

    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
                         unsigned AsmVariant, const char *ExtraCode);
    bool PrintAsmMemoryOperand(const MachineInstr *MI,
			       unsigned OpNo,
			       unsigned AsmVariant,
			       const char *ExtraCode);
  };
} // end of anonymous namespace

/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description.  This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass(std::ostream &o,
                                               TargetMachine &tm) {
  return new AlphaAsmPrinter(o, tm, tm.getTargetAsmInfo());
}

#include "AlphaGenAsmWriter.inc"

void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum)
{
  const MachineOperand &MO = MI->getOperand(opNum);
  if (MO.getType() == MachineOperand::MO_Register) {
    assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
    O << TM.getRegisterInfo()->get(MO.getReg()).Name;
  } else if (MO.isImmediate()) {
    O << MO.getImmedValue();
    assert(MO.getImmedValue() < (1 << 30));
  } else {
    printOp(MO);
  }
}

void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
  const MRegisterInfo &RI = *TM.getRegisterInfo();
  int new_symbol;

  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    O << RI.get(MO.getReg()).Name;
    return;

  case MachineOperand::MO_Immediate:
    std::cerr << "printOp() does not handle immediate values\n";
    abort();
    return;

  case MachineOperand::MO_MachineBasicBlock:
    printBasicBlockLabel(MO.getMachineBasicBlock());
    return;

  case MachineOperand::MO_ConstantPoolIndex:
    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
      << MO.getConstantPoolIndex();
    return;

  case MachineOperand::MO_ExternalSymbol:
    O << MO.getSymbolName();
    return;

  case MachineOperand::MO_GlobalAddress:
    O << Mang->getValueName(MO.getGlobal());
    return;

  case MachineOperand::MO_JumpTableIndex:
    O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
      << '_' << MO.getJumpTableIndex();
    return;

  default:
    O << "<unknown operand type: " << MO.getType() << ">";
    return;
  }
}

/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
  ++EmittedInsts;
  if (printInstruction(MI))
    return; // Printer was automatically generated

  assert(0 && "Unhandled instruction in asm writer!");
  abort();
  return;
}

/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  SetupMachineFunction(MF);
  O << "\n\n";

  // Print out constants referenced by the function
  EmitConstantPool(MF.getConstantPool());

  // Print out jump tables referenced by the function
  EmitJumpTableInfo(MF.getJumpTableInfo());

  // Print out labels for the function.
  const Function *F = MF.getFunction();
  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);

  EmitAlignment(4, F);
  switch (F->getLinkage()) {
  default: assert(0 && "Unknown linkage type!");
  case Function::InternalLinkage:  // Symbols default to internal.
    break;
   case Function::ExternalLinkage:
     O << "\t.globl " << CurrentFnName << "\n";
     break;
  case Function::WeakLinkage:
  case Function::LinkOnceLinkage:
    O << "\t.weak " << CurrentFnName << "\n";
    break;
  }

  O << "\t.ent " << CurrentFnName << "\n";

  O << CurrentFnName << ":\n";

  // Print out code for the function.
  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
       I != E; ++I) {
    printBasicBlockLabel(I, true);
    O << '\n';
    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
         II != E; ++II) {
      // Print the assembly for the instruction.
      O << "\t";
      printMachineInstruction(II);
    }
  }
  ++LabelNumber;

  O << "\t.end " << CurrentFnName << "\n";

  // We didn't modify anything.
  return false;
}

bool AlphaAsmPrinter::doInitialization(Module &M)
{
  AsmPrinter::doInitialization(M);
  if(TM.getSubtarget<AlphaSubtarget>().hasF2I()
     || TM.getSubtarget<AlphaSubtarget>().hasCT())
    O << "\t.arch ev6\n";
  else
    O << "\t.arch ev56\n";
  O << "\t.set noat\n";
  return false;
}

bool AlphaAsmPrinter::doFinalization(Module &M) {
  const TargetData *TD = TM.getTargetData();

  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    if (I->hasInitializer()) {   // External global require no code
      // Check to see if this is a special global used by LLVM, if so, emit it.
      if (EmitSpecialLLVMGlobal(I))
        continue;

      O << "\n\n";
      std::string name = Mang->getValueName(I);
      Constant *C = I->getInitializer();
      unsigned Size = TD->getTypeSize(C->getType());
      //      unsigned Align = TD->getTypeAlignmentShift(C->getType());
      unsigned Align = getPreferredAlignmentLog(I);

      if (C->isNullValue() &&
          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
        SwitchToDataSection("\t.section .data", I);
        if (I->hasInternalLinkage())
          O << "\t.local " << name << "\n";

        O << "\t.comm " << name << "," << TD->getTypeSize(C->getType())
          << "," << (1 << Align)
          <<  "\n";
      } else {
        switch (I->getLinkage()) {
        case GlobalValue::LinkOnceLinkage:
        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
          // Nonnull linkonce -> weak
          O << "\t.weak " << name << "\n";
          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
          SwitchToDataSection("", I);
          break;
        case GlobalValue::AppendingLinkage:
          // FIXME: appending linkage variables should go into a section of
          // their name or something.  For now, just emit them as external.
        case GlobalValue::ExternalLinkage:
          // If external or appending, declare as a global symbol
          O << "\t.globl " << name << "\n";
          // FALL THROUGH
        case GlobalValue::InternalLinkage:
          SwitchToDataSection(C->isNullValue() ? "\t.section .bss" :
                              "\t.section .data", I);
          break;
        case GlobalValue::GhostLinkage:
          std::cerr << "GhostLinkage cannot appear in AlphaAsmPrinter!\n";
          abort();
        case GlobalValue::DLLImportLinkage:
          std::cerr << "DLLImport linkage is not supported by this target!\n";
          abort();
        case GlobalValue::DLLExportLinkage:
          std::cerr << "DLLExport linkage is not supported by this target!\n";
          abort();
        default:
          assert(0 && "Unknown linkage type!");
        }

        EmitAlignment(Align);
        O << "\t.type " << name << ",@object\n";
        O << "\t.size " << name << "," << Size << "\n";
        O << name << ":\n";
        EmitGlobalConstant(C);
      }
    }

  AsmPrinter::doFinalization(M);
  return false;
}

/// PrintAsmOperand - Print out an operand for an inline asm expression.
///
bool AlphaAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
                                    unsigned AsmVariant,
                                    const char *ExtraCode) {
  printOperand(MI, OpNo);
  return false;
}

bool AlphaAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
					    unsigned OpNo,
					    unsigned AsmVariant,
					    const char *ExtraCode) {
  if (ExtraCode && ExtraCode[0])
    return true; // Unknown modifier.
  O << "0(";
  printOperand(MI, OpNo);
  O << ")";
  return false;
}
<|endoftext|>