1987319d3SReid Spencer //===-- examples/HowToUseJIT/HowToUseJIT.cpp - An example use of the JIT --===//
2b987b7ceSReid Spencer //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b987b7ceSReid Spencer //
7b987b7ceSReid Spencer //===----------------------------------------------------------------------===//
8b987b7ceSReid Spencer //
9b987b7ceSReid Spencer //  This small program provides an example of how to quickly build a small
10b987b7ceSReid Spencer //  module with two functions and execute it with the JIT.
11b987b7ceSReid Spencer //
12b987b7ceSReid Spencer // Goal:
13b987b7ceSReid Spencer //  The goal of this snippet is to create in the memory
14b987b7ceSReid Spencer //  the LLVM module consisting of two functions as follow:
15b987b7ceSReid Spencer //
16b987b7ceSReid Spencer // int add1(int x) {
17b987b7ceSReid Spencer //   return x+1;
18b987b7ceSReid Spencer // }
19b987b7ceSReid Spencer //
20b987b7ceSReid Spencer // int foo() {
21b987b7ceSReid Spencer //   return add1(10);
22b987b7ceSReid Spencer // }
23b987b7ceSReid Spencer //
24b987b7ceSReid Spencer // then compile the module via JIT, then execute the `foo'
25b987b7ceSReid Spencer // function and return result to a driver, i.e. to a "host program".
26b987b7ceSReid Spencer //
27b987b7ceSReid Spencer // Some remarks and questions:
28b987b7ceSReid Spencer //
29b987b7ceSReid Spencer // - could we invoke some code using noname functions too?
30b987b7ceSReid Spencer //   e.g. evaluate "foo()+foo()" without fears to introduce
31b987b7ceSReid Spencer //   conflict of temporary function name with some real
32b987b7ceSReid Spencer //   existing function name?
33b987b7ceSReid Spencer //
34b987b7ceSReid Spencer //===----------------------------------------------------------------------===//
35b987b7ceSReid Spencer 
3685c9bacaSNAKAMURA Takumi #include "llvm/ADT/STLExtras.h"
372b8e4170SEugene Zelenko #include "llvm/ExecutionEngine/ExecutionEngine.h"
38605e30e9SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h"
392b8e4170SEugene Zelenko #include "llvm/IR/Argument.h"
402b8e4170SEugene Zelenko #include "llvm/IR/BasicBlock.h"
41005f27a0SChandler Carruth #include "llvm/IR/Constants.h"
42005f27a0SChandler Carruth #include "llvm/IR/DerivedTypes.h"
432b8e4170SEugene Zelenko #include "llvm/IR/Function.h"
44005f27a0SChandler Carruth #include "llvm/IR/IRBuilder.h"
45005f27a0SChandler Carruth #include "llvm/IR/Instructions.h"
46005f27a0SChandler Carruth #include "llvm/IR/LLVMContext.h"
47005f27a0SChandler Carruth #include "llvm/IR/Module.h"
482b8e4170SEugene Zelenko #include "llvm/IR/Type.h"
492b8e4170SEugene Zelenko #include "llvm/Support/Casting.h"
5073312b3fSTorok Edwin #include "llvm/Support/ManagedStatic.h"
51605e30e9SChandler Carruth #include "llvm/Support/TargetSelect.h"
520c19df48SChris Lattner #include "llvm/Support/raw_ostream.h"
532b8e4170SEugene Zelenko #include <algorithm>
542b8e4170SEugene Zelenko #include <cassert>
552b8e4170SEugene Zelenko #include <memory>
562b8e4170SEugene Zelenko #include <vector>
578ad343f2SEric Christopher 
58b987b7ceSReid Spencer using namespace llvm;
59b987b7ceSReid Spencer 
60b987b7ceSReid Spencer int main() {
61d24df245SChris Lattner   InitializeNativeTarget();
62d24df245SChris Lattner 
636773d388SOwen Anderson   LLVMContext Context;
646773d388SOwen Anderson 
65b987b7ceSReid Spencer   // Create some module to put our function into it.
66*0eaee545SJonas Devlieghere   std::unique_ptr<Module> Owner = std::make_unique<Module>("test", Context);
672a8a2795SRafael Espindola   Module *M = Owner.get();
68b987b7ceSReid Spencer 
69b987b7ceSReid Spencer   // Create the add1 function entry and insert this entry into module M.  The
70b987b7ceSReid Spencer   // function will have a return type of "int" and take an argument of "int".
71b800b392SChris Lattner   Function *Add1F =
7213680223SJames Y Knight       Function::Create(FunctionType::get(Type::getInt32Ty(Context),
7313680223SJames Y Knight                                          {Type::getInt32Ty(Context)}, false),
7413680223SJames Y Knight                        Function::ExternalLinkage, "add1", M);
75b987b7ceSReid Spencer 
76b987b7ceSReid Spencer   // Add a basic block to the function. As before, it automatically inserts
77b987b7ceSReid Spencer   // because of the last argument.
7855f1c09eSOwen Anderson   BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
79b987b7ceSReid Spencer 
808ad343f2SEric Christopher   // Create a basic block builder with default parameters.  The builder will
818ad343f2SEric Christopher   // automatically append instructions to the basic block `BB'.
828ad343f2SEric Christopher   IRBuilder<> builder(BB);
838ad343f2SEric Christopher 
84b987b7ceSReid Spencer   // Get pointers to the constant `1'.
858ad343f2SEric Christopher   Value *One = builder.getInt32(1);
86b987b7ceSReid Spencer 
87b987b7ceSReid Spencer   // Get pointers to the integer argument of the add1 function...
88222dcd44SAlkis Evlogimenos   assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
895717ecbaSDuncan P. N. Exon Smith   Argument *ArgX = &*Add1F->arg_begin();          // Get the arg
90b987b7ceSReid Spencer   ArgX->setName("AnArg");            // Give it a nice symbolic name for fun.
91b987b7ceSReid Spencer 
92b987b7ceSReid Spencer   // Create the add instruction, inserting it into the end of BB.
938ad343f2SEric Christopher   Value *Add = builder.CreateAdd(One, ArgX);
94b987b7ceSReid Spencer 
95b987b7ceSReid Spencer   // Create the return instruction and add it to the basic block
968ad343f2SEric Christopher   builder.CreateRet(Add);
97b987b7ceSReid Spencer 
98b987b7ceSReid Spencer   // Now, function add1 is ready.
99b987b7ceSReid Spencer 
1009e4b6899SJohnny Chen   // Now we're going to create function `foo', which returns an int and takes no
101b987b7ceSReid Spencer   // arguments.
102b800b392SChris Lattner   Function *FooF =
10313680223SJames Y Knight       Function::Create(FunctionType::get(Type::getInt32Ty(Context), {}, false),
10413680223SJames Y Knight                        Function::ExternalLinkage, "foo", M);
105b987b7ceSReid Spencer 
106b987b7ceSReid Spencer   // Add a basic block to the FooF function.
10755f1c09eSOwen Anderson   BB = BasicBlock::Create(Context, "EntryBlock", FooF);
108b987b7ceSReid Spencer 
1098ad343f2SEric Christopher   // Tell the basic block builder to attach itself to the new basic block
1108ad343f2SEric Christopher   builder.SetInsertPoint(BB);
111b987b7ceSReid Spencer 
1128ad343f2SEric Christopher   // Get pointer to the constant `10'.
1138ad343f2SEric Christopher   Value *Ten = builder.getInt32(10);
1148ad343f2SEric Christopher 
1158ad343f2SEric Christopher   // Pass Ten to the call to Add1F
1168ad343f2SEric Christopher   CallInst *Add1CallRes = builder.CreateCall(Add1F, Ten);
117eaf625dcSChris Lattner   Add1CallRes->setTailCall(true);
118b987b7ceSReid Spencer 
119b987b7ceSReid Spencer   // Create the return instruction and add it to the basic block.
1208ad343f2SEric Christopher   builder.CreateRet(Add1CallRes);
121b987b7ceSReid Spencer 
122b987b7ceSReid Spencer   // Now we create the JIT.
1232a8a2795SRafael Espindola   ExecutionEngine* EE = EngineBuilder(std::move(Owner)).create();
124b987b7ceSReid Spencer 
1250c19df48SChris Lattner   outs() << "We just constructed this LLVM module:\n\n" << *M;
1260c19df48SChris Lattner   outs() << "\n\nRunning foo: ";
1270c19df48SChris Lattner   outs().flush();
128b987b7ceSReid Spencer 
129b987b7ceSReid Spencer   // Call the `foo' function with no arguments:
130b987b7ceSReid Spencer   std::vector<GenericValue> noargs;
131b987b7ceSReid Spencer   GenericValue gv = EE->runFunction(FooF, noargs);
132b987b7ceSReid Spencer 
133b987b7ceSReid Spencer   // Import result of execution:
1340c19df48SChris Lattner   outs() << "Result: " << gv.IntVal << "\n";
13573312b3fSTorok Edwin   delete EE;
13673312b3fSTorok Edwin   llvm_shutdown();
137b987b7ceSReid Spencer   return 0;
138b987b7ceSReid Spencer }
139