環境設置

  • ubuntu體系:sudo apt-get install llvm
  • MAC: brew install llvm

makefile (MAC)

1
2
3
4
5
6
7
8
9
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#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

無參數

1
2
3
  llvm::FunctionType *funcType =
      llvm::FunctionType::get(builder.getInt32Ty(), false);
  llvm::Function *mainFunc = llvm::Function::Create(funcType, llvm::Function::ExternalLinkage, "main", module);

有參數

1
2
3
4
5
6
  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

1
  llvm::Constant *putsFunc = module->getOrInsertFunction("puts", putsType);

創造新的function

1
2
  llvm::BasicBlock *entry = llvm::BasicBlock::Create(context, "entrypoint", mainFunc);
  builder.SetInsertPoint(entry);

增添function內容

新增變數

  • global variable
1
  llvm::Value *helloWorld = builder.CreateGlobalStringPtr("hello world!\n");
  • local variable

Reference

Create a working compiler with the LLVM framework