You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

12 months ago
#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRStmtBuilder.h"
#include "Module.h"
#include "Type.h"
#include <iostream>
#include <memory>
#ifdef DEBUG
#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 code");
auto builder = IRStmtBuilder::create(nullptr, module);
SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
SysYF::Ptr<Type> FloatType = Type::get_float_type(module);
auto zero_initializer = ConstantZero::create(Int32Type, module);
auto a = GlobalVariable::create("a", module, Int32Type, false, zero_initializer);
// main function
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
"main", module);
auto bb = BasicBlock::create(module, "entry", mainFun);
builder->set_insert_point(bb);
auto retAlloca = builder->create_alloca(Int32Type);
// store 10 to a
builder->create_store(CONST_INT(10), a);
auto aValue = builder->create_load(a);
// if(a > 0)
auto icmp = builder->create_icmp_gt(aValue, CONST_INT(0));
auto trueBB = BasicBlock::create(module, "trueBB_if", mainFun); // true分支
auto falseBB = BasicBlock::create(module, "falseBB_if", mainFun); // false分支
builder->create_cond_br(icmp, trueBB, falseBB); // 条件BR
// if true return a
builder->set_insert_point(trueBB);
builder->create_ret(aValue);
// if false return 0
builder->set_insert_point(falseBB);
builder->create_ret(CONST_INT(0));
std::cout << module->print();
12 months ago
return 0;
}