Example #1
1
int main(int argc, char**argv) {
    
    // Create an LLVM Module by calling makeLLVMModule()
    // Access the LLVM Module through a module owner
    std::unique_ptr<Module> Owner(makeLLVMModule());
    Module* Mod = Owner.get();

    // Verify the LLVM Module - check syntax and semantics
    verifyModule(*Mod, &errs());

    // Create a 'Pass Manager' for the compiler pipeline
    // Configure the Pass Manager with available / custom passes
    legacy::PassManager PM;
    PM.add(createPrintModulePass(outs()));
    
    // Run the LLVM Module through the pipeline managed by the Pass Manager.
    // The pipeline has a single 'print' pass which will stream out the LLVM Module as LLVM IR
    PM.run(*Mod);

    // Now let's check if the LLVM Module is functionally correct. To do this, we will test the module
    // with concrete values, execute the module on an 'ExecutionEngine' (which can be configured as a
    // JIT compiler or an interpreter), and verify if the output matches the expected result.
    std::string errStr;
    ExecutionEngine *Engine = EngineBuilder(std::move(Owner)).setErrorStr(&errStr).create();

    if (!Engine) {
        errs() << argv[0] << ": Failed to construct the Execution Engine: " << errStr << "\n";
        return -1; // Add a error macro
    }

    // Input values 2,3,4.
    // Expected value: mul_add(2,3,4) = 2 * 3 + 4 = 10
    std::vector<GenericValue> Args(3);
    Args[0].IntVal = APInt(32, 2);
    Args[1].IntVal = APInt(32, 3);
    Args[2].IntVal = APInt(32, 4);

    GenericValue GV = Engine->runFunction(mul_add, Args);

    outs() << "\nCalling mul_add( " << Args[0].IntVal << ", " << Args[1].IntVal << ", " << Args[2].IntVal <<" )";
    outs() << "\nResult: " << GV.IntVal << "\n";
    if( GV.IntVal == (Args[0].IntVal * Args[1].IntVal + Args[2].IntVal) )
    {
        outs() << "\n\nResult matches expectation!!";
        outs() << "\nMyFirstModule is a perfect LLVM Module :)";
    }
    else
    {
        outs() << "\n\nOops! Result doesn't match expectation. Check mul_add again.";
    }

    delete Mod;
    return 0;
}
Example #2
0
casefoldFunctionType caseFoldCodeGen(void) {
                            
    Module * M = new Module("casefold", getGlobalContext());
    
    IDISA::IDISA_Builder * idb = GetIDISA_Builder(M);

    kernel::PipelineBuilder pipelineBuilder(M, idb);

    Encoding encoding(Encoding::Type::UTF_8, 8);
    
    pablo::PabloFunction * function = casefold2pablo(encoding);
    

    pipelineBuilder.CreateKernels(function);

    pipelineBuilder.ExecuteKernels();

    //std::cerr << "ExecuteKernels(); done\n";
    llvm::Function * main_IR = M->getFunction("Main");
    ExecutionEngine * mEngine = JIT_to_ExecutionEngine(M);
    
    mEngine->finalizeObject();
    //std::cerr << "finalizeObject(); done\n";

    delete idb;

    return reinterpret_cast<casefoldFunctionType>(mEngine->getPointerToFunction(main_IR));
}
Example #3
0
/*!
  Sets the value of this QJSValue's property with the given \a name to
  the given \a value.

  If this QJSValue is not an object, this function does nothing.

  If this QJSValue does not already have a property with name \a name,
  a new property is created.

  \sa property(), deleteProperty()
*/
void QJSValue::setProperty(const QString& name, const QJSValue& value)
{
    ExecutionEngine *engine = d->engine;
    if (!engine)
        return;
    Scope scope(engine);

    Scoped<Object> o(scope, d->value);
    if (!o)
        return;

    if (!value.d->checkEngine(o->engine())) {
        qWarning("QJSValue::setProperty(%s) failed: cannot set value created in a different engine", name.toUtf8().constData());
        return;
    }

    ScopedString s(scope, engine->newString(name));
    uint idx = s->asArrayIndex();
    if (idx < UINT_MAX) {
        setProperty(idx, value);
        return;
    }

    QV4::ExecutionContext *ctx = engine->currentContext();
    s->makeIdentifier();
    QV4::ScopedValue v(scope, value.d->getValue(engine));
    o->put(s, v);
    if (scope.hasException())
        ctx->catchException();
}
Example #4
0
int run(unique_ptr<Module> module, Chars_const fnName, const vector<string> args) {
  
  check(module, "no module");
  
  Function* entryFn = module->getFunction(fnName);
  check(entryFn, "Source file does not contain a function of the given name");
  
  // Use an EngineBuilder to configure and construct an MCJIT ExecutionEngine.
#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR <= 5
  EngineBuilder builder(module.release());
  builder.setUseMCJIT(true);
#else
  const EngineBuilder builder(move(module));
  const SectionMemoryManager mm;
  builder.setMCJITMemoryManager(&mm);
#endif
  string errorStr;
  builder.setErrorStr(&errorStr);
  builder.setEngineKind(EngineKind::JIT);
  builder.setOptLevel(CodeGenOpt::None);
  
  ExecutionEngine* engine = builder.create();
  
  // Call 'finalizeObject' to notify the JIT that we're ready to execute the jitted code,
  // then run the static constructors.
  engine->finalizeObject();
  engine->runStaticConstructorsDestructors(false);
  
  // Pass the args to the jitted function, and capture the result.
  const int result = engine->runFunctionAsMain(entryFn, args, nullptr);
  engine->runStaticConstructorsDestructors(true); // Run the static destructors.
  return result;
}
Example #5
0
/*!
  Creates a new \c{Object} and calls this QJSValue as a
  constructor, using the created object as the `this' object and
  passing \a args as arguments. If the return value from the
  constructor call is an object, then that object is returned;
  otherwise the default constructed object is returned.

  If this QJSValue is not a function, callAsConstructor() does
  nothing and returns an undefined QJSValue.

  Calling this function can cause an exception to occur in the
  script engine; in that case, the value that was thrown
  (typically an \c{Error} object) is returned. You can call
  isError() on the return value to determine whether an
  exception occurred.

  \sa call(), QJSEngine::newObject()
*/
QJSValue QJSValue::callAsConstructor(const QJSValueList &args)
{
    FunctionObject *f = d->value.asFunctionObject();
    if (!f)
        return QJSValue();

    ExecutionEngine *engine = d->engine;
    assert(engine);

    Scope scope(engine);
    ScopedCallData callData(scope, args.size());
    for (int i = 0; i < args.size(); ++i) {
        if (!args.at(i).d->checkEngine(engine)) {
            qWarning("QJSValue::callAsConstructor() failed: cannot construct function with argument created in a different engine");
            return QJSValue();
        }
        callData->args[i] = args.at(i).d->getValue(engine);
    }

    ScopedValue result(scope);
    QV4::ExecutionContext *ctx = engine->currentContext();
    result = f->construct(callData);
    if (scope.hasException())
        result = ctx->catchException();

    return new QJSValuePrivate(engine, result);
}
Example #6
0
void Object::defineDefaultProperty(const QString &name, const Value &value)
{
    ExecutionEngine *e = engine();
    Scope scope(e);
    ScopedString s(scope, e->newIdentifier(name));
    defineDefaultProperty(s, value);
}
Example #7
0
ReturnedValue Lookup::lookup(Object *thisObject, PropertyAttributes *attrs)
{
    Heap::Object *obj = thisObject->d();
    ExecutionEngine *engine = thisObject->engine();
    Identifier *name = engine->currentContext()->compilationUnit->runtimeStrings[nameIndex]->identifier;
    int i = 0;
    while (i < Size && obj) {
        classList[i] = obj->internalClass;

        index = obj->internalClass->find(name);
        if (index != UINT_MAX) {
            level = i;
            *attrs = obj->internalClass->propertyData.at(index);
            return !attrs->isAccessor() ? obj->memberData->data[index].asReturnedValue() : thisObject->getValue(obj->propertyAt(index), *attrs);
        }

        obj = obj->prototype;
        ++i;
    }
    level = Size;

    while (obj) {
        index = obj->internalClass->find(name);
        if (index != UINT_MAX) {
            *attrs = obj->internalClass->propertyData.at(index);
            return !attrs->isAccessor() ? obj->memberData->data[index].asReturnedValue() : thisObject->getValue(obj->propertyAt(index), *attrs);
        }

        obj = obj->prototype;
    }
    return Primitive::emptyValue().asReturnedValue();
}
int main(int argc, char **argv) {
  int n = argc > 1 ? atol(argv[1]) : 10;

  InitializeNativeTarget();
 
  LLVMContext Context;
 
  Module *M = new Module("test", Context);
  ExecutionEngine* EE = llvm::EngineBuilder(M).setEngineKind(EngineKind::JIT).create();
 
  for (int i = 0; i < n; ++i) {
    SMDiagnostic error;
    ParseAssemblyString(function_assembly,
                        M,
                        error,
                        Context);
 
    Function *func = M->getFunction( "factorial" );
 
    typedef int(*func_t)(int);
    func_t f = (func_t)(uintptr_t)(EE->getPointerToFunction(func));
 
    EE->freeMachineCodeForFunction(func);
    func->eraseFromParent();
  }
 
  delete EE;
 
  llvm_shutdown();
 
  return 0;
}
int main(int argc, char **argv) {
  int n = argc > 1 ? atol(argv[1]) : 24;

  LLVMContext Context;
  
  // Create some module to put our function into it.
  Module *M = new Module("test", Context);

  // We are about to create the "fib" function:
  Function *FibF = CreateFibFunction(M, Context);

  // Now we going to create JIT
  ExecutionEngine *EE = EngineBuilder(M).create();

  errs() << "verifying... ";
  if (verifyModule(*M)) {
    errs() << argv[0] << ": Error constructing function!\n";
    return 1;
  }

  errs() << "OK\n";
  errs() << "We just constructed this LLVM module:\n\n---------\n" << *M;
  errs() << "---------\nstarting fibonacci(" << n << ") with JIT...\n";

  // Call the Fibonacci function with argument n:
  std::vector<GenericValue> Args(1);
  Args[0].IntVal = APInt(32, n);
  GenericValue GV = EE->runFunction(FibF, Args);

  // import result of execution
  outs() << "Result: " << GV.IntVal << "\n";
  return 0;
}
Example #10
0
static void llvm_init(){
    ExecutionEngine *ee = tcg_llvm_ctx->getExecutionEngine();
    FunctionPassManager *fpm = tcg_llvm_ctx->getFunctionPassManager();
    Module *mod = tcg_llvm_ctx->getModule();
    LLVMContext &ctx = mod->getContext();

    // Link logging function in with JIT
    Function *logFunc;
    std::vector<Type*> argTypes;
    // DynValBuffer*
    argTypes.push_back(IntegerType::get(ctx, 8*sizeof(uintptr_t)));
    // DynValEntryType
    argTypes.push_back(IntegerType::get(ctx, 8*sizeof(DynValEntryType)));
    // LogOp
    argTypes.push_back(IntegerType::get(ctx, 8*sizeof(LogOp)));
    // Dynamic value
    argTypes.push_back(IntegerType::get(ctx, 8*sizeof(uintptr_t)));
    logFunc = Function::Create(
            FunctionType::get(Type::getVoidTy(ctx), argTypes, false),
            Function::ExternalLinkage, "log_dynval", mod);
    logFunc->addFnAttr(Attribute::AlwaysInline);
    ee->addGlobalMapping(logFunc, (void*) &log_dynval);
    
    // Create instrumentation pass and add to function pass manager
    llvm::FunctionPass *instfp = createPandaInstrFunctionPass(mod);
    fpm->add(instfp);
    PIFP = static_cast<PandaInstrFunctionPass*>(instfp);
}
Example #11
0
		ArrayObject<T>* allocateArray(ArrayType type, size_t arraySize)
		{
			ExecutionEngine * eng = new ExecutionEngine();
			eng->heap = new Heap();
			eng->objectTable = new ObjectTable();
			Method m = getMethod();

			m.byteCode = new Instruction[2];
			m.byteCode[0] = (Instruction)InstructionSet::NEWARRAY;
			m.byteCode[1] = (Instruction)type;
			m.byteCodeLength = 2;

			MethodFrame frm(2, 2);
			frm.operandStack->push(arraySize);

			frm.pc = 0;
			frm.method = &m;

			eng->execute(&frm);

			int result = frm.operandStack->pop();

			Assert::AreNotEqual(0, result);
			Assert::AreEqual(1, result);

			ArrayObject<T> * objectPtr = (ArrayObject<T> *) eng->objectTable->get(result);

			return objectPtr;
		}
void QEnginioCollectionObjectPrivate::QmlCallbackFunctor::operator ()(QEnginioOperationObject *aOperation)
{
    using namespace QV4;

    if (!aOperation)
        return;

    if (iCallback.isCallable()) {
        QJSValuePrivate *prv=QJSValuePrivate::get(iCallback);
        FunctionObject *f =prv->value.asFunctionObject();

        if (f) {
            ExecutionEngine *engine = prv->engine;
            Q_ASSERT(engine);

            Scope scope(engine);
            ScopedCallData callData(scope, 1); // args.length());
            callData->thisObject = engine->globalObject->asReturnedValue();

            ScopedValue result(scope);
            QV4::ExecutionContext *ctx = engine->currentContext();

            callData->args[0] = QObjectWrapper::wrap(engine,aOperation);

            result = f->call(callData);
            if (scope.hasException()) {
                result = ctx->catchException();
            }
            QJSValue tmp(new QJSValuePrivate(engine, result));
        }
    }

    delete aOperation;
}
Example #13
0
int main()
{
    InitializeNativeTarget();
    llvm_start_multithreaded();
    LLVMContext context;
    string error;
    OwningPtr<llvm::MemoryBuffer> fileBuf;
    MemoryBuffer::getFile("hw.bc", fileBuf);
    ErrorOr<Module*> m = parseBitcodeFile(fileBuf.get(), context);
    ExecutionEngine *ee = ExecutionEngine::create(m.get());

    Function* func = ee->FindFunctionNamed("main");
    std::cout << "hop " << m.get()  << " ee " << ee << " f " << func << std::endl;

    typedef void (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    pfn();

    Function* f = ee->FindFunctionNamed("fib");
    std::cout << "big " << f << std::endl;

    //    typedef std::function<int(int)> fibType;
    typedef int (*fibType)(int);
    fibType ffib = reinterpret_cast<fibType>(ee->getPointerToFunction(f));
    std::cout << "fib " << ffib(7) << std::endl;



    delete ee;
}
void Object::defineAccessorProperty(const QString &name, ReturnedValue (*getter)(CallContext *), ReturnedValue (*setter)(CallContext *))
{
    ExecutionEngine *e = engine();
    Scope scope(e);
    Scoped<String> s(scope, e->newIdentifier(name));
    defineAccessorProperty(s, getter, setter);
}
Example #15
0
int main() {
    LLVMInitializeNativeTarget();
    LLVMInitializeNativeAsmPrinter();
    LLVMInitializeNativeAsmParser();

    LLVMContext &Context = getGlobalContext();
    IRBuilder<> Builder(Context);
    std::unique_ptr<Module> Owner = make_unique<Module>("simple_module", Context);
    Module *M = Owner.get();

    Function *F = Function::Create(TypeBuilder<int32_t(void), false>::get(Context),
                                   GlobalValue::ExternalLinkage, "scramble", M);
    BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
    Builder.SetInsertPoint(BB);
    Builder.CreateRet(ConstantInt::get(Context, APInt(32, 24)));

    F = Function::Create(TypeBuilder<int32_t(void), false>::get(Context),
                         GlobalValue::ExternalLinkage, "ooo1", M);
    BB = BasicBlock::Create(Context, "entry", F);
    Builder.SetInsertPoint(BB);
    Builder.CreateRet(ConstantInt::get(Context, APInt(32, 42)));

    M->dump();
    ExecutionEngine *EE = EngineBuilder(std::move(Owner)).create();
    assert(EE != NULL && "error creating MCJIT with EngineBuilder");
    union {
        uint64_t raw;
        int (*usable)();
    } functionPointer;
    functionPointer.raw = EE->getFunctionAddress("ooo1");
    std::cout << functionPointer.usable() << std::endl;

    return 0;
}
Example #16
0
void* getPointerToFunction(Module * mod, Function * func)
{
    ExecutionEngine * execEngine = createExecutionEngine(mod);
    if (!execEngine) exit(-1);

    return execEngine->getPointerToFunction(func);
}
Example #17
0
/*!
  Returns the value of this QJSValue's property with the given \a name.
  If no such property exists, an undefined QJSValue is returned.

  If the property is implemented using a getter function (i.e. has the
  PropertyGetter flag set), calling property() has side-effects on the
  script engine, since the getter function will be called (possibly
  resulting in an uncaught script exception). If an exception
  occurred, property() returns the value that was thrown (typically
  an \c{Error} object).

  \sa setProperty(), hasProperty(), QJSValueIterator
*/
QJSValue QJSValue::property(const QString& name) const
{
    ExecutionEngine *engine = d->engine;
    if (!engine)
        return QJSValue();
    QV4::Scope scope(engine);

    ScopedObject o(scope, d->value);
    if (!o)
        return QJSValue();

    ScopedString s(scope, engine->newString(name));
    uint idx = s->asArrayIndex();
    if (idx < UINT_MAX)
        return property(idx);

    s->makeIdentifier();
    QV4::ExecutionContext *ctx = engine->currentContext();
    QV4::ScopedValue result(scope);
    result = o->get(s);
    if (scope.hasException())
        result = ctx->catchException();

    return new QJSValuePrivate(engine, result);
}
Example #18
0
int main(int argc, char **argv)
{
  using namespace llvm;

  std::cout << "hello_world_ir: " << std::endl;
  std::cout << std::endl;
  std::cout << hello_world_ir << std::endl;
  std::cout << std::endl;

  InitializeNativeTarget();

  LLVMContext context;
  SMDiagnostic error;

  Module *m = ParseIR(MemoryBuffer::getMemBuffer(StringRef(hello_world_ir)), error, context);
  if(!m)
  {
    error.print(argv[0], errs());
  }

  ExecutionEngine *ee = ExecutionEngine::create(m);

  Function *func = ee->FindFunctionNamed("hello_world");

  typedef void (*fcn_ptr)();
  fcn_ptr hello_world = reinterpret_cast<fcn_ptr>(ee->getPointerToFunction(func));
  hello_world();
  delete ee;

  return 0;
}
int main()
{
   TestClass tc;
   tc.setHealth(100);
   tc.printHealth();
   
   InitializeNativeTarget();
   LLVMContext context;
   string error;

   auto mb = MemoryBuffer::getFile("bitcode/damage.bc");
   if (!mb) {
      cout << "ERROR: Failed to getFile" << endl;
      return 0;
   }

   auto m = parseBitcodeFile(mb->get(), context);
   if(!m) {
      cout << "ERROR: Failed to load script file." << endl;
      return 0;
   }
   
   ExecutionEngine *ee = ExecutionEngine::create(m.get());

   // NOTE: Function names are mangled by the compiler.
   Function* init_func = ee->FindFunctionNamed("_Z9initilizev");
   if(!init_func) {
      cout << "ERROR: Failed to find 'initilize' function." << endl;
      return 0;
   }

   Function* attack_func = ee->FindFunctionNamed("_Z6attackP9TestClass");
   if(!attack_func) {
      cout << "ERROR: Failed to find 'attack' function." << endl;
      return 0;
   }

   typedef void (*init_pfn)();
   init_pfn initilize = reinterpret_cast<init_pfn>(ee->getPointerToFunction(init_func));
   if(!initilize) {
      cout << "ERROR: Failed to cast 'initilize' function." << endl;
      return 0;
   }

   initilize();
   cout << "Running attacking script..." << endl;

   typedef void (*attack_pfn)(TestClass*);
   attack_pfn attack = reinterpret_cast<attack_pfn>(ee->getPointerToFunction(attack_func));
   if(!attack) {
      cout << "ERROR: Failed to cast 'attack' function." << endl;
      return 0;
   }

   attack(&tc);
   
   tc.printHealth();
   delete ee;
}
Example #20
0
ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {

    InitializeNativeTarget();
    InitializeNativeTargetAsmPrinter();
    InitializeNativeTargetAsmParser();

    PassRegistry * Registry = PassRegistry::getPassRegistry();
    initializeCore(*Registry);
    initializeCodeGen(*Registry);
    initializeLowerIntrinsicsPass(*Registry);

    std::string errMessage;
    EngineBuilder builder{std::unique_ptr<Module>(m)};
    builder.setErrorStr(&errMessage);
    builder.setMCPU(sys::getHostCPUName());
    TargetOptions opts = InitTargetOptionsFromCodeGenFlags();
    builder.setTargetOptions(opts);
    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
    switch (OptLevel) {
        case '0': optLevel = CodeGenOpt::None; break;
        case '1': optLevel = CodeGenOpt::Less; break;
        case '2': optLevel = CodeGenOpt::Default; break;
        case '3': optLevel = CodeGenOpt::Aggressive; break;
        default: errs() << OptLevel << " is an invalid optimization level.\n";
    }
    builder.setOptLevel(optLevel);

    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
        std::vector<std::string> attrs;
        attrs.push_back("avx2");
        builder.setMAttrs(attrs);
    }
    // builder.selectTarget();

    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
        if (IROutputFilename.empty()) {
            m->dump();
        } else {
            std::error_code error;
            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
            m->print(out, nullptr);
        }
    }

    ExecutionEngine * engine = builder.create();
    ICGrepObjectCache * cache = nullptr;
    if (engine == nullptr) {
        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
    }
    if (EnableObjectCache) {
        if (ObjectCacheDir.empty())
            // Default is $HOME/.cache/icgrep
            cache = new ICGrepObjectCache();
        else
            cache = new ICGrepObjectCache(ObjectCacheDir);
        engine->setObjectCache(cache);
    }
    return engine;
}
Example #21
0
// LLVMRemoveModule exists in LLVM's C bindings,
// but it requires pointless parameters
extern "C" LLVMBool LLVMExecutionEngineRemoveModule(
    LLVMExecutionEngineRef eeref, LLVMModuleRef mref)
{
    ExecutionEngine *ee = unwrap(eeref);
    Module *m = unwrap(mref);

    return ee->removeModule(m);
}
Example #22
0
void Object::defineAccessorProperty(const QString &name, void (*getter)(const BuiltinFunction *, Scope &, CallData *),
                                    void (*setter)(const BuiltinFunction *, Scope &, CallData *))
{
    ExecutionEngine *e = engine();
    Scope scope(e);
    ScopedString s(scope, e->newIdentifier(name));
    defineAccessorProperty(s, getter, setter);
}
void Object::defineDefaultProperty(const StringRef name, ReturnedValue (*code)(CallContext *), int argumentCount)
{
    ExecutionEngine *e = engine();
    Scope scope(e);
    Scoped<FunctionObject> function(scope, e->newBuiltinFunction(e->rootContext, name, code));
    function->defineReadonlyProperty(e->id_length, Primitive::fromInt32(argumentCount));
    defineDefaultProperty(name, function);
}
Example #24
0
GenericValue CodeGenContext::runCode() {
    std::cout << "Running code ...\n";
    ExecutionEngine* ee = EngineBuilder(module_).create();
    vector<GenericValue> noargs;
    GenericValue v = ee->runFunction(main_func_, noargs);
    std::cout << "Code was run.\n";
    return v;
}
Example #25
0
extern "C" void*
LLVMRustExecuteJIT(void* mem,
                   LLVMPassManagerRef PMR,
                   LLVMModuleRef M,
                   CodeGenOpt::Level OptLevel,
                   bool EnableSegmentedStacks) {

  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();

  std::string Err;
  TargetOptions Options;
  Options.JITExceptionHandling = true;
  Options.JITEmitDebugInfo = true;
  Options.NoFramePointerElim = true;
  Options.EnableSegmentedStacks = EnableSegmentedStacks;
  PassManager *PM = unwrap<PassManager>(PMR);
  RustMCJITMemoryManager* MM = (RustMCJITMemoryManager*) mem;

  assert(MM);

  PM->add(createBasicAliasAnalysisPass());
  PM->add(createInstructionCombiningPass());
  PM->add(createReassociatePass());
  PM->add(createGVNPass());
  PM->add(createCFGSimplificationPass());
  PM->add(createFunctionInliningPass());
  PM->add(createPromoteMemoryToRegisterPass());
  PM->run(*unwrap(M));

  ExecutionEngine* EE = EngineBuilder(unwrap(M))
    .setErrorStr(&Err)
    .setTargetOptions(Options)
    .setJITMemoryManager(MM)
    .setOptLevel(OptLevel)
    .setUseMCJIT(true)
    .setAllocateGVsWithCode(false)
    .create();

  if(!EE || Err != "") {
    LLVMRustError = Err.c_str();
    return 0;
  }

  MM->invalidateInstructionCache();
  Function* func = EE->FindFunctionNamed("_rust_main");

  if(!func || Err != "") {
    LLVMRustError = Err.c_str();
    return 0;
  }

  void* entry = EE->getPointerToFunction(func);
  assert(entry);

  return entry;
}
Example #26
0
LLVMExecutionEngineRef
mono_llvm_create_ee (LLVMModuleProviderRef MP, AllocCodeMemoryCb *alloc_cb, FunctionEmittedCb *emitted_cb, ExceptionTableCb *exception_cb)
{
  std::string Error;

  force_pass_linking ();

  LLVMInitializeX86Target ();
  LLVMInitializeX86TargetInfo ();

  llvm::cl::ParseEnvironmentOptions("mono", "MONO_LLVM", "", false);

  mono_mm = new MonoJITMemoryManager ();
  mono_mm->alloc_cb = alloc_cb;

#if LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION < 8
   DwarfExceptionHandling = true;
#else
   JITExceptionHandling = true;
#endif
  // PrettyStackTrace installs signal handlers which trip up libgc
  DisablePrettyStackTrace = true;

  ExecutionEngine *EE = ExecutionEngine::createJIT (unwrap (MP), &Error, mono_mm, CodeGenOpt::Default);
  if (!EE) {
	  errs () << "Unable to create LLVM ExecutionEngine: " << Error << "\n";
	  g_assert_not_reached ();
  }
  EE->InstallExceptionTableRegister (exception_cb);
  EE->RegisterJITEventListener (new MonoJITEventListener (emitted_cb));

  fpm = new FunctionPassManager (unwrap (MP));

  fpm->add(new TargetData(*EE->getTargetData()));
  /* Add a default set of passes */
  //createStandardFunctionPasses (fpm, 2);
  fpm->add(createInstructionCombiningPass());
  fpm->add(createReassociatePass());
  fpm->add(createGVNPass());
  fpm->add(createCFGSimplificationPass());

  /* The one used by opt is:
   * -simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify
   */

  /* Add passes specified by the env variable */
  /* Only the passes in force_pass_linking () can be used */
  for (unsigned i = 0; i < PassList.size(); ++i) {
      const PassInfo *PassInf = PassList[i];
      Pass *P = 0;

      if (PassInf->getNormalCtor())
		  P = PassInf->getNormalCtor()();
	  fpm->add (P);
  }

  return wrap(EE);
}
Example #27
0
/* Executes the AST by running the main function */
GenericValue CodeGenContext::runCode() {
	std::cout << "Running code...\n";
	ExistingModuleProvider *mp = new ExistingModuleProvider(module);
	ExecutionEngine *ee = ExecutionEngine::create(mp, false);
	vector<GenericValue> noargs;
	GenericValue v = ee->runFunction(mainFunction, noargs);
	std::cout << "Code was run.\n";
	return v;
}
Example #28
0
void * compile(llvm::Module * m) {
    ExecutionEngine * engine =
      EngineBuilder(std::unique_ptr<Module>(m))
      .create();
    engine->finalizeObject();

    return engine->getPointerToFunction(
        m->getFunction("aFun"));
}
Example #29
0
void Object::defineDefaultProperty(String *name, void (*code)(const BuiltinFunction *, Scope &, CallData *), int argumentCount)
{
    ExecutionEngine *e = engine();
    Scope scope(e);
    ExecutionContext *global = e->rootContext();
    ScopedFunctionObject function(scope, BuiltinFunction::create(global, name, code));
    function->defineReadonlyConfigurableProperty(e->id_length(), Primitive::fromInt32(argumentCount));
    defineDefaultProperty(name, function);
}
Example #30
0
/* Executes the AST by running the main function */
GenericValue CodeGenContext::runCode() {
	std::cout << "Running code...\n";
	InitializeNativeTarget();
	ExecutionEngine *ee = ExecutionEngine::create(module, false);
	vector<GenericValue> noargs;
	GenericValue v = ee->runFunction(mainFunction, noargs);
	std::cout << "Code was run.\n";
	return v;
}