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.

80 lines
2.8 KiB

#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("SysYF code"); // module name是什么无关紧要
auto builder = IRStmtBuilder::create(nullptr, module);
SysYF::Ptr<Type> Int32Type = Type::get_int32_type(module);
auto zero_initializer = ConstantZero::create(Int32Type, module);
auto a = GlobalVariable::create("a", module, Int32Type, false, zero_initializer);
// climbStairs函数
// 函数参数类型的vector
std::vector<SysYF::Ptr<Type>> Ints(1, Int32Type);
//通过返回值类型与参数类型列表得到函数类型
auto climbStairsFunTy = FunctionType::create(Int32Type, Ints);
// main函数
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
"main", module);
auto bb = BasicBlock::create(module, "entry", mainFun);
// BasicBlock的名字在生成中无所谓,但是可以方便阅读
builder->set_insert_point(bb);
builder->create_store(CONST_INT(10), a);
auto aLoad = builder->create_load(a);
auto trueBB = BasicBlock::create(module, "trueBB_if", mainFun); // true分支
auto falseBB = BasicBlock::create(module, "falseBB_if", mainFun); // false分支
auto icmp = builder->create_icmp_lt(CONST_INT(0), aLoad);
builder->create_cond_br(icmp, trueBB, falseBB);
builder->set_insert_point(trueBB);
builder->create_ret(aLoad);
builder->set_insert_point(falseBB);
builder->create_ret(CONST_INT(0));
// 给这么多注释了,但是可能你们还是会弄很多bug
// 所以强烈建议配置AutoComplete,效率会大大提高!
// 别人配了AutoComplete,只花1小时coding
// 你没有配AutoComplete,找method花5小时,debug花5小时,肯定哭唧唧!
// 最后,如果猜不到某个IR指令对应的C++的函数,建议把指令翻译成英语然后在method列表中搜索一下
// 最后的最后,这个例子只涉及到了一点基本的指令生成,
// 对于额外的指令,包括数组,在之后的实验中可能需要大家好好搜索一下思考一下,
// 还有涉及到的C++语法,可以在gitlab上发issue提问或者向大家提供指导
// 对于这个例子里的代码风格/用法,如果有好的建议也欢迎提出!
std::cout << module->print();
return 0;
}