02_llvm的IR测试创建函数和代码块

如果要使用LLVM的能力,则需熟悉如何根据自己的代码生成出llvm的IR,以便提供给llvm使用。

测试创建function

测试代码如下02_test_function.cpp

#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Verifier.h"
using namespace llvm;
/*
以c语言举例,编一个c程序后,一般一个c的函数会对应生成一个llvm IR的function,
这里创建一个function就是利用llvm IR的机制手动创建LLVM IR函数的过程,
目的是以后有自己的前端时,能熟练创建输出llvm ir,然后利用llvm的中后端能力。
*/
int main() {
LLVMContext c;
Module *m = new Module("test module", c);
Type *voidTy = Type::getVoidTy(c);
/*函数在 include/llvm/IR/DerivedTypes.h:102:class FunctionType : public Type {
/// Create a FunctionType taking no parameters.
static FunctionType *get(Type *Result, bool isVarArg);
*/
FunctionType *funcTy = FunctionType::get(voidTy, false);
Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, "test_function IR", m);
verifyFunction(*func);
m->print(outs(), nullptr);
return 0;
}

编译脚本

CLANG_PATH="../output/bin/clang++"
${CLANG_PATH} -w -o test_func_bin `llvm-config --cxxflags --ldflags --system-libs --libs core` ./02_test_function.cpp

运行结果

; ModuleID = 'test module'
source_filename = "test module"
declare void @"test_function IR"()

测试创建代码块

代码和简单介绍如下

#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/IRBuilder.h"
using namespace llvm;
/*
function由基本逻辑块basic block(代码块)组成,一个block仅有一个起点和一个终点,起点是起点标签,其内容是一组IR指令,终点是最后一条指令,通常jump到其他代码块。
IRBuilder:IR代码创建工具类。
*/
int main() {
LLVMContext c;
Module *m = new Module("test module", c);
Type *voidTy = Type::getVoidTy(c);
/*函数在 include/llvm/IR/DerivedTypes.h:102:class FunctionType : public Type {
/// Create a FunctionType taking no parameters.
static FunctionType *get(Type *Result, bool isVarArg);
*/
FunctionType *funcTy = FunctionType::get(voidTy, false);
Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, "test_function IR", m);
// 创建一个block
IRBuilder<> builder(c);
BasicBlock *b = BasicBlock::Create(c, "entry_block", func);
builder.SetInsertPoint(b);
verifyFunction(*func);
m->print(outs(), nullptr);
return 0;
}

编译脚本

CLANG_PATH="../output/bin/clang++"
${CLANG_PATH} -w -o test_block_bin `llvm-config --cxxflags --ldflags --system-libs --libs core` ./03_test_block.cpp

运行结果

; ModuleID = 'test module'
source_filename = "test module"
define void @"test_function IR"() {
entry_block:
}
posted @   00lab  阅读(97)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示