llvm - helloworld
Contents
環境設置
- ubuntu體系:sudo apt-get install llvm
- MAC: brew install llvm
makefile (MAC)
BIN_PATH=/usr/local/Cellar/llvm/3.6.1/bin/
export PATH:=$(PATH):$(BIN_PATH)
LLVM_CONFIG=llvm-config
FLAGS= --cxxflags --ldflags --system-libs --libs core
toy: toy.cpp
clang++ -g -O3 toy.cpp `$(LLVM_CONFIG) $(FLAGS)` -o toy
clean:
rm -f toy
top module
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Support/IRBuilder.h"
int main()
{
llvm::LLVMContext& context = llvm::getGlobalContext();
llvm::Module* module = new llvm::Module("top", context);
llvm::IRBuilder<> builder(context);
module->dump( );
}
function
宣告function
無參數
llvm::FunctionType *funcType =
llvm::FunctionType::get(builder.getInt32Ty(), false);
llvm::Function *mainFunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);
有參數
std::vector< llvm::Type* > putsArgs;
putsArgs.push_back(builder.getInt8Ty()->getPointerTo());
llvm::ArrayRef< llvm::Type* > argsRef(putsArgs);
llvm::FunctionType *putsType =
llvm::FunctionType::get(builder.getInt32Ty(), argsRef, false);
定義function
引用已有的function
llvm::Constant *putsFunc = module->getOrInsertFunction("puts", putsType);
創造新的function
llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
builder.SetInsertPoint(entry);
增添function內容
新增變數
- global variable
llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
- local variable