<commit_before>#include <stdio.h>

#include <Parser.h>
#include <Node.h>
#include <DeclareClass.h>
#include <DeclareVar.h>
#include <DeclareFunc.h>
#include <Type.h>
#include <Ident.h>

#include "SnowyTestSuite.h"

using namespace Snowy;

static const Node* build_graph(string code)
{
    Log("Test").debug("Building:\n---\n%s---", code.c_str());
    std::stringstream ins;
    ins << code;

    Parser parser;
    const Node *root = parser.parse(ins);
    s_assert_notnull(root);
    return root;
}

static void assert_code_desc(const char *code, const string& expected)
{
    std::stringstream ins;
    ins << code;

    Parser parser;
    const Node *root = build_graph(string(code));

    const string& actual = root->to_program_string();
    s_assert_cmpstr(actual, expected);

    delete root;
}

void string_literal_test(void)
{
    assert_code_desc("\"abc\"\n", "StringLiteral=[\"abc\"]\n");
}

void int_literal_test(void)
{
    assert_code_desc("1\n", "IntLiteral=[1]\n");
}

void multi_node_test(void)
{
    assert_code_desc("1\n2\n3\n", "IntLiteral=[1]\nIntLiteral=[2]\nIntLiteral=[3]\n");
}

void arithmetic_expr_test(void)
{
    const char *code = "1 + 2\n";
    const char *desc = "Tuple=[lhs=[IntLiteral=[1]] op=[+] rhs=[IntLiteral=[2]]]\n";
    assert_code_desc(code, desc);
}

void assignment_test(void)
{
    const char *code = "a = 1 + 2\n";
    const char *desc = "DeclareVar=[ident=[Ident[a type=Integer]] expr=[Tuple=[lhs=[IntLiteral=[1]] op=[+] rhs=[IntLiteral=[2]]]]]\n";
    assert_code_desc(code, desc);
}

void string_assignment_test(void)
{
    const char *code = "a = \"this is a test\"\n";
    const char *desc = "DeclareVar=[ident=[Ident[a type=String]] expr=[StringLiteral=[\"this is a test\"]]]\n";
    assert_code_desc(code, desc);
}

void multi_assignment_test(void)
{
    // TODO
}

void func_no_args(void)
{
    const char *code = "def add() do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=0]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_one_arg(void)
{
    const char *code = "def add(one) do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=1 arg0=[Ident[one]]]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_two_args(void)
{
    const char *code = "def add(one, two) do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=2 arg0=[Ident[one]] arg1=[Ident[two]]]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_body_one_line(void)
{
    const char *code = "def test() do\n1\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[test]] args=[ArgsDecl[size=0]] block=[\n IntLiteral=[1]\n]]\n";
    assert_code_desc(code, desc);
}

void func_body_multi_line(void)
{
    const char *code = "def test() do\n1\n2\n3\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[test]] args=[ArgsDecl[size=0]] block=[\n IntLiteral=[1]\n IntLiteral=[2]\n IntLiteral=[3]\n]]\n";
    assert_code_desc(code, desc);
}

static void empty_line_test(void)
{
    assert_code_desc(R"snow(

        1
    )snow", "IntLiteral=[1]\n");
}

static void comment_full_line_test(void)
{
    assert_code_desc(R"snow(
        # 1
        1
    )snow", "IntLiteral=[1]\n");
}

static void comment_part_line_test(void)
{
    assert_code_desc(R"snow(
        1 # 2
    )snow", "IntLiteral=[1]\n");
}

static void class_declare_empty(void)
{
    assert_code_desc(R"snow(
        class MyClass do
        end
    )snow", "DeclareClass=[type=[Type[MyClass]]]\n");
}

static void class_declare_with_var(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          i = 0
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 1);

    DeclareVar *var = c->getVars()[0];
    s_assert_cmpstr(var->to_program_string(), "DeclareVar=[ident=[Ident[i type=Integer]] expr=[IntLiteral=[0]]]\n");

    delete n;
}

static void class_declare_with_var_no_spaces(void)
{
    const Node *n = build_graph("class MyClass do\ni = 0\nend\n");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 1);

    DeclareVar *var = c->getVars()[0];
    s_assert_cmpstr(var->to_program_string(), "DeclareVar=[ident=[Ident[i type=Integer]] expr=[IntLiteral=[0]]]\n");
}

static void class_declare_with_two_vars(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          a = 0
          b = 0
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    cout << c->getClassType().getNodeId() << "\n";
    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 2);

    DeclareVar& a = *c->getVars()[0];
    s_assert_cmpstr(a.to_program_string(), "DeclareVar=[ident=[Ident[a type=Integer]] expr=[IntLiteral=[0]]]\n");

    DeclareVar& b = *c->getVars()[1];
    s_assert_cmpstr(b.to_program_string(), "DeclareVar=[ident=[Ident[b type=Integer]] expr=[IntLiteral=[0]]]\n");

    delete n;
}

static void class_declare_with_func(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          def myfunc() do
          end
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getFuncs().size() == 1);

    DeclareFunc& func = *c->getFuncs()[0];
    s_assert_cmpstr(func.getName(), "myfunc");

    delete n;
}

static void class_declare_with_two_funcs(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          def firstFunc() do
            a = 0
          end
          def secondFunc() do
            b = 0
          end
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getFuncs().size() == 2);

    DeclareFunc& first_func = *c->getFuncs()[0];
    s_assert_cmpstr(first_func.getName(), "firstFunc");

    DeclareFunc& second_func = *c->getFuncs()[1];
    s_assert_cmpstr(second_func.getName(), "secondFunc");

    delete n;
}

static void type_static()
{
    const Node *n = build_graph("Integer:i = 0");
    s_assert(n->isNodeType(DECLARE_VAR));

    const DeclareVar& decl = *(DeclareVar*)n;
    const Ident& i = decl.getIdent();
    s_assert_cmpstr(i.getName()->c_str(), "i");

    s_assert_notnull(Type::Integer);
    s_assert_notnull(i.getType());
    s_assert(i.getType() == Type::Integer);

    delete n;
}

static void type_inference_assignment_test()
{
    const Node *n = build_graph("i = 0");
    s_assert(n->isNodeType(DECLARE_VAR));

    const DeclareVar& decl = *(DeclareVar*)n;
    const Ident& i = decl.getIdent();

    s_assert_notnull(Type::Integer);
    s_assert_notnull(i.getType());
    s_assert(i.getType() == Type::Integer);

    delete n;
}

void parser_tests(TestSuite& tests)
{
    tests.add("/Parser/int_literal", int_literal_test);
    tests.add("/Parser/string_literal", string_literal_test);
    tests.add("/Parser/multi_node", multi_node_test);
    tests.add("/Parser/arithmetic_expr_test", arithmetic_expr_test);
    tests.add("/Parser/assignment_test", assignment_test);
    tests.add("/Parser/string_assignment_test", string_assignment_test);
    tests.add("/Parser/multi_assignment_test", multi_assignment_test);
    tests.add("/Parser/func/no_args", func_no_args);
    tests.add("/Parser/func/one_arg", func_one_arg);
    tests.add("/Parser/func/two_args", func_two_args);
    tests.add("/Parser/func/body_one_line", func_body_one_line);
    tests.add("/Parser/func/body_multi_line", func_body_multi_line);
    tests.add("/Parser/empty_line", empty_line_test);
    tests.add("/Parser/comment/full_line", comment_full_line_test);
    tests.add("/Parser/comment/part_line", comment_part_line_test);
    tests.add("/Parser/class/empty", class_declare_empty);
    tests.add("/Parser/class/with_var", class_declare_with_var);
    tests.add("/Parser/class/with_var_no_spaces", class_declare_with_var_no_spaces);
    tests.add("/Parser/class/with_two_vars", class_declare_with_two_vars);
    tests.add("/Parser/class/with_func", class_declare_with_func);
    tests.add("/Parser/class/with_two_funcs", class_declare_with_two_funcs);
    tests.add("/Parser/type/static", type_static);
    tests.add("/Parser/type/assignment_inference", type_inference_assignment_test);
}
<commit_msg>Fix memory leaks down to 246 allocation(s)<commit_after>#include <stdio.h>

#include <Parser.h>
#include <Node.h>
#include <DeclareClass.h>
#include <DeclareVar.h>
#include <DeclareFunc.h>
#include <Type.h>
#include <Ident.h>

#include "SnowyTestSuite.h"

using namespace Snowy;

static const Node* build_graph(string code)
{
    Log("Test").debug("Building:\n---\n%s---", code.c_str());
    std::stringstream ins;
    ins << code;

    Parser parser;
    const Node *root = parser.parse(ins);
    s_assert_notnull(root);
    return root;
}

static void assert_code_desc(const char *code, const string& expected)
{
    std::stringstream ins;
    ins << code;

    Parser parser;
    const Node *root = build_graph(string(code));

    const string& actual = root->to_program_string();
    s_assert_cmpstr(actual, expected);

    delete root;
}

void string_literal_test(void)
{
    assert_code_desc("\"abc\"\n", "StringLiteral=[\"abc\"]\n");
}

void int_literal_test(void)
{
    assert_code_desc("1\n", "IntLiteral=[1]\n");
}

void multi_node_test(void)
{
    assert_code_desc("1\n2\n3\n", "IntLiteral=[1]\nIntLiteral=[2]\nIntLiteral=[3]\n");
}

void arithmetic_expr_test(void)
{
    const char *code = "1 + 2\n";
    const char *desc = "Tuple=[lhs=[IntLiteral=[1]] op=[+] rhs=[IntLiteral=[2]]]\n";
    assert_code_desc(code, desc);
}

void assignment_test(void)
{
    const char *code = "a = 1 + 2\n";
    const char *desc = "DeclareVar=[ident=[Ident[a type=Integer]] expr=[Tuple=[lhs=[IntLiteral=[1]] op=[+] rhs=[IntLiteral=[2]]]]]\n";
    assert_code_desc(code, desc);
}

void string_assignment_test(void)
{
    const char *code = "a = \"this is a test\"\n";
    const char *desc = "DeclareVar=[ident=[Ident[a type=String]] expr=[StringLiteral=[\"this is a test\"]]]\n";
    assert_code_desc(code, desc);
}

void multi_assignment_test(void)
{
    // TODO
}

void func_no_args(void)
{
    const char *code = "def add() do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=0]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_one_arg(void)
{
    const char *code = "def add(one) do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=1 arg0=[Ident[one]]]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_two_args(void)
{
    const char *code = "def add(one, two) do\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[add]] args=[ArgsDecl[size=2 arg0=[Ident[one]] arg1=[Ident[two]]]] block=[NULL]]\n";
    assert_code_desc(code, desc);
}

void func_body_one_line(void)
{
    const char *code = "def test() do\n1\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[test]] args=[ArgsDecl[size=0]] block=[\n IntLiteral=[1]\n]]\n";
    assert_code_desc(code, desc);
}

void func_body_multi_line(void)
{
    const char *code = "def test() do\n1\n2\n3\nend\n";
    const char *desc = "DeclareFunc=[ident=[Ident[test]] args=[ArgsDecl[size=0]] block=[\n IntLiteral=[1]\n IntLiteral=[2]\n IntLiteral=[3]\n]]\n";
    assert_code_desc(code, desc);
}

static void empty_line_test(void)
{
    assert_code_desc(R"snow(

        1
    )snow", "IntLiteral=[1]\n");
}

static void comment_full_line_test(void)
{
    assert_code_desc(R"snow(
        # 1
        1
    )snow", "IntLiteral=[1]\n");
}

static void comment_part_line_test(void)
{
    assert_code_desc(R"snow(
        1 # 2
    )snow", "IntLiteral=[1]\n");
}

static void class_declare_empty(void)
{
    assert_code_desc(R"snow(
        class MyClass do
        end
    )snow", "DeclareClass=[type=[Type[MyClass]]]\n");
}

static void class_declare_with_var(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          i = 0
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 1);

    DeclareVar *var = c->getVars()[0];
    s_assert_cmpstr(var->to_program_string(), "DeclareVar=[ident=[Ident[i type=Integer]] expr=[IntLiteral=[0]]]\n");

    delete n;
}

static void class_declare_with_var_no_spaces(void)
{
    const Node *n = build_graph("class MyClass do\ni = 0\nend\n");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 1);

    DeclareVar *var = c->getVars()[0];
    s_assert_cmpstr(var->to_program_string(), "DeclareVar=[ident=[Ident[i type=Integer]] expr=[IntLiteral=[0]]]\n");

    delete n;
}

static void class_declare_with_two_vars(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          a = 0
          b = 0
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    cout << c->getClassType().getNodeId() << "\n";
    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getVars().size() == 2);

    DeclareVar& a = *c->getVars()[0];
    s_assert_cmpstr(a.to_program_string(), "DeclareVar=[ident=[Ident[a type=Integer]] expr=[IntLiteral=[0]]]\n");

    DeclareVar& b = *c->getVars()[1];
    s_assert_cmpstr(b.to_program_string(), "DeclareVar=[ident=[Ident[b type=Integer]] expr=[IntLiteral=[0]]]\n");

    delete n;
}

static void class_declare_with_func(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          def myfunc() do
          end
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getFuncs().size() == 1);

    DeclareFunc& func = *c->getFuncs()[0];
    s_assert_cmpstr(func.getName(), "myfunc");

    delete n;
}

static void class_declare_with_two_funcs(void)
{
    const Node *n = build_graph(R"snow(
        class MyClass do
          def firstFunc() do
            a = 0
          end
          def secondFunc() do
            b = 0
          end
        end
    )snow");

    s_assert(n->isNodeType(DECLARE_CLASS));
    DeclareClass *c = (DeclareClass*)n;

    s_assert_cmpstr(c->getClassType().getId(), "MyClass");
    s_assert(c->getFuncs().size() == 2);

    DeclareFunc& first_func = *c->getFuncs()[0];
    s_assert_cmpstr(first_func.getName(), "firstFunc");

    DeclareFunc& second_func = *c->getFuncs()[1];
    s_assert_cmpstr(second_func.getName(), "secondFunc");

    delete n;
}

static void type_static()
{
    const Node *n = build_graph("Integer:i = 0");
    s_assert(n->isNodeType(DECLARE_VAR));

    const DeclareVar& decl = *(DeclareVar*)n;
    const Ident& i = decl.getIdent();
    s_assert_cmpstr(i.getName()->c_str(), "i");

    s_assert_notnull(Type::Integer);
    s_assert_notnull(i.getType());
    s_assert(i.getType() == Type::Integer);

    delete n;
}

static void type_inference_assignment_test()
{
    const Node *n = build_graph("i = 0");
    s_assert(n->isNodeType(DECLARE_VAR));

    const DeclareVar& decl = *(DeclareVar*)n;
    const Ident& i = decl.getIdent();

    s_assert_notnull(Type::Integer);
    s_assert_notnull(i.getType());
    s_assert(i.getType() == Type::Integer);

    delete n;
}

void parser_tests(TestSuite& tests)
{
    tests.add("/Parser/int_literal", int_literal_test);
    tests.add("/Parser/string_literal", string_literal_test);
    tests.add("/Parser/multi_node", multi_node_test);
    tests.add("/Parser/arithmetic_expr_test", arithmetic_expr_test);
    tests.add("/Parser/assignment_test", assignment_test);
    tests.add("/Parser/string_assignment_test", string_assignment_test);
    tests.add("/Parser/multi_assignment_test", multi_assignment_test);
    tests.add("/Parser/func/no_args", func_no_args);
    tests.add("/Parser/func/one_arg", func_one_arg);
    tests.add("/Parser/func/two_args", func_two_args);
    tests.add("/Parser/func/body_one_line", func_body_one_line);
    tests.add("/Parser/func/body_multi_line", func_body_multi_line);
    tests.add("/Parser/empty_line", empty_line_test);
    tests.add("/Parser/comment/full_line", comment_full_line_test);
    tests.add("/Parser/comment/part_line", comment_part_line_test);
    tests.add("/Parser/class/empty", class_declare_empty);
    tests.add("/Parser/class/with_var", class_declare_with_var);
    tests.add("/Parser/class/with_var_no_spaces", class_declare_with_var_no_spaces);
    tests.add("/Parser/class/with_two_vars", class_declare_with_two_vars);
    tests.add("/Parser/class/with_func", class_declare_with_func);
    tests.add("/Parser/class/with_two_funcs", class_declare_with_two_funcs);
    tests.add("/Parser/type/static", type_static);
    tests.add("/Parser/type/assignment_inference", type_inference_assignment_test);
}
<|endoftext|>


<commit_before>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
using namespace llvm;

/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library.  In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this.  Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;

// Register the target.
static RegisterTarget<X86_32TargetMachine>
X("x86",    "32-bit X86: Pentium-Pro and above");
static RegisterTarget<X86_64TargetMachine>
Y("x86-64", "64-bit X86: EM64T and AMD64");

// Force static initialization.
extern "C" void LLVMInitializeX86Target() { }

// No assembler printer by default
X86TargetMachine::AsmPrinterCtorFn X86TargetMachine::AsmPrinterCtor = 0;

const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const {
  if (Subtarget.isFlavorIntel())
    return new X86WinTargetAsmInfo(*this);
  else
    switch (Subtarget.TargetType) {
     case X86Subtarget::isDarwin:
      return new X86DarwinTargetAsmInfo(*this);
     case X86Subtarget::isELF:
      return new X86ELFTargetAsmInfo(*this);
     case X86Subtarget::isMingw:
     case X86Subtarget::isCygwin:
      return new X86COFFTargetAsmInfo(*this);
     case X86Subtarget::isWindows:
      return new X86WinTargetAsmInfo(*this);
     default:
      return new X86GenericTargetAsmInfo(*this);
    }
}

unsigned X86_32TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
  return 10;
#endif
  return 0;
}

unsigned X86_64TargetMachine::getJITMatchQuality() {
#if defined(__x86_64__) || defined(_M_AMD64)
  return 10;
#endif
  return 0;
}

unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "i[3-9]86-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
      TT[4] == '-' && TT[1] - '3' < 6)
    return 20;
  // If the target triple is something non-X86, we don't match.
  if (!TT.empty()) return 0;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer32)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "x86_64-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' &&
      TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-')
    return 20;

  // We strongly match "amd64-*".
  if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' &&
      TT[3] == '6' && TT[4] == '4' && TT[5] == '-')
    return 20;

  // If the target triple is something non-X86-64, we don't match.
  if (!TT.empty()) return 0;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer64)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS)
  : X86TargetMachine(M, FS, false) {
}

X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS)
  : X86TargetMachine(M, FS, true) {
}

/// X86TargetMachine ctor - Create an ILP32 architecture model
///
X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS,
                                   bool is64Bit)
  : Subtarget(M, FS, is64Bit),
    DataLayout(Subtarget.getDataLayout()),
    FrameInfo(TargetFrameInfo::StackGrowsDown,
              Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4),
    InstrInfo(*this), JITInfo(*this), TLInfo(*this), ELFWriterInfo(*this) {
  DefRelocModel = getRelocationModel();
  // FIXME: Correctly select PIC model for Win64 stuff
  if (getRelocationModel() == Reloc::Default) {
    if (Subtarget.isTargetDarwin() ||
        (Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64()))
      setRelocationModel(Reloc::DynamicNoPIC);
    else
      setRelocationModel(Reloc::Static);
  }

  assert(getRelocationModel() != Reloc::Default &&
         "Relocation mode not picked");

  // ELF doesn't have a distinct dynamic-no-PIC model. Dynamic-no-PIC
  // is defined as a model for code which may be used in static or
  // dynamic executables but not necessarily a shared library. On ELF
  // implement this by using the Static model.
  if (Subtarget.isTargetELF() &&
      getRelocationModel() == Reloc::DynamicNoPIC)
    setRelocationModel(Reloc::Static);

  if (Subtarget.is64Bit()) {
    // No DynamicNoPIC support under X86-64.
    if (getRelocationModel() == Reloc::DynamicNoPIC)
      setRelocationModel(Reloc::PIC_);
    // Default X86-64 code model is small.
    if (getCodeModel() == CodeModel::Default)
      setCodeModel(CodeModel::Small);
  }

  if (Subtarget.isTargetCygMing()) {
    Subtarget.setPICStyle(PICStyles::None);
  } else if (Subtarget.isTargetDarwin()) {
    if (Subtarget.is64Bit())
      Subtarget.setPICStyle(PICStyles::RIPRel);
    else
      Subtarget.setPICStyle(PICStyles::Stub);
  } else if (Subtarget.isTargetELF()) {
    if (Subtarget.is64Bit())
      Subtarget.setPICStyle(PICStyles::RIPRel);
    else
      Subtarget.setPICStyle(PICStyles::GOT);
  }

  // Finally, unless we're in PIC or DynamicNoPIC mode, set the PIC style to
  // None.
  if (getRelocationModel() == Reloc::Static)
    Subtarget.setPICStyle(PICStyles::None);
}

//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//

bool X86TargetMachine::addInstSelector(PassManagerBase &PM,
                                       CodeGenOpt::Level OptLevel) {
  // Install an instruction selector.
  PM.add(createX86ISelDag(*this, OptLevel));

  // If we're using Fast-ISel, clean up the mess.
  if (EnableFastISel)
    PM.add(createDeadMachineInstructionElimPass());

  // Install a pass to insert x87 FP_REG_KILL instructions, as needed.
  PM.add(createX87FPRegKillInserterPass());

  return false;
}

bool X86TargetMachine::addPreRegAlloc(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel) {
  // Calculate and set max stack object alignment early, so we can decide
  // whether we will need stack realignment (and thus FP).
  PM.add(createX86MaxStackAlignmentCalculatorPass());
  return false;  // -print-machineinstr shouldn't print after this.
}

bool X86TargetMachine::addPostRegAlloc(PassManagerBase &PM,
                                       CodeGenOpt::Level OptLevel) {
  PM.add(createX86FloatingPointStackifierPass());
  return true;  // -print-machineinstr should print after this.
}

bool X86TargetMachine::addAssemblyEmitter(PassManagerBase &PM,
                                          CodeGenOpt::Level OptLevel,
                                          bool Verbose,
                                          raw_ostream &Out) {
  // FIXME: Move this somewhere else!
  // On Darwin, override 64-bit static relocation to pic_ since the
  // assembler doesn't support it.
  if (DefRelocModel == Reloc::Static &&
      Subtarget.isTargetDarwin() && Subtarget.is64Bit() &&
      getCodeModel() == CodeModel::Small)
    setRelocationModel(Reloc::PIC_);

  assert(AsmPrinterCtor && "AsmPrinter was not linked in");
  if (AsmPrinterCtor)
    PM.add(AsmPrinterCtor(Out, *this, Verbose));
  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      MachineCodeEmitter &MCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86CodeEmitterPass(*this, MCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      JITCodeEmitter &JCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86JITCodeEmitterPass(*this, JCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      ObjectCodeEmitter &OCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86ObjectCodeEmitterPass(*this, OCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            MachineCodeEmitter &MCE) {
  PM.add(createX86CodeEmitterPass(*this, MCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            JITCodeEmitter &JCE) {
  PM.add(createX86JITCodeEmitterPass(*this, JCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            ObjectCodeEmitter &OCE) {
  PM.add(createX86ObjectCodeEmitterPass(*this, OCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}
<commit_msg>many more cleanups, for example if in the "none" pic-style, make sure we're set to static codegen.  Simplify the decision tree of target->picstyle/picmode settings.<commit_after>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the X86 specific subclass of TargetMachine.
//
//===----------------------------------------------------------------------===//

#include "X86TargetAsmInfo.h"
#include "X86TargetMachine.h"
#include "X86.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
using namespace llvm;

/// X86TargetMachineModule - Note that this is used on hosts that cannot link
/// in a library unless there are references into the library.  In particular,
/// it seems that it is not possible to get things to work on Win32 without
/// this.  Though it is unused, do not remove it.
extern "C" int X86TargetMachineModule;
int X86TargetMachineModule = 0;

// Register the target.
static RegisterTarget<X86_32TargetMachine>
X("x86",    "32-bit X86: Pentium-Pro and above");
static RegisterTarget<X86_64TargetMachine>
Y("x86-64", "64-bit X86: EM64T and AMD64");

// Force static initialization.
extern "C" void LLVMInitializeX86Target() { }

// No assembler printer by default
X86TargetMachine::AsmPrinterCtorFn X86TargetMachine::AsmPrinterCtor = 0;

const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const {
  if (Subtarget.isFlavorIntel())
    return new X86WinTargetAsmInfo(*this);
  else
    switch (Subtarget.TargetType) {
     case X86Subtarget::isDarwin:
      return new X86DarwinTargetAsmInfo(*this);
     case X86Subtarget::isELF:
      return new X86ELFTargetAsmInfo(*this);
     case X86Subtarget::isMingw:
     case X86Subtarget::isCygwin:
      return new X86COFFTargetAsmInfo(*this);
     case X86Subtarget::isWindows:
      return new X86WinTargetAsmInfo(*this);
     default:
      return new X86GenericTargetAsmInfo(*this);
    }
}

unsigned X86_32TargetMachine::getJITMatchQuality() {
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)
  return 10;
#endif
  return 0;
}

unsigned X86_64TargetMachine::getJITMatchQuality() {
#if defined(__x86_64__) || defined(_M_AMD64)
  return 10;
#endif
  return 0;
}

unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "i[3-9]86-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
      TT[4] == '-' && TT[1] - '3' < 6)
    return 20;
  // If the target triple is something non-X86, we don't match.
  if (!TT.empty()) return 0;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer32)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) {
  // We strongly match "x86_64-*".
  std::string TT = M.getTargetTriple();
  if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' &&
      TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-')
    return 20;

  // We strongly match "amd64-*".
  if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' &&
      TT[3] == '6' && TT[4] == '4' && TT[5] == '-')
    return 20;

  // If the target triple is something non-X86-64, we don't match.
  if (!TT.empty()) return 0;

  if (M.getEndianness()  == Module::LittleEndian &&
      M.getPointerSize() == Module::Pointer64)
    return 10;                                   // Weak match
  else if (M.getEndianness() != Module::AnyEndianness ||
           M.getPointerSize() != Module::AnyPointerSize)
    return 0;                                    // Match for some other target

  return getJITMatchQuality()/2;
}

X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS)
  : X86TargetMachine(M, FS, false) {
}

X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS)
  : X86TargetMachine(M, FS, true) {
}

/// X86TargetMachine ctor - Create an X86 target.
///
X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS,
                                   bool is64Bit)
  : Subtarget(M, FS, is64Bit),
    DataLayout(Subtarget.getDataLayout()),
    FrameInfo(TargetFrameInfo::StackGrowsDown,
              Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4),
    InstrInfo(*this), JITInfo(*this), TLInfo(*this), ELFWriterInfo(*this) {
  DefRelocModel = getRelocationModel();

  // If no relocation model was picked, default as appropriate for the target.
  if (getRelocationModel() == Reloc::Default) {
    if (!Subtarget.isTargetDarwin())
      setRelocationModel(Reloc::Static);
    else if (Subtarget.is64Bit())
      setRelocationModel(Reloc::PIC_);
    else
      setRelocationModel(Reloc::DynamicNoPIC);
  }

  assert(getRelocationModel() != Reloc::Default &&
         "Relocation mode not picked");

  // If no code model is picked, default to small.
  if (getCodeModel() == CodeModel::Default)
    setCodeModel(CodeModel::Small);

  // ELF and X86-64 don't have a distinct dynamic-no-PIC model.  Dynamic-no-PIC
  // is defined as a model for code which may be used in static or dynamic
  // executables but not necessarily a shared library. On these systems we just
  // compile in -static mode.
  if (getRelocationModel() == Reloc::DynamicNoPIC &&
      !Subtarget.isTargetDarwin())
    setRelocationModel(Reloc::Static);

  // Determine the PICStyle based on the target selected.
  if (getRelocationModel() == Reloc::Static) {
    // Unless we're in PIC or DynamicNoPIC mode, set the PIC style to None.
    Subtarget.setPICStyle(PICStyles::None);
  } else if (Subtarget.isTargetCygMing()) {
    Subtarget.setPICStyle(PICStyles::None);
  } else if (Subtarget.isTargetDarwin()) {
    if (Subtarget.is64Bit())
      Subtarget.setPICStyle(PICStyles::RIPRel);
    else
      Subtarget.setPICStyle(PICStyles::Stub);
  } else if (Subtarget.isTargetELF()) {
    if (Subtarget.is64Bit())
      Subtarget.setPICStyle(PICStyles::RIPRel);
    else
      Subtarget.setPICStyle(PICStyles::GOT);
  }

  // Finally, if we have "none" as our PIC style, force to static mode.
  if (Subtarget.getPICStyle() == PICStyles::None)
    setRelocationModel(Reloc::Static);
}

//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//

bool X86TargetMachine::addInstSelector(PassManagerBase &PM,
                                       CodeGenOpt::Level OptLevel) {
  // Install an instruction selector.
  PM.add(createX86ISelDag(*this, OptLevel));

  // If we're using Fast-ISel, clean up the mess.
  if (EnableFastISel)
    PM.add(createDeadMachineInstructionElimPass());

  // Install a pass to insert x87 FP_REG_KILL instructions, as needed.
  PM.add(createX87FPRegKillInserterPass());

  return false;
}

bool X86TargetMachine::addPreRegAlloc(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel) {
  // Calculate and set max stack object alignment early, so we can decide
  // whether we will need stack realignment (and thus FP).
  PM.add(createX86MaxStackAlignmentCalculatorPass());
  return false;  // -print-machineinstr shouldn't print after this.
}

bool X86TargetMachine::addPostRegAlloc(PassManagerBase &PM,
                                       CodeGenOpt::Level OptLevel) {
  PM.add(createX86FloatingPointStackifierPass());
  return true;  // -print-machineinstr should print after this.
}

bool X86TargetMachine::addAssemblyEmitter(PassManagerBase &PM,
                                          CodeGenOpt::Level OptLevel,
                                          bool Verbose,
                                          raw_ostream &Out) {
  // FIXME: Move this somewhere else!
  // On Darwin, override 64-bit static relocation to pic_ since the
  // assembler doesn't support it.
  if (DefRelocModel == Reloc::Static &&
      Subtarget.isTargetDarwin() && Subtarget.is64Bit() &&
      getCodeModel() == CodeModel::Small)
    setRelocationModel(Reloc::PIC_);

  assert(AsmPrinterCtor && "AsmPrinter was not linked in");
  if (AsmPrinterCtor)
    PM.add(AsmPrinterCtor(Out, *this, Verbose));
  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      MachineCodeEmitter &MCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86CodeEmitterPass(*this, MCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      JITCodeEmitter &JCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86JITCodeEmitterPass(*this, JCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
                                      CodeGenOpt::Level OptLevel,
                                      bool DumpAsm,
                                      ObjectCodeEmitter &OCE) {
  // FIXME: Move this to TargetJITInfo!
  // On Darwin, do not override 64-bit setting made in X86TargetMachine().
  if (DefRelocModel == Reloc::Default &&
        (!Subtarget.isTargetDarwin() || !Subtarget.is64Bit()))
    setRelocationModel(Reloc::Static);

  // 64-bit JIT places everything in the same buffer except external functions.
  // On Darwin, use small code model but hack the call instruction for
  // externals.  Elsewhere, do not assume globals are in the lower 4G.
  if (Subtarget.is64Bit()) {
    if (Subtarget.isTargetDarwin())
      setCodeModel(CodeModel::Small);
    else
      setCodeModel(CodeModel::Large);
  }

  PM.add(createX86ObjectCodeEmitterPass(*this, OCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            MachineCodeEmitter &MCE) {
  PM.add(createX86CodeEmitterPass(*this, MCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            JITCodeEmitter &JCE) {
  PM.add(createX86JITCodeEmitterPass(*this, JCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}

bool X86TargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
                                            CodeGenOpt::Level OptLevel,
                                            bool DumpAsm,
                                            ObjectCodeEmitter &OCE) {
  PM.add(createX86ObjectCodeEmitterPass(*this, OCE));
  if (DumpAsm) {
    assert(AsmPrinterCtor && "AsmPrinter was not linked in");
    if (AsmPrinterCtor)
      PM.add(AsmPrinterCtor(errs(), *this, true));
  }

  return false;
}
<|endoftext|>


<commit_before>//===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file is just a split of the code that logically belongs in opt.cpp but
/// that includes the new pass manager headers.
///
//===----------------------------------------------------------------------===//

#include "NewPMDriver.h"
#include "Passes.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ToolOutputFile.h"

using namespace llvm;
using namespace opt_tool;

bool llvm::runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M,
                           tool_output_file *Out, StringRef PassPipeline,
                           OutputKind OK, VerifierKind VK) {
  FunctionAnalysisManager FAM;
  ModuleAnalysisManager MAM;

  // FIXME: Lift this registration of analysis passes into a .def file adjacent
  // to the one used to associate names with passes.
  MAM.registerPass(LazyCallGraphAnalysis());

  // Cross register the analysis managers through their proxies.
  MAM.registerPass(FunctionAnalysisManagerModuleProxy(FAM));
  FAM.registerPass(ModuleAnalysisManagerFunctionProxy(MAM));

  ModulePassManager MPM;
  if (VK > VK_NoVerifier)
    MPM.addPass(VerifierPass());

  if (!parsePassPipeline(MPM, PassPipeline, VK == VK_VerifyEachPass)) {
    errs() << Arg0 << ": unable to parse pass pipeline description.\n";
    return false;
  }

  if (VK > VK_NoVerifier)
    MPM.addPass(VerifierPass());

  // Add any relevant output pass at the end of the pipeline.
  switch (OK) {
  case OK_NoOutput:
    break; // No output pass needed.
  case OK_OutputAssembly:
    MPM.addPass(PrintModulePass(Out->os()));
    break;
  case OK_OutputBitcode:
    MPM.addPass(BitcodeWriterPass(Out->os()));
    break;
  }

  // Before executing passes, print the final values of the LLVM options.
  cl::PrintOptionValues();

  // Now that we have all of the passes ready, run them.
  MPM.run(&M, &MAM);

  // Declare success.
  if (OK != OK_NoOutput)
    Out->keep();
  return true;
}
<commit_msg>[PM] Back out one hunk of the patch in r200901 that was *supposed* to go in my next patch. Sorry for the breakage.<commit_after>//===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file is just a split of the code that logically belongs in opt.cpp but
/// that includes the new pass manager headers.
///
//===----------------------------------------------------------------------===//

#include "NewPMDriver.h"
#include "Passes.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ToolOutputFile.h"

using namespace llvm;
using namespace opt_tool;

bool llvm::runPassPipeline(StringRef Arg0, LLVMContext &Context, Module &M,
                           tool_output_file *Out, StringRef PassPipeline,
                           OutputKind OK, VerifierKind VK) {
  FunctionAnalysisManager FAM;
  ModuleAnalysisManager MAM;

  // Cross register the analysis managers through their proxies.
  MAM.registerPass(FunctionAnalysisManagerModuleProxy(FAM));
  FAM.registerPass(ModuleAnalysisManagerFunctionProxy(MAM));

  ModulePassManager MPM;
  if (VK > VK_NoVerifier)
    MPM.addPass(VerifierPass());

  if (!parsePassPipeline(MPM, PassPipeline, VK == VK_VerifyEachPass)) {
    errs() << Arg0 << ": unable to parse pass pipeline description.\n";
    return false;
  }

  if (VK > VK_NoVerifier)
    MPM.addPass(VerifierPass());

  // Add any relevant output pass at the end of the pipeline.
  switch (OK) {
  case OK_NoOutput:
    break; // No output pass needed.
  case OK_OutputAssembly:
    MPM.addPass(PrintModulePass(Out->os()));
    break;
  case OK_OutputBitcode:
    MPM.addPass(BitcodeWriterPass(Out->os()));
    break;
  }

  // Before executing passes, print the final values of the LLVM options.
  cl::PrintOptionValues();

  // Now that we have all of the passes ready, run them.
  MPM.run(&M, &MAM);

  // Declare success.
  if (OK != OK_NoOutput)
    Out->keep();
  return true;
}
<|endoftext|>


<commit_before>/*
    YahooInviteListImpl - conference invitation dialog

    Copyright (c) 2004 by Duncan Mac-Vicar P.    <duncan@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "yahooinvitelistimpl.h"

#include <kdebug.h>

#include <qlistbox.h>
#include <qlineedit.h>

YahooInviteListImpl::YahooInviteListImpl(QWidget *parent, const char *name) : YahooInviteListBase(parent,name)
{
	listFriends->setSelectionMode( QListBox::Extended );
	listInvited->setSelectionMode( QListBox::Extended );
}

YahooInviteListImpl::~YahooInviteListImpl()
{
}

void YahooInviteListImpl::setRoom( const QString &room )
{
	kdDebug(14180) << k_funcinfo << "Setting roomname to: " << room << endl;

	m_room = room;
}

void YahooInviteListImpl::fillFriendList( const QStringList &buddies )
{
	kdDebug(14180) << k_funcinfo << "Adding friends: " << buddies << endl;

	m_buddyList = buddies;
	updateListBoxes();
}

void YahooInviteListImpl::updateListBoxes()
{
	kdDebug(14180) << k_funcinfo << endl;

	listFriends->clear();
	listInvited->clear();
	listFriends->insertStringList( m_buddyList );
	listFriends->sort();
	listInvited->insertStringList( m_inviteeList );
	listInvited->sort();
}

void YahooInviteListImpl::addInvitees( const QStringList &invitees )
{
	kdDebug(14180) << k_funcinfo << "Adding invitees: " << invitees << endl;

	for( QStringList::const_iterator it = invitees.begin(); it != invitees.end(); it++ )
	{
		if( m_inviteeList.find( *it ) == m_inviteeList.end() )
			m_inviteeList.push_back( *it );
		if( m_buddyList.find( *it ) != m_buddyList.end() )
			m_buddyList.remove( *it );
	}

	updateListBoxes();
}

void YahooInviteListImpl::removeInvitees( const QStringList &invitees )
{
	kdDebug(14180) << k_funcinfo << "Removing invitees: " << invitees << endl;

	for( QStringList::const_iterator it = invitees.begin(); it != invitees.end(); it++ )
	{
		if( m_buddyList.find( *it ) == m_buddyList.end() )
			m_buddyList.push_back( *it );
		if( m_inviteeList.find( *it ) != m_inviteeList.end() )
			m_inviteeList.remove( *it );
	}

	updateListBoxes();
}

void YahooInviteListImpl::btnInvite_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	emit readyToInvite( m_room, m_inviteeList, editMessage->text() );
	QDialog::reject();
}

void YahooInviteListImpl::btnCancel_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QDialog::reject();
}

void YahooInviteListImpl::btnAddCustom_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QString userId;
	userId = editBuddyAdd->text();
	if( userId.isEmpty() )
		return;

	addInvitees( QStringList(userId) );
	editBuddyAdd->clear();
}

void YahooInviteListImpl::btnRemove_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QStringList buddies;
	for( uint i=0; i<listInvited->count(); i++ )
	{
		if (listInvited->isSelected(i))
		{
			buddies.push_back( listInvited->text(i) );
		}
	}
	removeInvitees( buddies );
}

void YahooInviteListImpl::btnAdd_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QStringList buddies;
	for( uint i=0; i<listFriends->count(); i++ )
	{
		if (listFriends->isSelected(i))
		{
			buddies.push_back( listFriends->text(i) );
		}
	}
	addInvitees( buddies );
}

#include "yahooinvitelistimpl.moc"

<commit_msg>check for empty invitelist<commit_after>/*
    YahooInviteListImpl - conference invitation dialog

    Copyright (c) 2004 by Duncan Mac-Vicar P.    <duncan@kde.org>

    Kopete    (c) 2002-2004 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "yahooinvitelistimpl.h"

#include <kdebug.h>

#include <qlistbox.h>
#include <qlineedit.h>

YahooInviteListImpl::YahooInviteListImpl(QWidget *parent, const char *name) : YahooInviteListBase(parent,name)
{
	listFriends->setSelectionMode( QListBox::Extended );
	listInvited->setSelectionMode( QListBox::Extended );
}

YahooInviteListImpl::~YahooInviteListImpl()
{
}

void YahooInviteListImpl::setRoom( const QString &room )
{
	kdDebug(14180) << k_funcinfo << "Setting roomname to: " << room << endl;

	m_room = room;
}

void YahooInviteListImpl::fillFriendList( const QStringList &buddies )
{
	kdDebug(14180) << k_funcinfo << "Adding friends: " << buddies << endl;

	m_buddyList = buddies;
	updateListBoxes();
}

void YahooInviteListImpl::updateListBoxes()
{
	kdDebug(14180) << k_funcinfo << endl;

	listFriends->clear();
	listInvited->clear();
	listFriends->insertStringList( m_buddyList );
	listFriends->sort();
	listInvited->insertStringList( m_inviteeList );
	listInvited->sort();
}

void YahooInviteListImpl::addInvitees( const QStringList &invitees )
{
	kdDebug(14180) << k_funcinfo << "Adding invitees: " << invitees << endl;

	for( QStringList::const_iterator it = invitees.begin(); it != invitees.end(); it++ )
	{
		if( m_inviteeList.find( *it ) == m_inviteeList.end() )
			m_inviteeList.push_back( *it );
		if( m_buddyList.find( *it ) != m_buddyList.end() )
			m_buddyList.remove( *it );
	}

	updateListBoxes();
}

void YahooInviteListImpl::removeInvitees( const QStringList &invitees )
{
	kdDebug(14180) << k_funcinfo << "Removing invitees: " << invitees << endl;

	for( QStringList::const_iterator it = invitees.begin(); it != invitees.end(); it++ )
	{
		if( m_buddyList.find( *it ) == m_buddyList.end() )
			m_buddyList.push_back( *it );
		if( m_inviteeList.find( *it ) != m_inviteeList.end() )
			m_inviteeList.remove( *it );
	}

	updateListBoxes();
}

void YahooInviteListImpl::btnInvite_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	if( m_inviteeList.count() )
		emit readyToInvite( m_room, m_inviteeList, editMessage->text() );
	QDialog::accept();
}

void YahooInviteListImpl::btnCancel_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QDialog::reject();
}

void YahooInviteListImpl::btnAddCustom_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QString userId;
	userId = editBuddyAdd->text();
	if( userId.isEmpty() )
		return;

	addInvitees( QStringList(userId) );
	editBuddyAdd->clear();
}

void YahooInviteListImpl::btnRemove_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QStringList buddies;
	for( uint i=0; i<listInvited->count(); i++ )
	{
		if (listInvited->isSelected(i))
		{
			buddies.push_back( listInvited->text(i) );
		}
	}
	removeInvitees( buddies );
}

void YahooInviteListImpl::btnAdd_clicked()
{
	kdDebug(14180) << k_funcinfo << endl;

	QStringList buddies;
	for( uint i=0; i<listFriends->count(); i++ )
	{
		if (listFriends->isSelected(i))
		{
			buddies.push_back( listFriends->text(i) );
		}
	}
	addInvitees( buddies );
}

#include "yahooinvitelistimpl.moc"

<|endoftext|>


<commit_before>#include "ui_calcbmi.h"
#include "calcbmi.h"

CalcBMI::CalcBMI(QWidget *parent) :
   QDialog(parent),
   ui(new Ui::CalcBMI)
{
   ui->setupUi(this);
}

CalcBMI::~CalcBMI()
{
   delete ui;
}

void CalcBMI::UpdateMethod()
{

}

void CalcBMI::on_closeButton_clicked()
{
   CloseWindow(this);
}
<commit_msg>richard was here so please ignore<commit_after>#include "ui_calcbmi.h"
#include "calcbmi.h"

CalcBMI::CalcBMI(QWidget *parent) :
   QDialog(parent),
   ui(new Ui::CalcBMI)
{
   ui->setupUi(this);
   qDebug() << "ignore this";
}

CalcBMI::~CalcBMI()
{
   delete ui;
}

void CalcBMI::UpdateMethod()
{

}

void CalcBMI::on_closeButton_clicked()
{
   CloseWindow(this);
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "compileoutputwindow.h"
#include "buildmanager.h"
#include "showoutputtaskhandler.h"
#include "task.h"

#include <find/basetextfind.h>
#include <aggregation/aggregate.h>
#include <extensionsystem/pluginmanager.h>

#include <QtGui/QKeyEvent>
#include <QtGui/QIcon>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
#include <QtGui/QTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QPlainTextEdit>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

CompileOutputWindow::CompileOutputWindow(BuildManager * /*bm*/)
{
    m_textEdit = new QPlainTextEdit();
    m_textEdit->setWindowTitle(tr("Compile Output"));
    m_textEdit->setWindowIcon(QIcon(":/qt4projectmanager/images/window.png"));
    m_textEdit->setReadOnly(true);
    m_textEdit->setFrameStyle(QFrame::NoFrame);
    Aggregation::Aggregate *agg = new Aggregation::Aggregate;
    agg->add(m_textEdit);
    agg->add(new Find::BaseTextFind(m_textEdit));

    qRegisterMetaType<QTextCharFormat>("QTextCharFormat");

    m_handler = new ShowOutputTaskHandler(this);
    ExtensionSystem::PluginManager::instance()->addObject(m_handler);
}

CompileOutputWindow::~CompileOutputWindow()
{
    ExtensionSystem::PluginManager::instance()->removeObject(m_handler);
    delete m_handler;
}

bool CompileOutputWindow::hasFocus()
{
    return m_textEdit->hasFocus();
}

bool CompileOutputWindow::canFocus()
{
    return true;
}

void CompileOutputWindow::setFocus()
{
    m_textEdit->setFocus();
}

QWidget *CompileOutputWindow::outputWidget(QWidget *)
{
    return m_textEdit;
}

void CompileOutputWindow::appendText(const QString &text, const QTextCharFormat &textCharFormat)
{
    QString textWithNewline = text;
    if (!textWithNewline.endsWith("\n"))
        textWithNewline.append("\n");
    QTextCursor cursor = QTextCursor(m_textEdit->document());
    cursor.movePosition(QTextCursor::End);
    cursor.beginEditBlock();
    cursor.insertText(textWithNewline, textCharFormat);
    cursor.endEditBlock();
}

void CompileOutputWindow::clearContents()
{
    m_textEdit->clear();
    m_taskPositions.clear();
}

void CompileOutputWindow::visibilityChanged(bool b)
{
    if (b)
        m_textEdit->verticalScrollBar()->setValue(m_textEdit->verticalScrollBar()->maximum());
}

int CompileOutputWindow::priorityInStatusBar() const
{
    return 50;
}

bool CompileOutputWindow::canNext()
{
    return false;
}

bool CompileOutputWindow::canPrevious()
{
    return false;
}

void CompileOutputWindow::goToNext()
{

}

void CompileOutputWindow::goToPrev()
{

}

bool CompileOutputWindow::canNavigate()
{
    return false;
}

void CompileOutputWindow::registerPositionOf(const Task &task)
{
    QTextBlock block(m_textEdit->textCursor().block());
    m_taskPositions.insert(task.taskId, block.position() + block.length() + 1);
}

bool CompileOutputWindow::knowsPositionOf(const Task &task)
{
    return (m_taskPositions.contains(task.taskId));
}

void CompileOutputWindow::showPositionOf(const Task &task)
{
    int position = m_taskPositions.value(task.taskId);
    QTextCursor newCursor(m_textEdit->document()->findBlock(position));
    newCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    m_textEdit->setTextCursor(newCursor);
}
<commit_msg>Fixes scrolling to the bottom of compile output<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "compileoutputwindow.h"
#include "buildmanager.h"
#include "showoutputtaskhandler.h"
#include "task.h"

#include <find/basetextfind.h>
#include <aggregation/aggregate.h>
#include <extensionsystem/pluginmanager.h>

#include <QtGui/QKeyEvent>
#include <QtGui/QIcon>
#include <QtGui/QTextBlock>
#include <QtGui/QTextCursor>
#include <QtGui/QTextEdit>
#include <QtGui/QScrollBar>
#include <QtGui/QPlainTextEdit>

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

CompileOutputWindow::CompileOutputWindow(BuildManager * /*bm*/)
{
    m_textEdit = new QPlainTextEdit();
    m_textEdit->setWindowTitle(tr("Compile Output"));
    m_textEdit->setWindowIcon(QIcon(":/qt4projectmanager/images/window.png"));
    m_textEdit->setReadOnly(true);
    m_textEdit->setFrameStyle(QFrame::NoFrame);
    Aggregation::Aggregate *agg = new Aggregation::Aggregate;
    agg->add(m_textEdit);
    agg->add(new Find::BaseTextFind(m_textEdit));

    qRegisterMetaType<QTextCharFormat>("QTextCharFormat");

    m_handler = new ShowOutputTaskHandler(this);
    ExtensionSystem::PluginManager::instance()->addObject(m_handler);
}

CompileOutputWindow::~CompileOutputWindow()
{
    ExtensionSystem::PluginManager::instance()->removeObject(m_handler);
    delete m_handler;
}

bool CompileOutputWindow::hasFocus()
{
    return m_textEdit->hasFocus();
}

bool CompileOutputWindow::canFocus()
{
    return true;
}

void CompileOutputWindow::setFocus()
{
    m_textEdit->setFocus();
}

QWidget *CompileOutputWindow::outputWidget(QWidget *)
{
    return m_textEdit;
}

void CompileOutputWindow::appendText(const QString &text, const QTextCharFormat &textCharFormat)
{
    if (m_textEdit->document()->blockCount() > 10000)
        return;
    bool shouldScroll = (m_textEdit->verticalScrollBar()->value() ==
                         m_textEdit->verticalScrollBar()->maximum());
    QString textWithNewline = text;
    if (!textWithNewline.endsWith("\n"))
        textWithNewline.append("\n");
    QTextCursor cursor = QTextCursor(m_textEdit->document());
    cursor.movePosition(QTextCursor::End);
    cursor.beginEditBlock();
    cursor.insertText(textWithNewline, textCharFormat);

    if (m_textEdit->document()->blockCount() > 10000) {
        QTextCharFormat tmp;
        tmp.setFontWeight(QFont::Bold);
        cursor.insertText(tr("Additional output omitted\n"), tmp);
    }

    cursor.endEditBlock();

    if (shouldScroll)
        m_textEdit->setTextCursor(cursor);
}

void CompileOutputWindow::clearContents()
{
    m_textEdit->clear();
    m_taskPositions.clear();
}

void CompileOutputWindow::visibilityChanged(bool b)
{
    if (b)
        m_textEdit->verticalScrollBar()->setValue(m_textEdit->verticalScrollBar()->maximum());
}

int CompileOutputWindow::priorityInStatusBar() const
{
    return 50;
}

bool CompileOutputWindow::canNext()
{
    return false;
}

bool CompileOutputWindow::canPrevious()
{
    return false;
}

void CompileOutputWindow::goToNext()
{

}

void CompileOutputWindow::goToPrev()
{

}

bool CompileOutputWindow::canNavigate()
{
    return false;
}

void CompileOutputWindow::registerPositionOf(const Task &task)
{
    QTextBlock block(m_textEdit->textCursor().block());
    m_taskPositions.insert(task.taskId, block.position() + block.length() + 1);
}

bool CompileOutputWindow::knowsPositionOf(const Task &task)
{
    return (m_taskPositions.contains(task.taskId));
}

void CompileOutputWindow::showPositionOf(const Task &task)
{
    int position = m_taskPositions.value(task.taskId);
    QTextCursor newCursor(m_textEdit->document()->findBlock(position));
    newCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    m_textEdit->setTextCursor(newCursor);
}
<|endoftext|>


<commit_before>// @(#)root/winnt:$Name:  $:$Id: Win32Splash.cxx,v 1.4 2003/10/08 15:30:43 brun Exp $
// Author: Bertrand Bellenot   30/07/02

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifdef WIN32
#include "Windows4Root.h"
#include <stdlib.h>
#include <stdio.h>

#define ID_SPLASHSCREEN      25
#define MY_BUFSIZE         1024 // buffer size for console window titles

///////////////////////////////////////////////////////////////////////////////
// Global Variables:
HINSTANCE hInst;                        // current instance
HWND hMainWnd = NULL;
HWND hSplashWnd = NULL;               // Splash screen
HBITMAP hBmp = NULL;
BITMAP bm;
BOOL bSplash = TRUE;
DWORD DelayVal = 0;
BOOL bClassRegistered = FALSE;

///////////////////////////////////////////////////////////////////////////////
// Foward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
LRESULT CALLBACK    SplashWndProc(HWND, UINT, WPARAM, LPARAM);

////////////////////////////////////////////////////////////////////////////////
// Splashscreen functions
////////////////////////////////////////////////////////////////////////////////
//
//
void HideSplashScreen()
{
    // Destroy the window
    if (IsWindow(hSplashWnd)) {
        DestroyWindow(hSplashWnd);
        DeleteObject(hBmp);
        hSplashWnd = NULL;
        UnregisterClass("RootSplashScreen", hInst);
    }
}

////////////////////////////////////////////////////////////////////////////////
//
//
BOOL CreateSplashScreen(HWND hParent)
{
    int xScreen;
    int yScreen;
    // Crenter the splashscreen
    xScreen = GetSystemMetrics(SM_CXFULLSCREEN);
    yScreen = GetSystemMetrics(SM_CYFULLSCREEN);

    hSplashWnd = CreateWindowEx(
            WS_EX_TOOLWINDOW,
            "RootSplashScreen",
            NULL,
            WS_POPUP | WS_VISIBLE,
            (xScreen - 360)/2,
            (yScreen - 240)/2,
            360, 240,
            hParent,
            NULL,
            hInst,
            NULL);

    return (hSplashWnd != NULL);
}

////////////////////////////////////////////////////////////////////////////////
//
//
BOOL PreTranslateMessage(MSG* pMsg)
{
    if (!IsWindow(hSplashWnd))
        return FALSE;

    // If we get a keyboard or mouse message, hide the splash screen.
    if (pMsg->message == WM_KEYDOWN ||
        pMsg->message == WM_SYSKEYDOWN ||
        pMsg->message == WM_LBUTTONDOWN ||
        pMsg->message == WM_RBUTTONDOWN ||
        pMsg->message == WM_MBUTTONDOWN ||
        pMsg->message == WM_NCLBUTTONDOWN ||
        pMsg->message == WM_NCRBUTTONDOWN ||
        pMsg->message == WM_NCMBUTTONDOWN)
    {
        HideSplashScreen();
        return TRUE;    // message handled here
    }

    return FALSE;   // message not handled
}

void CreateSplash(DWORD time)
{
    MSG msg;
    if (MyRegisterClass(hInst) != 0)
        bClassRegistered = TRUE;
    if(time > 0) {
        bSplash = TRUE;
        DelayVal = time * 1000;
    }
    else return;
    // Create the splash screen
    if (bSplash)
        CreateSplashScreen(NULL);

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0)) {
        PreTranslateMessage(&msg);
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    HideSplashScreen();
}

///////////////////////////////////////////////////////////////////////////////
//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = (WNDPROC)SplashWndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = NULL;
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = NULL;
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = "RootSplashScreen";
    wcex.hIconSm        = NULL;
    return RegisterClassEx(&wcex);
}

////////////////////////////////////////////////////////////////////////////
// Message handler for splash screen.
//
LRESULT CALLBACK SplashWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hDC;
    HANDLE hfbm;
    BITMAPFILEHEADER bmfh;
    BITMAPINFOHEADER bmih;
    HGLOBAL hmem1,hmem2;
    LPBITMAPINFO lpbmi;
    LPVOID lpvBits;
    DWORD dwRead;
    HWND hwndFound;         // this is what is returned to the caller
    char pszNewWindowTitle[MY_BUFSIZE]; // contains fabricated WindowTitle
    char pszOldWindowTitle[MY_BUFSIZE]; // contains original WindowTitle
    const char bmpDir[] = "\\icons\\Splash.bmp";
    char FullBmpDir[128];
    char *RootSysDir;
    int xScreen;
    int yScreen;

    switch (message)
    {
        case WM_CREATE:
            SetTimer(hWnd, ID_SPLASHSCREEN, DelayVal, NULL);
            RootSysDir = getenv("ROOTSYS");
            sprintf(FullBmpDir,"%s%s",RootSysDir,bmpDir);
            // Retrieve a handle identifying the file.
            hfbm = CreateFile(FullBmpDir, GENERIC_READ,
                    FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL,
                    OPEN_EXISTING, FILE_ATTRIBUTE_READONLY,
                    (HANDLE) NULL);
            if(hfbm) {
                // Retrieve the BITMAPFILEHEADER structure.
                ReadFile(hfbm, &bmfh, sizeof(BITMAPFILEHEADER), &dwRead,
                        (LPOVERLAPPED)NULL);
                // Retrieve the BITMAPFILEHEADER structure.
                ReadFile(hfbm, &bmih, sizeof(BITMAPINFOHEADER),
                        &dwRead, (LPOVERLAPPED)NULL);
                // Allocate memory for the BITMAPINFO structure.
                hmem1 = GlobalAlloc(GHND, sizeof(BITMAPINFOHEADER) +
                        ((1<<bmih.biBitCount) * sizeof(RGBQUAD)));
                lpbmi = (LPBITMAPINFO)GlobalLock(hmem1);
                // Load BITMAPINFOHEADER into the BITMAPINFO structure.
                lpbmi->bmiHeader.biSize = bmih.biSize;
                lpbmi->bmiHeader.biWidth = bmih.biWidth;
                lpbmi->bmiHeader.biHeight = bmih.biHeight;
                lpbmi->bmiHeader.biPlanes = bmih.biPlanes;
                lpbmi->bmiHeader.biBitCount = bmih.biBitCount;
                lpbmi->bmiHeader.biCompression = bmih.biCompression;
                lpbmi->bmiHeader.biSizeImage = bmih.biSizeImage;
                lpbmi->bmiHeader.biXPelsPerMeter = bmih.biXPelsPerMeter;
                lpbmi->bmiHeader.biYPelsPerMeter = bmih.biYPelsPerMeter;
                lpbmi->bmiHeader.biClrUsed = bmih.biClrUsed;
                lpbmi->bmiHeader.biClrImportant = bmih.biClrImportant;
                // Retrieve the color table.
                // 1 << bmih.biBitCount == 2 ^ bmih.biBitCount
                ReadFile(hfbm, lpbmi->bmiColors,
                        ((1<<bmih.biBitCount) * sizeof(RGBQUAD)),
                        &dwRead, (LPOVERLAPPED) NULL);
                // Allocate memory for the required number of bytes.
                hmem2 = GlobalAlloc(GHND, (bmfh.bfSize - bmfh.bfOffBits));
                lpvBits = GlobalLock(hmem2);
                // Retrieve the bitmap data.
                ReadFile(hfbm, lpvBits, (bmfh.bfSize - bmfh.bfOffBits),
                        &dwRead, (LPOVERLAPPED) NULL);
                hDC = GetDC(hWnd);
                // Create a bitmap from the data stored in the .BMP file.
                hBmp = CreateDIBitmap(hDC, &bmih, CBM_INIT, lpvBits, lpbmi, DIB_RGB_COLORS);
                // Unlock the global memory objects and close the .BMP file.
                GlobalUnlock(hmem1);
                GlobalUnlock(hmem2);
                CloseHandle(hfbm);
                GetObjectA(hBmp, sizeof(bm), &bm);
                // Center the splashscreen
                xScreen = GetSystemMetrics(SM_CXFULLSCREEN);
                yScreen = GetSystemMetrics(SM_CYFULLSCREEN);
                SetWindowPos(hWnd, HWND_TOPMOST, (xScreen - bm.bmWidth)/2,
                    (yScreen - bm.bmHeight)/2, bm.bmWidth, bm.bmHeight, 0 );
            }
            break;

        case WM_TIMER:
            if (wParam == ID_SPLASHSCREEN) {
                KillTimer (hWnd, ID_SPLASHSCREEN);
                HideSplashScreen();
            }
            break;

        case WM_DESTROY:
            PostQuitMessage(0);

        case WM_PAINT:
            hDC = BeginPaint(hWnd, &ps);
            // TODO: Add any drawing code here...
            RECT rt;
            GetClientRect(hWnd, &rt);
            HDC hImageDC;
            hImageDC = CreateCompatibleDC(hDC);
            if (hImageDC == NULL)
                return FALSE;
            // Paint the image.
            HBITMAP hOldBitmap;
            hOldBitmap = (HBITMAP)SelectObject(hImageDC, hBmp);
            BitBlt(hDC, 0, 0, bm.bmWidth, bm.bmHeight, hImageDC, 0, 0, SRCCOPY);
            SelectObject(hImageDC, hOldBitmap);
            EndPaint(hWnd, &ps);
            SetCapture(hWnd);
            SetConsoleTitle("ROOT session");
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}
#endif
<commit_msg>Reverting to the previous version of teh splash screen. new version had side-effects.<commit_after>// @(#)root/winnt:$Name:  $:$Id: Win32Splash.cxx,v 1.5 2003/10/10 14:24:33 brun Exp $
// Author: Bertrand Bellenot   30/07/02

/*************************************************************************
 * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifdef WIN32
#include "Windows4Root.h"
#include <stdlib.h>
#include <stdio.h>

#define ID_SPLASHSCREEN      25
#define MY_BUFSIZE         1024 // buffer size for console window titles

///////////////////////////////////////////////////////////////////////////////
// Global Variables:
HINSTANCE hInst;                        // current instance
HWND hMainWnd = NULL;
HWND hSplashWnd = NULL;               // Splash screen
HBITMAP hBmp = NULL;
BITMAP bm;
BOOL bSplash = TRUE;
DWORD DelayVal = 0;
BOOL bClassRegistered = FALSE;

///////////////////////////////////////////////////////////////////////////////
// Foward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
LRESULT CALLBACK    SplashWndProc(HWND, UINT, WPARAM, LPARAM);

////////////////////////////////////////////////////////////////////////////////
// Splashscreen functions
////////////////////////////////////////////////////////////////////////////////
//
//
void HideSplashScreen()
{
    // Destroy the window
    if (IsWindow(hSplashWnd)) {
        DestroyWindow(hSplashWnd);
        DeleteObject(hBmp);
        hSplashWnd = NULL;
        UnregisterClass("RootSplashScreen", hInst);
    }
}

////////////////////////////////////////////////////////////////////////////////
//
//
BOOL CreateSplashScreen(HWND hParent)
{
    int xScreen;
    int yScreen;
    // Crenter the splashscreen
    xScreen = GetSystemMetrics(SM_CXFULLSCREEN);
    yScreen = GetSystemMetrics(SM_CYFULLSCREEN);

    hSplashWnd = CreateWindowEx(
            WS_EX_TOOLWINDOW,
            "RootSplashScreen",
            NULL,
            WS_POPUP | WS_VISIBLE,
            (xScreen - 360)/2,
            (yScreen - 240)/2,
            360, 240,
            hParent,
            NULL,
            hInst,
            NULL);

    return (hSplashWnd != NULL);
}

////////////////////////////////////////////////////////////////////////////////
//
//
BOOL PreTranslateMessage(MSG* pMsg)
{
    if (!IsWindow(hSplashWnd))
        return FALSE;

    // If we get a keyboard or mouse message, hide the splash screen.
    if (pMsg->message == WM_KEYDOWN ||
        pMsg->message == WM_SYSKEYDOWN ||
        pMsg->message == WM_LBUTTONDOWN ||
        pMsg->message == WM_RBUTTONDOWN ||
        pMsg->message == WM_MBUTTONDOWN ||
        pMsg->message == WM_NCLBUTTONDOWN ||
        pMsg->message == WM_NCRBUTTONDOWN ||
        pMsg->message == WM_NCMBUTTONDOWN)
    {
        HideSplashScreen();
        return TRUE;    // message handled here
    }

    return FALSE;   // message not handled
}

void CreateSplash(DWORD time)
{
    MSG msg;
    if (MyRegisterClass(hInst) != 0)
        bClassRegistered = TRUE;
    if(time > 0) {
        bSplash = TRUE;
        DelayVal = time * 1000;
    }
    else return;
    // Create the splash screen
    if (bSplash)
        CreateSplashScreen(NULL);

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0)) {
        PreTranslateMessage(&msg);
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    HideSplashScreen();
}

///////////////////////////////////////////////////////////////////////////////
//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = (WNDPROC)SplashWndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = NULL;
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = NULL;
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = "RootSplashScreen";
    wcex.hIconSm        = NULL;
    return RegisterClassEx(&wcex);
}

////////////////////////////////////////////////////////////////////////////
// Message handler for splash screen.
//
LRESULT CALLBACK SplashWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
    HDC hDC;
    HANDLE hfbm;
    BITMAPFILEHEADER bmfh;
    BITMAPINFOHEADER bmih;
    HGLOBAL hmem1,hmem2;
    LPBITMAPINFO lpbmi;
    LPVOID lpvBits;
    DWORD dwRead;
    HWND hwndFound;         // this is what is returned to the caller
    char pszNewWindowTitle[MY_BUFSIZE]; // contains fabricated WindowTitle
    char pszOldWindowTitle[MY_BUFSIZE]; // contains original WindowTitle
    const char bmpDir[] = "\\icons\\Splash.bmp";
    char FullBmpDir[128];
    char *RootSysDir;
    int xScreen;
    int yScreen;

    switch (message)
    {
        case WM_CREATE:
            SetTimer(hWnd, ID_SPLASHSCREEN, DelayVal, NULL);
            RootSysDir = getenv("ROOTSYS");
            sprintf(FullBmpDir,"%s%s",RootSysDir,bmpDir);
            // Retrieve a handle identifying the file.
            hfbm = CreateFile(FullBmpDir, GENERIC_READ,
                    FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL,
                    OPEN_EXISTING, FILE_ATTRIBUTE_READONLY,
                    (HANDLE) NULL);
            if(hfbm) {
                // Retrieve the BITMAPFILEHEADER structure.
                ReadFile(hfbm, &bmfh, sizeof(BITMAPFILEHEADER), &dwRead,
                        (LPOVERLAPPED)NULL);
                // Retrieve the BITMAPFILEHEADER structure.
                ReadFile(hfbm, &bmih, sizeof(BITMAPINFOHEADER),
                        &dwRead, (LPOVERLAPPED)NULL);
                // Allocate memory for the BITMAPINFO structure.
                hmem1 = GlobalAlloc(GHND, sizeof(BITMAPINFOHEADER) +
                        ((1<<bmih.biBitCount) * sizeof(RGBQUAD)));
                lpbmi = (LPBITMAPINFO)GlobalLock(hmem1);
                // Load BITMAPINFOHEADER into the BITMAPINFO structure.
                lpbmi->bmiHeader.biSize = bmih.biSize;
                lpbmi->bmiHeader.biWidth = bmih.biWidth;
                lpbmi->bmiHeader.biHeight = bmih.biHeight;
                lpbmi->bmiHeader.biPlanes = bmih.biPlanes;
                lpbmi->bmiHeader.biBitCount = bmih.biBitCount;
                lpbmi->bmiHeader.biCompression = bmih.biCompression;
                lpbmi->bmiHeader.biSizeImage = bmih.biSizeImage;
                lpbmi->bmiHeader.biXPelsPerMeter = bmih.biXPelsPerMeter;
                lpbmi->bmiHeader.biYPelsPerMeter = bmih.biYPelsPerMeter;
                lpbmi->bmiHeader.biClrUsed = bmih.biClrUsed;
                lpbmi->bmiHeader.biClrImportant = bmih.biClrImportant;
                // Retrieve the color table.
                // 1 << bmih.biBitCount == 2 ^ bmih.biBitCount
                ReadFile(hfbm, lpbmi->bmiColors,
                        ((1<<bmih.biBitCount) * sizeof(RGBQUAD)),
                        &dwRead, (LPOVERLAPPED) NULL);
                // Allocate memory for the required number of bytes.
                hmem2 = GlobalAlloc(GHND, (bmfh.bfSize - bmfh.bfOffBits));
                lpvBits = GlobalLock(hmem2);
                // Retrieve the bitmap data.
                ReadFile(hfbm, lpvBits, (bmfh.bfSize - bmfh.bfOffBits),
                        &dwRead, (LPOVERLAPPED) NULL);
                hDC = GetDC(hWnd);
                // Create a bitmap from the data stored in the .BMP file.
                hBmp = CreateDIBitmap(hDC, &bmih, CBM_INIT, lpvBits, lpbmi, DIB_RGB_COLORS);
                // Unlock the global memory objects and close the .BMP file.
                GlobalUnlock(hmem1);
                GlobalUnlock(hmem2);
                CloseHandle(hfbm);
                GetObjectA(hBmp, sizeof(bm), &bm);
                // Center the splashscreen
                xScreen = GetSystemMetrics(SM_CXFULLSCREEN);
                yScreen = GetSystemMetrics(SM_CYFULLSCREEN);
                SetWindowPos(hWnd, HWND_TOPMOST, (xScreen - bm.bmWidth)/2,
                    (yScreen - bm.bmHeight)/2, bm.bmWidth, bm.bmHeight, 0 );
            }
            break;

        case WM_TIMER:
            if (wParam == ID_SPLASHSCREEN) {
                KillTimer (hWnd, ID_SPLASHSCREEN);
                HideSplashScreen();
            }
            break;

        case WM_DESTROY:
            PostQuitMessage(0);

        case WM_PAINT:
            hDC = BeginPaint(hWnd, &ps);
            // TODO: Add any drawing code here...
            RECT rt;
            GetClientRect(hWnd, &rt);
            HDC hImageDC;
            hImageDC = CreateCompatibleDC(hDC);
            if (hImageDC == NULL)
                return FALSE;
            // Paint the image.
            HBITMAP hOldBitmap;
            hOldBitmap = (HBITMAP)SelectObject(hImageDC, hBmp);
            BitBlt(hDC, 0, 0, bm.bmWidth, bm.bmHeight, hImageDC, 0, 0, SRCCOPY);
            SelectObject(hImageDC, hOldBitmap);
            EndPaint(hWnd, &ps);
             // fetch current window title
            GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
            // format a "unique" NewWindowTitle
            wsprintf(pszNewWindowTitle,"%d/%d", GetTickCount(), GetCurrentProcessId());
            // change current window title
            SetConsoleTitle(pszNewWindowTitle);
            // ensure window title has been updated
            Sleep(40);
            // look for NewWindowTitle
            hwndFound=FindWindow(NULL, pszNewWindowTitle);
            // restore original window title
            ShowWindow(hwndFound, SW_RESTORE);
            SetForegroundWindow(hwndFound);
            SetConsoleTitle("ROOT session");
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}
#endif
<|endoftext|>


<commit_before>/**
 * @author  MyungHyun Lee (Kent)
 * @date    2009-01-30
 */

#include <ProcessOptions.h>
#include <net/message_framework.h>
#include <net/MFServer.h>
#include <LAManager.h>

#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include <vector>
#include <string>

#include <iostream>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "LaServiceHandle.h"

using namespace std;
using namespace boost;
using namespace sf1v5_dummy;
using namespace messageframework;

namespace LaProcess {

//void initMFClient();
//void initMFServer();
//void initServiceList();
//int registerServiceList();

/*
 void initMFClient()
 {
 //-H -I -P -C -S -N
 MessageFrameworkNode controllerNode( po.getControllerIp(), po.getControllerPort() );
 client_ = new MessageClient( MF_CLIENT_ARG( "DocumentProcess_Server", controllerNode ) );
 }

void initMFServer() {
	MessageFrameworkNode controllerNode(po.getControllerIp(),
			po.getControllerPort() );
	server_ = new MessageServer( MF_SERVER_ARG( "LAProcess_Server", po.getHostPort(), controllerNode ) );

	cout << "[LAProcess]: MF up and ready to go" << endl;
}

/*
void initServiceList(vector<ServiceInfo> & serviceList) {
	ServiceInfo serviceInfo;
	//vector<ServiceParameterType> params;

	serviceInfo.setServer(po.getControllerIp(), po.getControllerPort() );
	//serviceInfo.setPermissionFlag(SERVE_AT_SERVER);

	serviceInfo.setServiceName("parseString");
	//params.clear();
	//params.push_back(STRING_TYPE);
	//serviceInfo.setParameterList(params);
	serviceList.push_back(serviceInfo);
}

int registerServiceList(const vector<ServiceInfo> & serviceList) {
	unsigned int i = 0;
	unsigned int nTimeout = 0;
	int failCnt = 0;
	bool ret = false;

	server_->setAgentInfo("col1");
	for (i = 0; i < serviceList.size(); i++) {
		while ( !(ret = server_->registerService(serviceList[i]) ) && nTimeout
				< 100) {
			cout << "[LAProcess] service registration failed, trying again."
					<< endl;
			boost::thread::sleep(boost::get_system_time()
					+ boost::posix_time::milliseconds(10) );
			nTimeout++;
		}
		if (ret == false) {
			failCnt++;
		}
	}

	return failCnt;
}

long la_time = 0;

void parseString(LAManager& laMgr, ServiceMessagePtr &sm)
{
	   // sm->display();
        for(int i=0; i<sm->getBufferNum(); i++){
           string str;
				vector<string> termList;
				mf_deserialize(str, sm, i);
				//cout<<"Input: "<<str<<endl;
				laMgr.parseString(str, termList);
				// cout<<"Output: "<<endl;
				//for(int j=0; j<termList.size();j++){
				//	cout<<termList[j]<<endl;
				//}
				mf_serialize(termList, sm, i);
        	}
}

int laServerMain() {
	int ret = 0;

	vector<ServiceInfo> serviceList;
	vector<ServiceRequestInfoPtr> requestList;

	initServiceList(serviceList);
	if ( (ret = registerServiceList(serviceList)) != 0) {
		cerr << "[LAProcess]: number of failed service registrations: " << ret
				<< endl;
		return -1;
	}

	cout << "[LAProcess]: Running server... " << endl;
	while (true) {
		// check if there is a request
		server_->getServiceRequestList(requestList);

		std::vector<ServiceResultPtr> serviceResults;
		serviceResults.reserve(requestList.size());

		//std::vector<boost::shared_ptr<VariantType> > paramList;
		//ServiceResultPtr serviceResult(new ServiceResult);
		ServiceResultPtr serviceResult;

		posix_time::ptime begin = posix_time::microsec_clock::local_time();

		//cerr << "\t[LAPROCES]: requestList.size= : " << requestList.size()
		//		<< endl;

		for (unsigned int i = 0; i < requestList.size(); i++) {
			//serviceResult->clear();

			//requestList[i]->display();
			if (requestList[i]->getServiceName() == "parseString") {
				//shared_ptr<string> str( new string );
				//shared_ptr<vector<string> > termList( new vector<string>() );
				parseString(laMgr_, requestList[i]);
				server_->putResultOfService(requestList[i]);

			}

			//serviceResults.push_back(serviceResult);
			//cerr << "\t[LAPROCES]: serviceResults: size= "
			//		<<serviceResults.size()<<endl;

		}

		posix_time::ptime end = posix_time::microsec_clock::local_time();
		la_time += (end-begin).total_microseconds();

		std::cout << "[PROFILE] la_time total " << la_time << std::endl;
	}
}*/
}

MF_AUTO_MAIN(laProcess) {
	using namespace LaProcess;

	LAManagerPtr  laMgr_(new LAManager);
	sf1v5_dummy::ProcessOptions po;

	if ( !po.setLaProcessOptions(argc, argv)) {
		return 0;
	}

	//MessageFrameworkNodePtr  mfnode(new  MessageFrameworkNode(controllerNode( po.getControllerIp(), po.getControllerPort() ) );

	MFServer<LAServiceHandle> laServer(4, po.getHostPort(), po.getControllerIp(), po.getControllerPort() );

	boost::unordered_map<std::string, ServiceItem<LAServiceHandle> > serviceList;
	{
				ServiceItem<LAServiceHandle> item;
				item.callback_ = &LAServiceHandle::parseString;
				serviceList[ "parseString" ] = item;
	}

	laServer.createServiceList(serviceList);
	cout << "[LAProcess]: MF up and ready to go" << endl;

	boost::shared_ptr<LAServiceHandle> lash( new LAServiceHandle);
	lash->setLAManager(laMgr_);

	laServer.setServiceHandle(lash);
	laServer.setAgentInfo("la");

	laServer.run();
	// client_ = new MessageClient( MF_CLIENT_ARG( "DocumentProcess_Server", controllerNode ) );

	//initMFServer();
	//initMFClient();

	//laServerMain();
	//boost::thread serverThread( &laServerMain );
	//serverThread.join();

	return 1;
}

<commit_msg>la-main.cpp<commit_after>/**
 * @author  MyungHyun Lee (Kent)
 * @date    2009-01-30
 */

#include <ProcessOptions.h>
#include <net/message_framework.h>
#include <net/MFServer.h>
#include <LAManager.h>

#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include <vector>
#include <string>

#include <iostream>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "LaServiceHandle.h"

using namespace std;
using namespace boost;
using namespace sf1v5_dummy;
using namespace messageframework;

namespace LaProcess {

//void initMFClient();
//void initMFServer();
//void initServiceList();
//int registerServiceList();

/*
 void initMFClient()
 {
 //-H -I -P -C -S -N
 MessageFrameworkNode controllerNode( po.getControllerIp(), po.getControllerPort() );
 client_ = new MessageClient( MF_CLIENT_ARG( "DocumentProcess_Server", controllerNode ) );
 }

 void initMFServer() {
 MessageFrameworkNode controllerNode(po.getControllerIp(),
 po.getControllerPort() );
 server_ = new MessageServer( MF_SERVER_ARG( "LAProcess_Server", po.getHostPort(), controllerNode ) );

 cout << "[LAProcess]: MF up and ready to go" << endl;
 }

 /*
 void initServiceList(vector<ServiceInfo> & serviceList) {
 ServiceInfo serviceInfo;
 //vector<ServiceParameterType> params;

 serviceInfo.setServer(po.getControllerIp(), po.getControllerPort() );
 //serviceInfo.setPermissionFlag(SERVE_AT_SERVER);

 serviceInfo.setServiceName("parseString");
 //params.clear();
 //params.push_back(STRING_TYPE);
 //serviceInfo.setParameterList(params);
 serviceList.push_back(serviceInfo);
 }

 int registerServiceList(const vector<ServiceInfo> & serviceList) {
 unsigned int i = 0;
 unsigned int nTimeout = 0;
 int failCnt = 0;
 bool ret = false;

 server_->setAgentInfo("col1");
 for (i = 0; i < serviceList.size(); i++) {
 while ( !(ret = server_->registerService(serviceList[i]) ) && nTimeout
 < 100) {
 cout << "[LAProcess] service registration failed, trying again."
 << endl;
 boost::thread::sleep(boost::get_system_time()
 + boost::posix_time::milliseconds(10) );
 nTimeout++;
 }
 if (ret == false) {
 failCnt++;
 }
 }

 return failCnt;
 }

 long la_time = 0;

 void parseString(LAManager& laMgr, ServiceMessagePtr &sm)
 {
 // sm->display();
 for(int i=0; i<sm->getBufferNum(); i++){
 string str;
 vector<string> termList;
 mf_deserialize(str, sm, i);
 //cout<<"Input: "<<str<<endl;
 laMgr.parseString(str, termList);
 // cout<<"Output: "<<endl;
 //for(int j=0; j<termList.size();j++){
 //	cout<<termList[j]<<endl;
 //}
 mf_serialize(termList, sm, i);
 }
 }

 int laServerMain() {
 int ret = 0;

 vector<ServiceInfo> serviceList;
 vector<ServiceRequestInfoPtr> requestList;

 initServiceList(serviceList);
 if ( (ret = registerServiceList(serviceList)) != 0) {
 cerr << "[LAProcess]: number of failed service registrations: " << ret
 << endl;
 return -1;
 }

 cout << "[LAProcess]: Running server... " << endl;
 while (true) {
 // check if there is a request
 server_->getServiceRequestList(requestList);

 std::vector<ServiceResultPtr> serviceResults;
 serviceResults.reserve(requestList.size());

 //std::vector<boost::shared_ptr<VariantType> > paramList;
 //ServiceResultPtr serviceResult(new ServiceResult);
 ServiceResultPtr serviceResult;

 posix_time::ptime begin = posix_time::microsec_clock::local_time();

 //cerr << "\t[LAPROCES]: requestList.size= : " << requestList.size()
 //		<< endl;

 for (unsigned int i = 0; i < requestList.size(); i++) {
 //serviceResult->clear();

 //requestList[i]->display();
 if (requestList[i]->getServiceName() == "parseString") {
 //shared_ptr<string> str( new string );
 //shared_ptr<vector<string> > termList( new vector<string>() );
 parseString(laMgr_, requestList[i]);
 server_->putResultOfService(requestList[i]);

 }

 //serviceResults.push_back(serviceResult);
 //cerr << "\t[LAPROCES]: serviceResults: size= "
 //		<<serviceResults.size()<<endl;

 }

 posix_time::ptime end = posix_time::microsec_clock::local_time();
 la_time += (end-begin).total_microseconds();

 std::cout << "[PROFILE] la_time total " << la_time << std::endl;
 }
 }*/
}

void InitLAServer(MFServer<LAServiceHandle>& laServer) {
	boost::unordered_map<std::string, ServiceItem<LAServiceHandle> > serviceList;
	{
		ServiceItem<LAServiceHandle> item;
		item.callback_ = &LAServiceHandle::parseString;
		serviceList[ "parseString" ] = item;
	}

	laServer.createServiceList(serviceList);

	LAManagerPtr laMgr_(new LAManager);
	boost::shared_ptr<LAServiceHandle> lash(new LAServiceHandle);
	lash->setLAManager(laMgr_);

	laServer.setServiceHandle(lash);
	laServer.setAgentInfo("la");
}

MF_AUTO_MAIN(laProcess) {
	using namespace LaProcess;

	sf1v5_dummy::ProcessOptions po;

	if ( !po.setLaProcessOptions(argc, argv)) {
		return 0;
	}

	//MessageFrameworkNodePtr  mfnode(new  MessageFrameworkNode(controllerNode( po.getControllerIp(), po.getControllerPort() ) );

	MFServer<LAServiceHandle> laServer(4, po.getHostPort(),
			po.getControllerIp(), po.getControllerPort() );

	cout << "[LAProcess]: MF up and ready to go" << endl;

	InitLAServer(laServer);

	laServer.run();

	// client_ = new MessageClient( MF_CLIENT_ARG( "DocumentProcess_Server", controllerNode ) );

	//initMFServer();
	//initMFClient();

	//laServerMain();
	//boost::thread serverThread( &laServerMain );
	//serverThread.join();

	return 1;
}

<|endoftext|>