Skip to content

Instantly share code, notes, and snippets.

@mudream4869
Created April 16, 2021 04:11
Show Gist options
  • Save mudream4869/5a18a7f7d93407caad831f5ab73ed0c1 to your computer and use it in GitHub Desktop.
Save mudream4869/5a18a7f7d93407caad831f5ab73ed0c1 to your computer and use it in GitHub Desktop.
LLVM Helloworld
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Value.h>
#include <llvm/Support/raw_os_ostream.h>
#include <memory>
int main() {
/*
#include <cstdio>
int main() {
printf("hello world");
return 0;
}
*/
auto theContext = std::make_unique<llvm::LLVMContext>();
auto theModule = std::make_unique<llvm::Module>("helloworld", *theContext);
auto theBuilder = std::make_unique<llvm::IRBuilder<>>(*theContext);
// prepare int
const auto int32Type = llvm::Type::getInt32Ty(*theContext);
// prepare char*
const auto int8PtrType = llvm::Type::getInt8PtrTy(*theContext);
// ----------- codegen ----------
// create main
auto mainFuncType = llvm::FunctionType::get(int32Type, false);
auto mainFunc = llvm::Function::Create(
mainFuncType, llvm::GlobalValue::ExternalLinkage, "main", *theModule);
// create printf
std::vector<llvm::Type*> printfFuncArgs{int8PtrType};
auto printfFuncType =
llvm::FunctionType::get(int32Type, printfFuncArgs, true);
auto printfFunc = llvm::Function::Create(printfFuncType,
llvm::GlobalValue::ExternalLinkage,
"printf", *theModule);
// create main block
auto mainBlock = llvm::BasicBlock::Create(*theContext, "entry",
theModule->getFunction("main"));
theBuilder->SetInsertPoint(mainBlock);
// create string
// call printf
auto helloStr = theBuilder->CreateGlobalStringPtr("hello world\n");
std::vector<llvm::Value*> callArgs{helloStr};
theBuilder->CreateCall(printfFunc, callArgs);
// return 0
theBuilder->CreateRet(llvm::Constant::getNullValue(int32Type));
// ------------------------------
std::error_code errorcode;
llvm::raw_fd_ostream stream("helloworld.ll", errorcode);
theModule->print(stream, nullptr);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment