LLVM learn

创建一个函数


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(), false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    verifyFunction(*fooFunc);
    return fooFunc;
}
int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");
    Function* fooFunc2 = createFunc(*Builder, "foo2");
    //Function* fooFunc2 = createFunc(Builder, "foo2");
    
    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

声明全局变量


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(), false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    BasicBlock::Create(*Context, "entry", fooFunc);
    verifyFunction(*fooFunc);
    return fooFunc;
}

GlobalVariable* createGlob(IRBuilder<>& builder, std::string Name,llvm::Type* Ty) {
    ModuleOb->getOrInsertGlobal(Name, Ty);
    GlobalVariable* gVar = ModuleOb->getNamedGlobal(Name);
    gVar->setLinkage(GlobalValue::CommonLinkage);
    gVar->setAlignment(Align(4));
    return gVar;
}
int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");
    Function* fooFunc2 = createFunc(*Builder, "foo2");
    auto gVar = createGlob(*Builder, "Hello",Builder->getInt32Ty());
    auto gVar2 = createGlob(*Builder, "Hello2", Builder->getDoubleTy());
    gVar2->setAlignment(Align(16));
    //Function* fooFunc2 = createFunc(Builder, "foo2");
    
    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

返回值和形参


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
   // Builder.reset();
    std::vector<string> Args;
    Args.push_back("a");
    Args.push_back("b");
    std::vector<Type*>Integers(Args.size(), Builder->getInt32Ty());
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(),Integers, false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    int idx = 0;
    for (auto i = fooFunc->arg_begin(); i != fooFunc->arg_end(); i += 1) {
        i->setName(Args[idx++]);
    }
    auto entry=BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Builder->CreateRet(Builder->getInt32(0));
    verifyFunction(*fooFunc);
    return fooFunc;
}

GlobalVariable* createGlob(IRBuilder<>& builder, std::string Name,llvm::Type* Ty) {
    ModuleOb->getOrInsertGlobal(Name, Ty);

    GlobalVariable* gVar = ModuleOb->getNamedGlobal(Name);
    gVar->setLinkage(GlobalValue::CommonLinkage);
    gVar->setAlignment(Align(4));
    return gVar;
}
int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");
    Function* fooFunc2 = createFunc(*Builder, "foo2");
    auto gVar = createGlob(*Builder, "Hello",Builder->getInt32Ty());
    auto gVar2 = createGlob(*Builder, "Hello2", Builder->getDoubleTy());
    gVar2->setAlignment(Align(16));
    //Function* fooFunc2 = createFunc(Builder, "foo2");
    

    
    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

if else语句生成


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
   // Builder.reset();
    std::vector<string> Args;
    Args.push_back("a");
    Args.push_back("b");
    std::vector<Type*>Integers(Args.size(), Builder->getInt32Ty());
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(),Integers, false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    int idx = 0;
    for (auto i = fooFunc->arg_begin(); i != fooFunc->arg_end(); i += 1) {
        i->setName(Args[idx++]);
    }
    auto entry=BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Value* constval=Builder->getInt32(16);
    Value* argv1 = fooFunc->arg_begin();
    Value* argv2 = fooFunc->arg_begin() + 1;
    Value* ret=Builder->CreateMul(argv1, constval, "multmp");
    Value* ret2 = Builder->CreateMul(argv2, constval, "multmp");
    Value* Cond = Builder->CreateICmpULT(argv1, argv2, "cmptmp");

    BasicBlock* ThenBB = BasicBlock::Create(*Context, "then", fooFunc);
    BasicBlock* ElseBB = BasicBlock::Create(*Context, "else", fooFunc);
    BasicBlock* MergeBB = BasicBlock::Create(*Context, "ifcond", fooFunc);
    Builder->CreateCondBr(Cond, ThenBB, ElseBB);
    Builder->SetInsertPoint(ThenBB);
    Value* thenval = Builder->CreateAdd(argv2, Builder->getInt32(2), "thenadd");
    Builder->CreateBr(MergeBB);
    Builder->SetInsertPoint(ElseBB);
    Value *ElseVal = Builder->CreateAdd(argv2, Builder->getInt32(4), "elseadd");
    Builder->CreateBr(MergeBB);
    Builder->SetInsertPoint(MergeBB);
    PHINode* phi = Builder->CreatePHI(Type::getInt32Ty(*Context), 2, "iftmp");
    phi->addIncoming(thenval, ThenBB);
    phi->addIncoming(ElseVal, ElseBB);
    Builder->CreateRet(phi);
    verifyFunction(*fooFunc);
    return fooFunc;
}

GlobalVariable* createGlob(IRBuilder<>& builder, std::string Name,llvm::Type* Ty) {
    ModuleOb->getOrInsertGlobal(Name, Ty);
    GlobalVariable* gVar = ModuleOb->getNamedGlobal(Name);
    gVar->setLinkage(GlobalValue::CommonLinkage);
    gVar->setAlignment(Align(8));
    auto *c = Builder->getInt32(0);
    gVar->setInitializer(c);
    return gVar;
}
int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");
    //Function* fooFunc2 = createFunc(*Builder, "foo2");
    auto gVar = createGlob(*Builder, "Hello",Builder->getInt32Ty());
    //auto gVar2 = createGlob(*Builder, "Hello2", Builder->getDoubleTy());
    //gVar2->setAlignment(Align(16));
    //Function* fooFunc2 = createFunc(Builder, "foo2");
    

    
    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

循环语句


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
   // Builder.reset();
    std::vector<string> Args;
    Args.push_back("a");
    Args.push_back("b");
    std::vector<Type*>Integers(Args.size(), Builder->getInt32Ty());
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(),Integers, false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    int idx = 0;
    for (auto i = fooFunc->arg_begin(); i != fooFunc->arg_end(); i += 1) {
        i->setName(Args[idx++]);
    }
    
    auto entry=BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Value* constval=Builder->getInt32(16);
    Value* argv1 = fooFunc->arg_begin();
    Value* argv2 = fooFunc->arg_begin() + 1;
    Value* ret=Builder->CreateMul(argv1, constval, "multmp");
    BasicBlock* PreBB = Builder->GetInsertBlock();
    BasicBlock* LoopBB = BasicBlock::Create(*Context, "loopBB", fooFunc);
    Builder->CreateBr(LoopBB);
    Builder->SetInsertPoint(LoopBB);
    PHINode* incVar = Builder->CreatePHI(Builder->getInt32Ty(), 2, "i");
    incVar->addIncoming(argv1, PreBB);
    Value* add = Builder->CreateAdd(incVar, Builder->getInt32(1), "nexti");
    Value* endCond = Builder->CreateICmpNE(argv2, add, "loopcond");
    BasicBlock* LoopEndBB = Builder->GetInsertBlock();
    BasicBlock* afterBB = BasicBlock::Create(*Context, "afterBB", fooFunc);
    Builder->CreateCondBr(endCond, LoopBB, afterBB);
    Builder->SetInsertPoint(afterBB);
    incVar->addIncoming(add, LoopEndBB);
    Builder->CreateRet(incVar);
    
    
    verifyFunction(*fooFunc);
    return fooFunc;
}


int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");

    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

静态数组


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(IRBuilder<>& builder, std::string Name) {
    Type* Int = Builder->getInt32Ty();
    Type* Arg = VectorType::get(Int, 2, 0);
    Type* Ptr = Arg->getPointerTo();
    FunctionType* funcType = FunctionType::get(Int, Ptr, false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    auto arg = fooFunc->arg_begin();
    arg->setName("aptr");
    BasicBlock* entry = BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Value* val = Builder->CreateGEP(Int, arg, Builder->getInt32(1), "arg1");
    Value* val2 = Builder->CreateLoad(Int, val, "retval");
    Builder->CreateRet(val2);
    return fooFunc;

}


int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");

    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}


int main() {
    init();
    Function* fooFunc = createFunc(*Builder, "foo");

    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

struct


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(std::string Name) {
    FunctionType* funcType = FunctionType::get(Builder->getVoidTy(), {},false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    BasicBlock* entry = BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    StructType* Foo = StructType::create(*Context, "Foo");
    Foo->setBody({
        Builder->getInt32Ty(),
        Builder->getInt8Ty(),
        Builder->getDoubleTy()
        });
    Value* fooBar = Builder->CreateAlloca(Foo, nullptr, "fooBar");
    Value* c = Builder->CreateGEP(Foo, fooBar, { Builder->getInt32(0),Builder->getInt32(2) });
    Builder->CreateStore(ConstantFP::get(Builder->getDoubleTy(), 3.14), c);
    verifyFunction(*fooFunc);
    return fooFunc;
    

}


int main() {
    init();
    Function* fooFunc = createFunc("foo");

    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

alloca


#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;

void init() {
    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
}
Function* createFunc(std::string Name) {
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(), {},false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    BasicBlock* entry = BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Value *ptr=Builder->CreateAlloca(Builder->getInt32Ty(),nullptr, "dataptr");
    Builder->CreateStore(Builder->getInt32(0), ptr, false);
    Value* data = Builder->CreateLoad(Builder->getInt32Ty(), ptr, "data");
    Builder->CreateRet(data);
    return fooFunc;
}
int main() {
    init();
    Function* fooFunc = createFunc("foo");
    ModuleOb->print(outs(), nullptr, false, false);
    //ModuleOb->dump();
}

new passmanager

    FunctionPassManager FPM;
    FPM.addPass(PromotePass());
    auto m = FunctionAnalysisManager();
    auto b = PassBuilder();
    b.registerFunctionAnalyses(m);
    FPM.run(*fooFunc, m);

生成可obj.

#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
#include "llvm/Transforms/Utils/Mem2Reg.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/TargetParser/Host.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/FileSystem.h"
#include<string>
#include<vector>
using namespace std;
using namespace llvm;

static unique_ptr<LLVMContext> Context;// = new LLVMContext();
static unique_ptr<Module> ModuleOb;
static unique_ptr<IRBuilder<>> Builder;
static std::unique_ptr<legacy::FunctionPassManager> TheFPM;

class Hello : public FunctionPass {
public:
    static char ID;
    Hello() : FunctionPass(ID) {}

    bool runOnFunction(Function& F) override {
        errs() << "Hello: ";
        errs().write_escaped(F.getName()) << '\n';
        return false;
    }
}; // end of struct Hello

char Hello::ID = 1010101;
static RegisterPass<Hello> X("hello", "Hello World Pass",
    false /* Only looks at CFG */,
    false /* Analysis Pass */);
void init() {
    

    Context = make_unique<LLVMContext>();
    ModuleOb = make_unique<Module>("my compiler", *Context);
    Builder = make_unique<IRBuilder<>>(*Context);
    TheFPM = std::make_unique<legacy::FunctionPassManager>(ModuleOb.get());
    
    // Do simple "peephole" optimizations and bit-twiddling optzns.
    TheFPM->add(createInstructionCombiningPass());
    // Reassociate expressions.
    TheFPM->add(createReassociatePass());
    // Eliminate Common SubExpressions.
    TheFPM->add(createGVNPass());
    // Simplify the control flow graph (deleting unreachable blocks, etc).
    TheFPM->add(createCFGSimplificationPass());

    auto t = new Hello();
    TheFPM->add(t);
    TheFPM->doInitialization();

    
}


Function* createFunc(std::string Name) {
    // Builder.reset();
    std::vector<string> Args;
    Args.push_back("a");
    Args.push_back("b");
    std::vector<Type*>Integers(Args.size(), Builder->getInt32Ty());
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(), Integers, false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *ModuleOb);
    int idx = 0;
    for (auto i = fooFunc->arg_begin(); i != fooFunc->arg_end(); i += 1) {
        i->setName(Args[idx++]);
    }
    auto entry = BasicBlock::Create(*Context, "entry", fooFunc);
    Builder->SetInsertPoint(entry);
    Value *sum=Builder->CreateMul(fooFunc->arg_begin(), fooFunc->arg_begin() + 1, "sum");
    Builder->CreateRet(sum);
    fooFunc->setCallingConv(llvm::CallingConv::C);
    verifyFunction(*fooFunc);
    return fooFunc;
}
static std::unique_ptr<DIBuilder> DBuilder;
int main() {
    init();
    Function* fooFunc = createFunc("mul");
    
    ModuleOb->print(outs(), nullptr, false, false);

    auto TargetTriple = sys::getDefaultTargetTriple();
    InitializeAllTargetInfos();
    InitializeAllTargets();
    InitializeAllTargetMCs();
    InitializeAllAsmParsers();
    InitializeAllAsmPrinters();
    std::string Error;
    auto Target = TargetRegistry::lookupTarget(TargetTriple, Error);
        
    // Print an error and exit if we couldn't find the requested target.
    // This generally occurs if we've forgotten to initialise the
    // TargetRegistry or we have a bogus target triple.
    if (!Target) {
        errs() << Error;
        return 1;
    }

    auto CPU = "generic";
    auto Features = "";

    TargetOptions opt;
    auto RM = std::optional<Reloc::Model>();
    auto TargetMachine = Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);

    ModuleOb->setDataLayout(TargetMachine->createDataLayout());
    ModuleOb->setTargetTriple(TargetTriple);
    legacy::PassManager pass;
    auto Filename = "output.obj";
    std::error_code EC;
    raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
    auto FileType = CGFT_ObjectFile;
    if (EC) {
        errs() << "Could not open file: " << EC.message();
        return 1;
    }

    if (TargetMachine->addPassesToEmitFile(pass, dest, nullptr, FileType)) {
        errs() << "TargetMachine can't emit a file of this type";
        return 1;
    }
    
    
    pass.run(*ModuleOb);
    dest.flush();

    //ModuleOb->dump();
}

创建一个alloc

std::unique_ptr<LLVMContext> TheContext;
std::unique_ptr<IRBuilder<>> Builder;
std::unique_ptr<Module> TheModule;


void init() {
    TheContext = std::make_unique<LLVMContext>();
    TheModule = std::make_unique<Module>("sysY", *TheContext);
    Builder = std::make_unique<IRBuilder<>>(*TheContext);
}

Function* createFunc(IRBuilder<>& builder, std::string Name) {
    FunctionType* funcType = FunctionType::get(Builder->getInt32Ty(), false);
    Function* fooFunc = Function::Create(funcType, Function::ExternalLinkage, Name, *TheModule);
    verifyFunction(*fooFunc);
    return fooFunc;
}

int main() {
    init();

    FunctionType* funcType = FunctionType::get(IntegerType::getInt64Ty(*TheContext), false);
    Function* func = createFunc(*Builder, "hello");
    auto entry = BasicBlock::Create(*TheContext, "entry", func);
    //return 0;
    
    Builder->SetInsertPoint(entry);
   // auto  v= Builder->CreateAlloca(Builder->getInt32Ty(), nullptr, "test");
    //func->print(outs());
    //return 0;
    auto& block = func->getEntryBlock();
    outs() << "test\n";
    IRBuilder<> tmp(&block, block.begin());
    auto val = (Constant::getIntegerValue(Builder->getInt64Ty(), APInt(32, 33, 10)));
    auto t = tmp.CreateAlloca(Builder->getDoubleTy(), nullptr);
    func->print(outs());
    Builder->CreateStore(val, t, false);
    Builder->CreateLoad(Builder->getInt32Ty(), val);
    func->print(outs());
    
}

创建数组

int main() {
    init();
    auto val = (Constant::getIntegerValue(Builder->getInt64Ty(), APInt(64, 10, 10)));
    auto t = llvm::ArrayType::get(Builder->getInt64Ty(), 100);
    auto tt = llvm::ArrayType::get(t, 100);
    auto func = createFunc(*Builder, "foo");
    BasicBlock *entry = BasicBlock::Create(*TheContext, "entry",func);
    Builder->SetInsertPoint(entry);
    Builder->CreateAlloca(t);
    Builder->CreateAlloca(tt);
    func->print(outs());
}

初始化后端


int main() {
  // Install standard binary operators.
  // 1 is lowest precedence.
  BinopPrecedence['<'] = 10;
  BinopPrecedence['+'] = 20;
  BinopPrecedence['-'] = 20;
  BinopPrecedence['*'] = 40; // highest.

  // Prime the first token.
  fprintf(stderr, "ready> ");
  getNextToken();

  InitializeModuleAndPassManager();

  // Run the main "interpreter loop" now.
  MainLoop();

  // Initialize the target registry etc.
  /*
  InitializeAllTargetInfos();
  InitializeAllTargets();
  InitializeAllTargetMCs();
  InitializeAllAsmParsers();
  InitializeAllAsmPrinters();
  */
  LLVMInitializeX86TargetInfo();
  LLVMInitializeX86Target();
  LLVMInitializeX86TargetMC();
  LLVMInitializeX86AsmParser();
  LLVMInitializeX86AsmPrinter();

  auto TargetTriple = sys::getDefaultTargetTriple();
  TheModule->setTargetTriple(TargetTriple);

  std::string Error;
  auto Target = TargetRegistry::lookupTarget(TargetTriple, Error);

  // Print an error and exit if we couldn't find the requested target.
  // This generally occurs if we've forgotten to initialise the
  // TargetRegistry or we have a bogus target triple.
  if (!Target) {
    errs() << Error;
    
    return 1;
  }

  auto CPU = "generic";
  auto Features = "";

  TargetOptions opt;
  auto RM = std::optional<Reloc::Model>();
  auto TheTargetMachine =
      Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);

  TheModule->setDataLayout(TheTargetMachine->createDataLayout());

  auto Filename = "output.o";
  std::error_code EC;
  raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);

  if (EC) {
    errs() << "Could not open file: " << EC.message();
    return 1;
  }
  
  legacy::PassManager pass;
  auto FileType = CGFT_ObjectFile;

  if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr, FileType)) {
    errs() << "TheTargetMachine can't emit a file of this type";
    return 1;
  }

  pass.run(*TheModule);
  dest.flush();

  outs() << "Wrote " << Filename << "\n";

  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值