|
|
#include "BasicBlock.h"
|
|
|
#include "Constant.h"
|
|
|
#include "Function.h"
|
|
|
#include "IRStmtBuilder.h"
|
|
|
#include "Module.h"
|
|
|
#include "Type.h"
|
|
|
|
|
|
#include <iostream>
|
|
|
#include <memory>
|
|
|
|
|
|
#ifdef DEBUG // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项
|
|
|
#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl; // 输出行号的简单示例
|
|
|
#else
|
|
|
#define DEBUG_OUTPUT
|
|
|
#endif
|
|
|
|
|
|
#define CONST_INT(num) \
|
|
|
ConstantInt::create(num, module)
|
|
|
|
|
|
#define CONST_FP(num) \
|
|
|
ConstantFloat::create(num, module) // 得到常数值的表示,方便后面多次用到
|
|
|
|
|
|
using namespace SysYF::IR;
|
|
|
|
|
|
int main() {
|
|
|
auto module = Module::create("if_test.sy"); // module name是if_test
|
|
|
auto builder = IRStmtBuilder::create(nullptr, module);
|
|
|
SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
|
|
|
|
|
|
// 生成一个全局变量a
|
|
|
auto zero_initializer = ConstantZero::create(Int32Type, module);
|
|
|
auto a = GlobalVariable::create("a", module, Int32Type, false, zero_initializer);
|
|
|
|
|
|
// 生成main函数
|
|
|
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
|
|
|
"main", module);
|
|
|
// 生成一个基本块并进入
|
|
|
auto entry = BasicBlock::create(module, "entry", mainFun);
|
|
|
builder->set_insert_point(entry);
|
|
|
|
|
|
// 给a赋值给10。
|
|
|
builder->create_store(CONST_INT(10), a); // store参数n
|
|
|
|
|
|
// 把a加载到寄存器
|
|
|
auto aReg = builder->create_load(a);
|
|
|
|
|
|
// 创造一个比较语句,就是说a>0
|
|
|
auto icmp = builder->create_icmp_gt(aReg, CONST_INT(0)); // n和4的比较
|
|
|
|
|
|
// 创造两个基本块,真 or 假
|
|
|
auto trueBB = BasicBlock::create(module, "true", mainFun); // true分支
|
|
|
auto falseBB = BasicBlock::create(module, "false", mainFun); // false分支
|
|
|
|
|
|
// 创建一个分支br
|
|
|
builder->create_cond_br(icmp, trueBB, falseBB);
|
|
|
|
|
|
// 构建真的返回
|
|
|
builder->set_insert_point(trueBB);
|
|
|
builder->create_ret(aReg);
|
|
|
|
|
|
// 构建假的返回
|
|
|
builder->set_insert_point(falseBB);
|
|
|
builder->create_ret(CONST_INT(0));
|
|
|
|
|
|
std::cout << module->print();
|
|
|
return 0;
|
|
|
}
|