美文网首页LLVM
llvm学习日记七:编写一个LLVM IR生成器

llvm学习日记七:编写一个LLVM IR生成器

作者: 鸣人的大哥 | 来源:发表于2019-11-14 15:21 被阅读0次

(已修改)
参考书:《Getting Started with LLVM Core Libraries》
参考链接:https://www.ibm.com/developerworks/opensource/library/os-createcompilerllvm1/index.html

这是一个简单的例子构建IR

一、源代码:

主要参考上面的链接,略有修改,基于LLVM9.0,一段简短的代码创建一段IR。
最后使用dump 查看创建的IR。
Xcode调试:

#include <llvm/ADT/SmallVector.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/Support/ToolOutputFile.h>
#include "llvm/IR/IRBuilder.h"

using namespace llvm;


int main() {
    LLVMContext Context;
    Module *mod = new Module("sum.ll", Context);
    IRBuilder<> builder(Context);
    FunctionType *ft = FunctionType::get(builder.getInt32Ty(),false);
    Function *mainfunc = Function::Create(ft, Function::ExternalLinkage, "main", mod);
    BasicBlock *entry = BasicBlock::Create(Context,"entrypoint",mainfunc);
    builder.SetInsertPoint(entry);
    Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
    std::vector<Type*> putsargs;
    putsargs.push_back(builder.getInt8Ty()->getPointerTo());
    ArrayRef<Type*>  argsRef(putsargs);
    FunctionType *putsType = FunctionType::get(builder.getInt32Ty(),argsRef,false);
    FunctionCallee putsFunc = mod->getOrInsertFunction("puts", putsType);
    builder.CreateCall(putsFunc,helloWorld);
    
    ConstantInt *zero = ConstantInt::get(IntegerType::getInt32Ty(Context), 0);
    builder.CreateRet(zero);
    
    
    mod->dump();
    return 0;
}



二、运行:

image.png

相关文章

网友评论

    本文标题:llvm学习日记七:编写一个LLVM IR生成器

    本文链接:https://www.haomeiwen.com/subject/knatictx.html