1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include "llvm/IR/Module.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/Linker/Linker.h"
using namespace llvm;
int main(int argc, const char **argv) { LLVMContext context; std::unique_ptr<Module> m = std::make_unique<Module>("hello", context); IRBuilder<> builder(context);
FunctionType *main_type = FunctionType::get( builder.getInt32Ty(), false); Function *main_func = Function::Create(main_type, GlobalValue::ExternalLinkage, "main", *m);
FunctionType *add_type = FunctionType::get( builder.getInt32Ty(), { builder.getInt32Ty(), builder.getInt32Ty() }, false ); Function *add_func = Function::Create(add_type, GlobalValue::ExternalLinkage, "add", *m);
BasicBlock *block = BasicBlock::Create(context, "entry", main_func); builder.SetInsertPoint(block);
Value *ret = builder.CreateCall(add_func, { builder.getInt32(3), builder.getInt32(6) });
builder.CreateRet(ret);
std::unique_ptr<Module> m2 = std::make_unique<Module>("add", context); add_func = Function::Create(add_type, GlobalValue::ExternalLinkage, "add", *m2); block = BasicBlock::Create(context, "entry", add_func); builder.SetInsertPoint(block); Value *v1 = add_func->getArg(0); Value *v2 = add_func->getArg(1); ret = builder.CreateNSWAdd(v1, v2); builder.CreateRet(ret);
Module dest("dest", context); Linker linker(dest); linker.linkInModule(std::move(m), Linker::Flags::OverrideFromSrc);
linker.linkInModule(std::move(m2), Linker::Flags::OverrideFromSrc);
dest.print(errs(), nullptr);
return 0; }
|