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
3.0 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
#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(int argc, const char * argv[]) {
auto module = Module::create("SysYF 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);
SysYF::Ptr<Type> ArrayType = Type::get_array_type(Int32Type, 2);
std::vector<SysYF::Ptr<Type>> Ints(2, Int32Type);
//add函数
auto addFunTy = FunctionType::create(Int32Type, Ints);
auto addFun = Function::create(addFunTy,
"add", module);
auto bb = BasicBlock::create(module, "entry", addFun);
builder->set_insert_point(bb);
auto a_add_alloc = builder->create_alloca(Int32Type);
auto b_add_alloc = builder->create_alloca(Int32Type);
auto ret_add_alloc = builder->create_alloca(Int32Type);
std::vector<SysYF::Ptr<Value>> args; // 获取climbStairs函数的形参,通过Function中的iterator
for (auto arg = addFun->arg_begin(); arg != addFun->arg_end(); arg++) {
args.push_back(*arg); // * 号运算符是从迭代器中取出迭代器当前指向的元素
}
builder->create_store(args[0], a_add_alloc);
builder->create_store(args[1], b_add_alloc);
auto a_add_load = builder->create_load(a_add_alloc);
auto b_add_load = builder->create_load(b_add_alloc);
auto add = builder->create_iadd(a_add_load, b_add_load);
auto sub = builder->create_isub(add, CONST_INT(1));
builder->create_store(sub, ret_add_alloc);
auto ret_add_load = builder->create_load(ret_add_alloc);
builder->create_ret(ret_add_load);
//main函数
auto mainFun = Function::create(FunctionType::create(Int32Type, {}),
"main", module);
bb = BasicBlock::create(module, "entry", mainFun);
builder->set_insert_point(bb);
auto a_main_alloc = builder->create_alloca(Int32Type);
auto b_main_alloc = builder->create_alloca(Int32Type);
auto c_main_alloc = builder->create_alloca(Int32Type);
builder->create_store(CONST_INT(2), a_main_alloc);
builder->create_store(CONST_INT(3), b_main_alloc);
builder->create_store(CONST_INT(5), c_main_alloc );
auto a_main_load = builder->create_load(a_main_alloc);
auto b_main_load = builder->create_load(b_main_alloc);
auto c_main_load = builder->create_load(c_main_alloc);
auto call = builder->create_call(addFun, {a_main_load,b_main_load});
auto add_main = builder->create_iadd(call, c_main_load);
builder->create_ret(add_main);
std::cout << module->print();
return 0;
}