diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5eaade7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ + .vscode + build + \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..96dd3cb --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,37 @@ +project(SysYFCompiler) + +cmake_minimum_required(VERSION 3.5) + +set(CMAKE_CXX_STANDARD 14) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -Wall -Wextra -Wno-unused -Wshadow -Werror -g -pedantic") + +# include generated files in project environment +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/AST) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/ErrorReporter) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/Frontend) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/SysYFIR) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/SysYFIRBuilder) + +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/AST) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/ErrorReporter) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/Frontend) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/SysYFIR) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/SysYFIRBuilder) + +add_executable( + SysYFCompiler + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp +) + +target_link_libraries( + SysYFCompiler + SysYFIRBuilder + IRLib + Driver + ASTPrinter + ErrReporter +) diff --git a/README.md b/README.md index cda0379..fa774a7 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,117 @@ -# PW6 +# PW6 实验文档 +- [PW6 实验文档](#pw6-实验文档) + - [0. 前言](#0-前言) + - [主要工作](#主要工作) + - [1. 实验要求](#1-实验要求) + - [1.1 目录结构](#11-目录结构) + - [1.2 提交要求和评分标准](#12-提交要求和评分标准) +## 0. 前言 +本次实验分为3关,为组队实验。**本次实验请务必使用git提交**。 +本次实验的目的是让大家熟悉生成中间代码所需要的相关知识: LLVM IR、 SysYF IR(LLVM IR的轻量级C++接口),并实际实现一个IR Builder。 +在开始实验之前,请确保LLVM的版本不低于10.0.1,且PATH环境变量配置正确。可以通过`lli --version`命令是否可以输出10.0.1的版本信息来验证。 + +### 主要工作 + +1. 第一部分: 了解LLVM IR。通过clang生成的.ll,了解LLVM IR与c代码的对应关系。相应文档见[phase1.md](./doc/phase1.md) +2. 第二部分: 了解SysYF IR。通过助教提供的c++例子,了解SysYF IR的c++接口及实现。相应文档见[phase2.md](./doc/phase2.md) +3. 第三部分: 使用SysYF IR,实现一个IR Builder,使其可以通过抽象语法树生成LLVM兼容的IR代码。相应文档见[phase3.md](./doc/phase3.md) +4. 实验报告:在[report.md](./report/report.md)中撰写报告。 + +## 1. 实验要求 + +### 1.1 目录结构 +除了下面指明你所要修改或提交的文件,其他文件请勿修改。 +``` log +. +├── CMakeLists.txt +├── README.md <- 实验文档说明(你在这里) +├── doc +│   ├── AST.md +│   ├── phase1.md <- 各阶段文档 +│   ├── phase2.md +│   ├── phase3.md +│   ├── SysYF语言定义.pdf +| └── SysYFIR.md <- SysYF IR 应用编程接口相关文档 +├── report +│   ├── report.md <- 需提交的实验报告 +│   └── contribution.md <- 需提交的组员贡献(队长负责填写) +├── include <- 实验所需的头文件 +│   ├── ... +│   └── SysYFIR +├── src +│   ├── ... +│   ├── SysYFIR +│   └── SysYFIRBuilder +| ├── CMakeLists.txt +| └── IRBuilder.cpp <- 你需要在第三关任务中修改的文件 +└── Student + ├── task1 <- 第一关任务相关的目录 + | ├── ll <- 需提交的LLVM IR文件(.ll)的目录(第一关) + | | ├── assign_hand.ll + |   │   ├── fun_hand.ll + |   │   ├── if_hand.ll + |   │   └── while_hand.ll + | ├── sy + | | ├── assign_test.sy + |   │   ├── fun_test.sy + |   │   ├── if_test.sy + |   │   └── while_test.sy + | └── demo + |      └── go_upstairs.c + ├── task2 <- 第二关任务相关的目录 + ├── CMakeLists.txt + | ├── cpp <- 需提交的.cpp目录(第二关) + | | ├── CMakeLists.txt + | | ├── assign_gen.cpp + |   │   ├── fun_gen.cpp + |   │   ├── if_gen.cpp + |   │   └── while_gen.cpp + | ├── sy + | | ├── assign_test.sy + |   │   ├── fun_test.sy + |   │   ├── if_test.sy + |   │   └── while_test.sy + | └── demo + |      |── CMakeLists.txt + |      |── go_upstairs.sy + |      └── go_upstairs_gen.cpp <- 打印go_upstairs.ll的cpp文件 + └── task3 + └── test + ├── test.py <- 第三关任务的评测脚本 + └── test <- 测试样例文件夹 +``` + +### 1.2 提交要求和评分标准 +* 提交要求 + 本实验的提交要求分为两部分: 实验部分的文件和报告。 + * 实验部分: + * 需要完成 `./Student/task1/ll`目录下的4个文件 + * 需要完成 `./Student/task2/cpp`目录下的4个文件 + * 需要完成 `./src/SysYFIRBuilder/IRBuilder.cpp` + * 需要在 `./report/report.md` 中撰写实验报告 + * 实验报告内容包括: + * 实验要求、问题回答、实验设计、实验难点及解决方案、实验总结、实验反馈、组间交流(具体参考[report.md](./report.md)) + * 本次实验报告**参与**评分标准. + * 提交规范: + * 不破坏目录结构(`report.md`如果需要放图片,请新建`figs`文件夹放在`./report`下,并将图片放在`figs`文件夹内) + * 不上传临时文件(凡是自动生成的文件和临时文件请不要上传) +* **组队实验要求** + * 由队长在 `./report/contribution.md` 中解释每位队员的贡献,并说明贡献比例 + * 组队实验意味着合作,但是小组间的交流是受限的,且**严格禁止**代码的共享。除此之外,如果小组和其它组进行了交流,必须在 `./report/report.md` 中记录交流的小组和你们之间交流内容 +* 评分标准: 本次实验分为3部分, 为组队实验, 请合理安排分工, 我们会根据组长填写的贡献比进行分数分配,如果对贡献比有异议的组员可根据git的提交记录申请仲裁,建议利用好git的分支功能 + * **禁止执行恶意代码,违者本次实验0分处理** + * 第一部分10分: `.ll`运行结果正确(1个2分, 注释共2分) + * 第二部分20分: `.cpp`运行结果正确(1个5分) + * 第三部分70分: 该部分成绩由5部分组成(团队代码得分, 实验报告得分, 迟交天数, 组员贡献比, 组长奖励加分) +* 实验检查 + * 线上: 助教会在educoder上检查前两部分 + * 线下: 线下检查只检查第三部分, 组长带组员到负责组长的助教处检查, 选做部分请找本次实验负责助教检查 +* 迟交规定 + * 迟交需要邮件通知助教: + * 邮箱: xuchaijun@mail.ustc.edu.cn + * 邮件主题: PW6迟交-学号 + * 内容: 包括迟交原因、最后版本commit ID、迟交时间等 +* 关于抄袭和雷同 + 经过助教和老师判定属于作业抄袭或雷同情况,所有参与方一律零分,不接受任何解释和反驳。 +如有任何问题,欢迎提issue进行批判指正。 diff --git a/Student/task1/demo/go_upstairs.c b/Student/task1/demo/go_upstairs.c new file mode 100644 index 0000000..e9176e9 --- /dev/null +++ b/Student/task1/demo/go_upstairs.c @@ -0,0 +1,28 @@ +int num[2] = {4, 8}; +int x[1]; +int n; +int tmp = 1; + +int climbStairs(int n) { + if(n < 4) + return n; + int dp[10]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + int i; + i = 3; + while(i 0? + br i1 %3, label %4, label %9 ; true->4 false->9 + + 4: ; label 4 while true + %5 = load i32, i32* @b, align 4 ; [b]+a + %6 = load i32, i32* @a, align 4 ; b+[a] + %7 = add nsw i32 %5, %6 ; b+a + store i32 %7, i32* @b, align 4; b = b+a + %8 = sub nsw i32 %6 , 1 ; a-1 + store i32 %8, i32* @a, align 4 ; a = a-1 + br label %1 + + 9: ; label 9 + %10 = load i32, i32* @b, align 4 + ret i32 %10 ; return b +} + +; 尾部:记录LLVM模块标识 +attributes #0 = { noinline nounwind optnone uwtable "frame-pointer"="all" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" } + +!llvm.module.flags = !{!0, !1, !2, !3, !4} ; LLVM模块的一些标志 +!llvm.ident = !{!5} ; LLVM的标识信息 + +!0 = !{i32 1, !"wchar_size", i32 4} ; LLVM模块标志,表示wchar_t的大小为4 +!1 = !{i32 7, !"PIC Level", i32 2} ; LLVM模块标志,表示启用位置无关代码的级别为2 +!2 = !{i32 7, !"PIE Level", i32 2} ; LLVM模块标志,表示启用可执行和链接的级别为2 +!3 = !{i32 7, !"uwtable", i32 1} ; LLVM模块标志,表示启用表格异常处理 +!4 = !{i32 7, !"frame-pointer", i32 2} ; LLVM模块标志,表示帧指针的使用级别为2 +!5 = !{!"Ubuntu clang version 14.0.0-1ubuntu1.1"} ; LLVM的标识信息,表示使用的编译器版本为Ubuntu clang version 14.0.0-1ubuntu1.1 +!6 = distinct !{!6, !7} ; 定义了一个distinct节点 +!7 = !{!"llvm.loop.mustprogress"} ; 定义了一个LLVM循环的特性 \ No newline at end of file diff --git a/Student/task1/sy/assign_test.sy b/Student/task1/sy/assign_test.sy new file mode 100644 index 0000000..87e3097 --- /dev/null +++ b/Student/task1/sy/assign_test.sy @@ -0,0 +1,6 @@ +int main(){ + float b = 1.8; + int a[2] = {2}; + a[1] = a[0] * b; + return a[1]; +} diff --git a/Student/task1/sy/func_test.sy b/Student/task1/sy/func_test.sy new file mode 100644 index 0000000..51d371f --- /dev/null +++ b/Student/task1/sy/func_test.sy @@ -0,0 +1,13 @@ +int add(int a,int b){ + return (a+b-1); +} + +int main(){ + int a; + int b; + int c; + a=3; + b=2; + c = 5; + return c + add(a,b); +} diff --git a/Student/task1/sy/if_test.sy b/Student/task1/sy/if_test.sy new file mode 100644 index 0000000..5fbc540 --- /dev/null +++ b/Student/task1/sy/if_test.sy @@ -0,0 +1,9 @@ +int a; + +int main(){ + a = 10; + if( a>0 ){ + return a; + } + return 0; +} diff --git a/Student/task1/sy/while_test.sy b/Student/task1/sy/while_test.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/Student/task1/sy/while_test.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/Student/task2/CMakeLists.txt b/Student/task2/CMakeLists.txt new file mode 100644 index 0000000..8c8c43d --- /dev/null +++ b/Student/task2/CMakeLists.txt @@ -0,0 +1,18 @@ +project(task2) + +cmake_minimum_required(VERSION 3.5) + +set(CMAKE_CXX_STANDARD 14) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -Wall -g -pedantic") + +set(SYSYF_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) + +# include generated files in project environment +include_directories(${SYSYF_SOURCE_DIR}include) +include_directories(${SYSYF_SOURCE_DIR}include/SysYFIR) +add_subdirectory(${SYSYF_SOURCE_DIR}src/SysYFIR src/SysYFIR) + +add_subdirectory(demo) +add_subdirectory(cpp) diff --git a/Student/task2/cpp/CMakeLists.txt b/Student/task2/cpp/CMakeLists.txt new file mode 100644 index 0000000..58796f3 --- /dev/null +++ b/Student/task2/cpp/CMakeLists.txt @@ -0,0 +1,36 @@ +add_executable( + assign_generator + assign_gen.cpp +) +target_link_libraries( + assign_generator + IRLib +) + +add_executable( + func_generator + func_gen.cpp +) +target_link_libraries( + func_generator + IRLib +) + +add_executable( + if_generator + if_gen.cpp +) +target_link_libraries( + if_generator + IRLib +) + +add_executable( + while_generator + while_gen.cpp +) +target_link_libraries( + while_generator + IRLib +) + \ No newline at end of file diff --git a/Student/task2/cpp/assign_gen.cpp b/Student/task2/cpp/assign_gen.cpp new file mode 100644 index 0000000..c30d8f1 --- /dev/null +++ b/Student/task2/cpp/assign_gen.cpp @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/Student/task2/cpp/func_gen.cpp b/Student/task2/cpp/func_gen.cpp new file mode 100644 index 0000000..c30d8f1 --- /dev/null +++ b/Student/task2/cpp/func_gen.cpp @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/Student/task2/cpp/if_gen.cpp b/Student/task2/cpp/if_gen.cpp new file mode 100644 index 0000000..c30d8f1 --- /dev/null +++ b/Student/task2/cpp/if_gen.cpp @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/Student/task2/cpp/while_gen.cpp b/Student/task2/cpp/while_gen.cpp new file mode 100644 index 0000000..c30d8f1 --- /dev/null +++ b/Student/task2/cpp/while_gen.cpp @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/Student/task2/demo/CMakeLists.txt b/Student/task2/demo/CMakeLists.txt new file mode 100644 index 0000000..8a83a7a --- /dev/null +++ b/Student/task2/demo/CMakeLists.txt @@ -0,0 +1,8 @@ +add_executable( + go_upstairs_generator + go_upstairs_gen.cpp +) +target_link_libraries( + go_upstairs_generator + IRLib +) diff --git a/Student/task2/demo/go_upstairs.sy b/Student/task2/demo/go_upstairs.sy new file mode 100644 index 0000000..e9176e9 --- /dev/null +++ b/Student/task2/demo/go_upstairs.sy @@ -0,0 +1,28 @@ +int num[2] = {4, 8}; +int x[1]; +int n; +int tmp = 1; + +int climbStairs(int n) { + if(n < 4) + return n; + int dp[10]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + int i; + i = 3; + while(i +#include + +#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 Int32Type = Type::get_int32_type(module); + + // 全局数组,num,x + auto arrayType_num = ArrayType::get(Int32Type, 2); + auto arrayType_x = ArrayType::get(Int32Type, 1); + auto zero_initializer = ConstantZero::create(Int32Type, module); + std::vector> init_val; + init_val.push_back(CONST_INT(4)); + init_val.push_back(CONST_INT(8)); + auto num_initializer = ConstantArray::create(arrayType_num, init_val); + auto num = GlobalVariable::create("num", module, arrayType_num, false, num_initializer);// 是否是常量定义,初始化常量(ConstantZero类) + auto x = GlobalVariable::create("x", module, arrayType_x, false, zero_initializer);// 参数解释: 名字name,所属module,全局变量类型type, + + auto n = GlobalVariable::create("n", module, Int32Type, false, zero_initializer); + auto tmp = GlobalVariable::create("tmp", module, Int32Type, false, CONST_INT(1)); + + // climbStairs函数 + // 函数参数类型的vector + std::vector> Ints(1, Int32Type); + + //通过返回值类型与参数类型列表得到函数类型 + auto climbStairsFunTy = FunctionType::create(Int32Type, Ints); + + // 由函数类型得到函数 + auto climbStairsFun = Function::create(climbStairsFunTy, + "climbStairs", module); + + // BB的名字在生成中无所谓,但是可以方便阅读 + auto bb = BasicBlock::create(module, "entry", climbStairsFun); + + builder->set_insert_point(bb); // 一个BB的开始,将当前插入指令点的位置设在bb + + auto retAlloca = builder->create_alloca(Int32Type); // 在内存中分配返回值的位置 + auto nAlloca = builder->create_alloca(Int32Type); // 在内存中分配参数n的位置 + + std::vector> args; // 获取climbStairs函数的形参,通过Function中的iterator + for (auto arg = climbStairsFun->arg_begin(); arg != climbStairsFun->arg_end(); arg++) { + args.push_back(*arg); // * 号运算符是从迭代器中取出迭代器当前指向的元素 + } + + builder->create_store(args[0], nAlloca); // store参数n + + auto retBB = BasicBlock::create( + module, "", climbStairsFun); // return分支,提前create,以便true分支可以br + + auto nLoad = builder->create_load(nAlloca); // 将参数n load上来 + auto icmp = builder->create_icmp_lt(nLoad, CONST_INT(4)); // n和4的比较,注意ICMPLT + + auto trueBB = BasicBlock::create(module, "trueBB_if", climbStairsFun); // true分支 + auto falseBB = BasicBlock::create(module, "falseBB_if", climbStairsFun); // false分支 + + builder->create_cond_br(icmp, trueBB, falseBB); // 条件BR + DEBUG_OUTPUT // 我调试的时候故意留下来的,以醒目地提醒你这个调试用的宏定义方法 + builder->set_insert_point(trueBB); // if true; 分支的开始需要SetInsertPoint设置 + nLoad = builder->create_load(nAlloca); + builder->create_store(nLoad, retAlloca); + builder->create_br(retBB); // br retBB + + builder->set_insert_point(falseBB); // if false + auto arrayType_dp = ArrayType::get(Int32Type, 10); + auto dpAlloca = builder->create_alloca(arrayType_dp); + + auto dp0Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(0)}); + builder->create_store(CONST_INT(0), dp0Gep); + + auto dp1Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(1)}); + builder->create_store(CONST_INT(1), dp1Gep); + + auto dp2Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(2)}); + builder->create_store(CONST_INT(2), dp2Gep); + + auto iAlloca = builder->create_alloca(Int32Type); + builder->create_store(CONST_INT(3), iAlloca); + + auto condBB = BasicBlock::create(module, "condBB_while", climbStairsFun); // 条件BB + trueBB = BasicBlock::create(module, "trueBB_while", climbStairsFun); // true分支 + falseBB = BasicBlock::create(module, "falseBB_while", climbStairsFun); // false分支 + + builder->create_br(condBB); + + builder->set_insert_point(condBB); + + auto iLoad = builder->create_load(iAlloca); + nLoad = builder->create_load(nAlloca); + auto add = builder->create_iadd(nLoad, CONST_INT(1)); + + icmp = builder->create_icmp_lt(iLoad, add); + builder->create_cond_br(icmp, trueBB, falseBB); + + builder->set_insert_point(trueBB); + + iLoad = builder->create_load(iAlloca); + auto sub = builder->create_isub(iLoad, CONST_INT(1)); + auto dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), sub}); + auto dp1Load = builder->create_load(dpGep); + + iLoad = builder->create_load(iAlloca); + sub = builder->create_isub(iLoad, CONST_INT(2)); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), sub}); + auto dp2Load = builder->create_load(dpGep); + + add = builder->create_iadd(dp1Load, dp2Load); + iLoad = builder->create_load(iAlloca); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), iLoad}); + builder->create_store(add, dpGep); + + iLoad = builder->create_load(iAlloca); + add = builder->create_iadd(iLoad, CONST_INT(1)); + builder->create_store(add, iAlloca); + + builder->create_br(condBB); + + builder->set_insert_point(falseBB); + nLoad = builder->create_load(nAlloca); + dpGep = builder->create_gep(dpAlloca, {CONST_INT(0), nLoad}); + auto dpLoad = builder->create_load(dpGep); + builder->create_store(dpLoad, retAlloca); + builder->create_br(retBB); + + builder->set_insert_point(retBB); // ret分支 + auto retLoad = builder->create_load(retAlloca); + builder->create_ret(retLoad); + + // main函数 + auto mainFun = Function::create(FunctionType::create(Int32Type, {}), + "main", module); + bb = BasicBlock::create(module, "entry", mainFun); + // BasicBlock的名字在生成中无所谓,但是可以方便阅读 + builder->set_insert_point(bb); + + retAlloca = builder->create_alloca(Int32Type); + auto resAlloca = builder->create_alloca(Int32Type); + + auto num0Gep = builder->create_gep(num, {CONST_INT(0), CONST_INT(0)}); // GEP: 这里为什么是{0, 0}呢? (实验报告相关) + auto num0Load = builder->create_load(num0Gep); + builder->create_store(num0Load, n); + + auto tmpLoad = builder->create_load(tmp); + auto numGep = builder->create_gep(num, {CONST_INT(0), tmpLoad}); + auto numLoad = builder->create_load(numGep); + auto x0Gep = builder->create_gep(x, {CONST_INT(0), CONST_INT(0)}); + builder->create_store(numLoad, x0Gep); + + nLoad = builder->create_load(n); + tmpLoad = builder->create_load(tmp); + add = builder->create_iadd(nLoad, tmpLoad); + auto call = builder->create_call(climbStairsFun, {add}); // 为什么这里传的是{add}呢? + builder->create_store(call, resAlloca); + + auto resLoad = builder->create_load(resAlloca); + x0Gep = builder->create_gep(x, {CONST_INT(0), CONST_INT(0)}); + auto x0Load = builder->create_load(x0Gep); + sub = builder->create_isub(resLoad, x0Load); + builder->create_store(sub, retAlloca); + retLoad = builder->create_load(retAlloca); + builder->create_ret(retLoad); + // 给这么多注释了,但是可能你们还是会弄很多bug + // 所以强烈建议配置AutoComplete,效率会大大提高! + // 别人配了AutoComplete,只花1小时coding + // 你没有配AutoComplete,找method花5小时,debug花5小时,肯定哭唧唧! + // 最后,如果猜不到某个IR指令对应的C++的函数,建议把指令翻译成英语然后在method列表中搜索一下 + // 最后的最后,这个例子只涉及到了一点基本的指令生成, + // 对于额外的指令,包括数组,在之后的实验中可能需要大家好好搜索一下思考一下, + // 还有涉及到的C++语法,可以在gitlab上发issue提问或者向大家提供指导 + // 对于这个例子里的代码风格/用法,如果有好的建议也欢迎提出! + std::cout << module->print(); + return 0; +} diff --git a/Student/task2/sy/assign_test.sy b/Student/task2/sy/assign_test.sy new file mode 100644 index 0000000..87e3097 --- /dev/null +++ b/Student/task2/sy/assign_test.sy @@ -0,0 +1,6 @@ +int main(){ + float b = 1.8; + int a[2] = {2}; + a[1] = a[0] * b; + return a[1]; +} diff --git a/Student/task2/sy/func_test.sy b/Student/task2/sy/func_test.sy new file mode 100644 index 0000000..51d371f --- /dev/null +++ b/Student/task2/sy/func_test.sy @@ -0,0 +1,13 @@ +int add(int a,int b){ + return (a+b-1); +} + +int main(){ + int a; + int b; + int c; + a=3; + b=2; + c = 5; + return c + add(a,b); +} diff --git a/Student/task2/sy/if_test.sy b/Student/task2/sy/if_test.sy new file mode 100644 index 0000000..5fbc540 --- /dev/null +++ b/Student/task2/sy/if_test.sy @@ -0,0 +1,9 @@ +int a; + +int main(){ + a = 10; + if( a>0 ){ + return a; + } + return 0; +} diff --git a/Student/task2/sy/while_test.sy b/Student/task2/sy/while_test.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/Student/task2/sy/while_test.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/Student/task3/test.py b/Student/task3/test.py new file mode 100644 index 0000000..cede8f7 --- /dev/null +++ b/Student/task3/test.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +import subprocess +import os + +IRBuild_ptn = '"{}" "-emit-ir" "-o" "{}" "{}"' +ExeGen_ptn = '"clang" "{}" "-o" "{}" "{}" "../../lib/lib.c"' +Exe_ptn = '"{}"' + +def eval(EXE_PATH, TEST_BASE_PATH, optimization): + print('===========TEST START===========') + print('now in {}'.format(TEST_BASE_PATH)) + dir_succ = True + for case in testcases: + print('Case %s:' % case, end='') + TEST_PATH = TEST_BASE_PATH + case + SY_PATH = TEST_BASE_PATH + case + '.sy' + LL_PATH = TEST_BASE_PATH + case + '.ll' + INPUT_PATH = TEST_BASE_PATH + case + '.in' + OUTPUT_PATH = TEST_BASE_PATH + case + '.out' + need_input = testcases[case] + + IRBuild_result = subprocess.run(IRBuild_ptn.format(EXE_PATH, LL_PATH, SY_PATH), shell=True, stderr=subprocess.PIPE) + if IRBuild_result.returncode == 0: + input_option = None + if need_input: + with open(INPUT_PATH, "rb") as fin: + input_option = fin.read() + + try: + subprocess.run(ExeGen_ptn.format(optimization, TEST_PATH, LL_PATH), shell=True, stderr=subprocess.PIPE) + result = subprocess.run(Exe_ptn.format(TEST_PATH), shell=True, input=input_option, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out = result.stdout.split(b'\n') + if result.returncode != b'': + out.append(str(result.returncode).encode()) + for i in range(len(out)-1, -1, -1): + out[i] = out[i].strip(b'\r') + if out[i] == b'': + out.remove(b'') + case_succ = True + with open(OUTPUT_PATH, "rb") as fout: + i = 0 + for line in fout.readlines(): + line = line.strip(b'\r').strip(b'\n') + if line == '': + continue + if out[i] != line: + dir_succ = False + case_succ = False + i = i + 1 + if case_succ: + print('\t\033[32mPass\033[0m') + else: + print('\t\033[31mWrong Answer\033[0m') + except Exception as _: + dir_succ = False + print(_, end='') + print('\t\033[31mCodeGen or CodeExecute Fail\033[0m') + finally: + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH]) + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH + ".o"]) + subprocess.call(["rm", "-rf", TEST_PATH, TEST_PATH + ".ll"]) + + else: + dir_succ = False + print('\t\033[31mIRBuild Fail\033[0m') + if dir_succ: + print('\t\033[32mSuccess\033[0m in dir {}'.format(TEST_BASE_PATH)) + else: + print('\t\033[31mFail\033[0m in dir {}'.format(TEST_BASE_PATH)) + + print('============TEST END============') + + +if __name__ == "__main__": + + # you can only modify this to add your testcase + TEST_DIRS = [ + './test/', + ] + # you can only modify this to add your testcase + + optimization = "-O0" # -O0 -O1 -O2 -O3 -O4(currently = -O3) -Ofast + for TEST_BASE_PATH in TEST_DIRS: + testcases = {} # { name: need_input } + EXE_PATH = os.path.abspath('../../build/SysYFCompiler') + testcase_list = list(map(lambda x: x.split('.'), os.listdir(TEST_BASE_PATH))) + testcase_list.sort() + for i in range(len(testcase_list)): + testcases[testcase_list[i][0]] = False + for i in range(len(testcase_list)): + testcases[testcase_list[i][0]] = testcases[testcase_list[i][0]] | (testcase_list[i][1] == 'in') + eval(EXE_PATH, TEST_BASE_PATH, optimization=optimization) diff --git a/Student/task3/test/01_main.out b/Student/task3/test/01_main.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/Student/task3/test/01_main.out @@ -0,0 +1 @@ +0 diff --git a/Student/task3/test/01_main.sy b/Student/task3/test/01_main.sy new file mode 100644 index 0000000..ade4548 --- /dev/null +++ b/Student/task3/test/01_main.sy @@ -0,0 +1,3 @@ +int main(){ + return 0; +} diff --git a/Student/task3/test/02_var_defn.out b/Student/task3/test/02_var_defn.out new file mode 100644 index 0000000..f04c001 --- /dev/null +++ b/Student/task3/test/02_var_defn.out @@ -0,0 +1 @@ +29 diff --git a/Student/task3/test/02_var_defn.sy b/Student/task3/test/02_var_defn.sy new file mode 100644 index 0000000..d0d0f2c --- /dev/null +++ b/Student/task3/test/02_var_defn.sy @@ -0,0 +1,8 @@ +int a,b; + +int main(){ + a=10; + b=5; + int c=a*2+b*1.1+3.6; + return c; +} \ No newline at end of file diff --git a/Student/task3/test/03_empty_stmt.out b/Student/task3/test/03_empty_stmt.out new file mode 100644 index 0000000..aabe6ec --- /dev/null +++ b/Student/task3/test/03_empty_stmt.out @@ -0,0 +1 @@ +21 diff --git a/Student/task3/test/03_empty_stmt.sy b/Student/task3/test/03_empty_stmt.sy new file mode 100644 index 0000000..a8c161f --- /dev/null +++ b/Student/task3/test/03_empty_stmt.sy @@ -0,0 +1,5 @@ +int main() { + int a = 10; + ; + return a * 2 + 1; +} diff --git a/Student/task3/test/04_arr_defn.out b/Student/task3/test/04_arr_defn.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/Student/task3/test/04_arr_defn.out @@ -0,0 +1 @@ +0 diff --git a/Student/task3/test/04_arr_defn.sy b/Student/task3/test/04_arr_defn.sy new file mode 100644 index 0000000..0fa1ceb --- /dev/null +++ b/Student/task3/test/04_arr_defn.sy @@ -0,0 +1,4 @@ +int a[10]; +int main(){ + return 0; +} diff --git a/Student/task3/test/05_arr_assign.out b/Student/task3/test/05_arr_assign.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/Student/task3/test/05_arr_assign.out @@ -0,0 +1 @@ +0 diff --git a/Student/task3/test/05_arr_assign.sy b/Student/task3/test/05_arr_assign.sy new file mode 100644 index 0000000..3fe56ba --- /dev/null +++ b/Student/task3/test/05_arr_assign.sy @@ -0,0 +1,5 @@ +int a[10]; +int main(){ + a[0]=1; + return 0; +} diff --git a/Student/task3/test/06_const_defn.out b/Student/task3/test/06_const_defn.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/Student/task3/test/06_const_defn.out @@ -0,0 +1 @@ +4 diff --git a/Student/task3/test/06_const_defn.sy b/Student/task3/test/06_const_defn.sy new file mode 100644 index 0000000..6804194 --- /dev/null +++ b/Student/task3/test/06_const_defn.sy @@ -0,0 +1,5 @@ +const int x=4; + +int main(){ + return x; +} \ No newline at end of file diff --git a/Student/task3/test/07_const_array_defn.out b/Student/task3/test/07_const_array_defn.out new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/Student/task3/test/07_const_array_defn.out @@ -0,0 +1 @@ +8 diff --git a/Student/task3/test/07_const_array_defn.sy b/Student/task3/test/07_const_array_defn.sy new file mode 100644 index 0000000..0ae4d90 --- /dev/null +++ b/Student/task3/test/07_const_array_defn.sy @@ -0,0 +1,7 @@ +const int a[5]={0,1,2,3,4}; +const int b = 3; +float c = a[b + 1]; + +int main(){ + return a[4] + c; +} \ No newline at end of file diff --git a/Student/task3/test/08_var_defn_func.out b/Student/task3/test/08_var_defn_func.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/Student/task3/test/08_var_defn_func.out @@ -0,0 +1 @@ +4 diff --git a/Student/task3/test/08_var_defn_func.sy b/Student/task3/test/08_var_defn_func.sy new file mode 100644 index 0000000..03ab608 --- /dev/null +++ b/Student/task3/test/08_var_defn_func.sy @@ -0,0 +1,8 @@ +int defn(){ + return 4; +} + +int main(){ + int a=defn(); + return a; +} \ No newline at end of file diff --git a/Student/task3/test/09_void_func.out b/Student/task3/test/09_void_func.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/Student/task3/test/09_void_func.out @@ -0,0 +1 @@ +5 diff --git a/Student/task3/test/09_void_func.sy b/Student/task3/test/09_void_func.sy new file mode 100644 index 0000000..2799e1e --- /dev/null +++ b/Student/task3/test/09_void_func.sy @@ -0,0 +1,13 @@ +int a,b,c; + +void add(int a,int b){ + c=a+b; + return; +} + +int main(){ + a=3; + b=2; + add(a,b); + return c; +} \ No newline at end of file diff --git a/Student/task3/test/10_if.out b/Student/task3/test/10_if.out new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Student/task3/test/10_if.out @@ -0,0 +1 @@ +1 diff --git a/Student/task3/test/10_if.sy b/Student/task3/test/10_if.sy new file mode 100644 index 0000000..a908d63 --- /dev/null +++ b/Student/task3/test/10_if.sy @@ -0,0 +1,9 @@ +int a; + +int main(){ + a = 10; + if( a>0 ){ + return 1; + } + return 0; +} diff --git a/Student/task3/test/11_if_else.out b/Student/task3/test/11_if_else.out new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/Student/task3/test/11_if_else.out @@ -0,0 +1 @@ +1 diff --git a/Student/task3/test/11_if_else.sy b/Student/task3/test/11_if_else.sy new file mode 100644 index 0000000..a4f5062 --- /dev/null +++ b/Student/task3/test/11_if_else.sy @@ -0,0 +1,10 @@ +int a; +int main(){ + a = 10; + if( a>0 ){ + return 1; + } + else{ + return 0; + } +} diff --git a/Student/task3/test/12_while.out b/Student/task3/test/12_while.out new file mode 100644 index 0000000..1e8b314 --- /dev/null +++ b/Student/task3/test/12_while.out @@ -0,0 +1 @@ +6 diff --git a/Student/task3/test/12_while.sy b/Student/task3/test/12_while.sy new file mode 100644 index 0000000..374f82d --- /dev/null +++ b/Student/task3/test/12_while.sy @@ -0,0 +1,11 @@ +int a; +int b; +int main(){ + b=0; + a=3; + while(a>0){ + b = b+a; + a = a-1; + } + return b; +} diff --git a/Student/task3/test/13_break.out b/Student/task3/test/13_break.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/Student/task3/test/13_break.out @@ -0,0 +1 @@ +5 diff --git a/Student/task3/test/13_break.sy b/Student/task3/test/13_break.sy new file mode 100644 index 0000000..55b40dc --- /dev/null +++ b/Student/task3/test/13_break.sy @@ -0,0 +1,9 @@ +int main(){ + int a=10; + while(a>0){ + a=a-1; + if(a==5) + break; + } + return a; +} \ No newline at end of file diff --git a/Student/task3/test/14_continue.out b/Student/task3/test/14_continue.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/Student/task3/test/14_continue.out @@ -0,0 +1 @@ +5 diff --git a/Student/task3/test/14_continue.sy b/Student/task3/test/14_continue.sy new file mode 100644 index 0000000..d0f9e50 --- /dev/null +++ b/Student/task3/test/14_continue.sy @@ -0,0 +1,11 @@ +int main(){ + int a=10; + while(a>0){ + if(a>5){ + a=a-1; + continue; + } + return a; + } + return a; +} \ No newline at end of file diff --git a/Student/task3/test/15_getint.in b/Student/task3/test/15_getint.in new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/Student/task3/test/15_getint.in @@ -0,0 +1 @@ +10 diff --git a/Student/task3/test/15_getint.out b/Student/task3/test/15_getint.out new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/Student/task3/test/15_getint.out @@ -0,0 +1 @@ +10 diff --git a/Student/task3/test/15_getint.sy b/Student/task3/test/15_getint.sy new file mode 100644 index 0000000..5a7c254 --- /dev/null +++ b/Student/task3/test/15_getint.sy @@ -0,0 +1,5 @@ +int main(){ + int a; + a = getint(); + return a; +} diff --git a/Student/task3/test/16_func_test.out b/Student/task3/test/16_func_test.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/Student/task3/test/16_func_test.out @@ -0,0 +1 @@ +5 diff --git a/Student/task3/test/16_func_test.sy b/Student/task3/test/16_func_test.sy new file mode 100644 index 0000000..67645a3 --- /dev/null +++ b/Student/task3/test/16_func_test.sy @@ -0,0 +1,23 @@ +int a; + +int myFunc(int a, int b, int c) { + a = 2; + { + int c; + c = 0; + if (c != 0) { + return 0; + } + } + while (b > 0) { + b = b - 1; + } + return (a)+(b); +} + +int main() { + a = (3); + int b; + b = myFunc(1, 2, 1); + return ((a+b)); +} \ No newline at end of file diff --git a/Student/task3/test/17_equal.in b/Student/task3/test/17_equal.in new file mode 100644 index 0000000..bce4388 --- /dev/null +++ b/Student/task3/test/17_equal.in @@ -0,0 +1 @@ +3 2 diff --git a/Student/task3/test/17_equal.out b/Student/task3/test/17_equal.out new file mode 100644 index 0000000..573541a --- /dev/null +++ b/Student/task3/test/17_equal.out @@ -0,0 +1 @@ +0 diff --git a/Student/task3/test/17_equal.sy b/Student/task3/test/17_equal.sy new file mode 100644 index 0000000..1453cdb --- /dev/null +++ b/Student/task3/test/17_equal.sy @@ -0,0 +1,12 @@ +int a; +int b; +int main(){ + a = getint(); + b = getint(); + if ( a == b ){ + return 1; + } + else{ + return 0; + } +} diff --git a/Student/task3/test/18_scope.out b/Student/task3/test/18_scope.out new file mode 100644 index 0000000..45a4fb7 --- /dev/null +++ b/Student/task3/test/18_scope.out @@ -0,0 +1 @@ +8 diff --git a/Student/task3/test/18_scope.sy b/Student/task3/test/18_scope.sy new file mode 100644 index 0000000..afc6d97 --- /dev/null +++ b/Student/task3/test/18_scope.sy @@ -0,0 +1,17 @@ +const int a = 5; +int b; + +int my_sum(int x, float y){ + b = a + x - y; + return b; +} + +int main(){ + int a = 7; + { + const float a = 3.3; + my_sum(a, a); + } + my_sum(a, b); + return b; +} diff --git a/Student/task3/test/19_gcd.in b/Student/task3/test/19_gcd.in new file mode 100644 index 0000000..4271cf2 --- /dev/null +++ b/Student/task3/test/19_gcd.in @@ -0,0 +1,2 @@ +4 +20 \ No newline at end of file diff --git a/Student/task3/test/19_gcd.out b/Student/task3/test/19_gcd.out new file mode 100644 index 0000000..b8626c4 --- /dev/null +++ b/Student/task3/test/19_gcd.out @@ -0,0 +1 @@ +4 diff --git a/Student/task3/test/19_gcd.sy b/Student/task3/test/19_gcd.sy new file mode 100644 index 0000000..1d20bc5 --- /dev/null +++ b/Student/task3/test/19_gcd.sy @@ -0,0 +1,34 @@ +int n; + +int gcd(int m,int n) +{ + int t; + int r; + + if(m 0) { + hanoi(getint(), 1, 2, 3); + putch(10); + n = n - 1; + } + return 0; +} diff --git a/Student/task3/test_stu/.gitkeep b/Student/task3/test_stu/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/doc/AST.md b/doc/AST.md new file mode 100755 index 0000000..54ef981 --- /dev/null +++ b/doc/AST.md @@ -0,0 +1,473 @@ +# AST + +**源码链接:** + +[SyntaxTree.h](../include/SyntaxTree.h) + +[SyntaxTree.cpp](../src/SyntaxTree.cpp) + + +## 目录 + +[Ptr](#ptr) + +[PtrLst](#ptrlist) + +[Position](#position) + +[Type](#type) + +[Binop](#binop) + +[UnaryOp](#unaryOp) + +[UnaryCondOp](#unarycondop) + +[BinaryCondOp](#binarycondop) + +[Node](#node) + +[Assembly](#assembly) + +[InitVal](#initval) + +[GlobalDef](#globaldef) + +[FuncDef](#funcdef) + +[VarDef](#vardef) + +[Stmt](#stmt) + +[AssignStmt](#assignstmt) + +[ReturnStmt](#returnstmt) + +[BlockStmt](#blockstmt) + +[EmptyStmt](#emptystmt) + +[ExprStmt](#exprstmt) + +[Expr](#expr) + +[CondExpr](#condexpr) + +[AddExpr](#addexpr) + +[UnaryCondExpr](#unarycondexpr) + +[BinaryCondExpr](#binarycondexpr) + +[BinaryExpr](#binaryexpr) + +[UnaryExpr](#unaryexpr) + +[LVal](#lval) + +[Literal](#literal) + +[FuncCallStmt](#funccallstmt) + +[FuncParam](#funcparam) + +[FuncFParamList](#funcfparamlist) + +[IfStmt](#ifstmt) + +[WhileStmt](#whilestmt) + +[BreakStmt](#breakstmt) + +[ContinueStmt](#continuestmt) + +[Visitor](#visitor) + +## Ptr + +AST中使用的指针类型。实际上是`std::shared_ptr` + +## PtrList + +存放[Ptr](#ptr)的list,实际上是`std::vector` + +## Position + +该节点代表的语法结构在源文件的位置信息,实际上是`yy::location`。由bison/flex自动生成。 + +## Type +包含SysY语言支持的数据类型:`Type::INT`以及`Type::VOID`。 + +多出的`Type::STRING`类型用作系统调用的参数类型,`Type::BOOL`作为条件表达式类型。 + +## Binop + +双目算术表达式的操作符。包含 + +`Binop::PLUS` 加 + +`Binop::MINUS`减 + +`Binop::MULTIPLY`乘 + +`Binop::DIVIDE`除 + +`Binop::MODULO`模 + +## UnaryOp + +单目算术表达式操作符,包含 + +`UnaryOp::PLUS`正 + +`UnaryOp::MINUS`负 + + +## UnaryCondOp + +单目条件表达式操作符,包含 + +`UnaryCondOp::NOT`非 + +## BinaryCondOp + +双目条件表达式操作符,包含 + +`BinaryCondOp::LT`小于 + +`BinaryCondOp::LTE`小于等于 + +`BinaryCondOp::GT`大于 + +`BinaryCondOp::GTE`大于等于 + +`BinaryCondOp::EQ`等于等于 + +`BinaryCondOp::NEQ`不等于 + +`BinaryCondOp::LAND`逻辑与 + +`BinaryCondOp::LOR`逻辑或 + +## Node + +语法树所有结点的基类, + +`Node::loc`是其在对应源文件的位置信息。类型为[Position](#position) + +`virtual void Node::accept(Visitor &visitor)`为虚函数,用于访问者模式,接受一个[Visitor](#visitor)。需要进行重写。 + +## Assembly + +AST的根结点 + +[PtrList](#ptrlist)<[GlobalDef](#globaldef)> `Assembly::global_defs`存放所有[GlobalDef](#globaldef)指针。 + +## InitVal + +代表初值的结点。该结点为嵌套定义。以下类型的变量初值均可表示: + +```c++ +int a = 1 + 1; +int b[2] = {1,2}; +int c[2][2] = {{1,2},{3,4}} +... +``` + +`bool InitVal::isExp` + +为真时初值为[Expr](#expr)类型。为假时代表以`{...}`的形式进行赋初值 +eg +```c++ +int a = 3 + 1;//isExp=true +int c[2][2] = {{1,2},{3,4}};//isExp=false +``` +所有`InitVal`结点最底层一定是[Expr](#expr)类型。也即`isExp`为true + +[PtrList](#ptrlist)<[InitVal](#initval)> `InitVal::elementList` + +当`isExp`为false时该域才有意义。是包含`{}`中其余`InitVal`结点指针的列表。 + +[Ptr](#ptr)<[Expr](#expr)> `InitVal::expr` + +当`isExp`为true时该域才有意义。一个初值表达式的指针。 + +## GlobalDef + +所有def结点的基类 + +## FuncDef + +代表函数定义。 + +[Type](#type) `FuncDef::ret_type`。 + +函数的返回值类型 + +[Ptr](#ptr)<[FuncFParamList](#funcfparamlist)> `FuncDef::param_list`。 + +函数的形参指针 + +`std::string FuncDef::name` + +函数名 + +[Ptr](#ptr)<[BlockStmt](#blockstmt)> `FuncDef::body` + +函数体指针 + +## VarDef + +代表变量定义 + +`bool VarDef::is_constant` + +是否为常量 + +[Type](#type) `VarDef::btype` + +变量类型(在sysY中只能是int) + +`std::string VarDef::name` + +变量名 + +`bool VarDef::is_inited` + +是否初始化 + +[PtrList](#ptrlist)<[Expr](#expr)> `VarDef::array_length` + +若为数组,则是存放各维长度表达式指针的列表,否则为空 + +[Ptr](#ptr)<[InitVal](#initval)> `VarDef::initializers` + +若初始化,则是指向初值定义的指针 + +## Stmt + +所有statement的基类 + +## AssignStmt + +表示如下类型的语句: +```c++ +target = value +``` + +即赋值型语句 + +[Ptr](#ptr)<[Lval](#lval)> `AssignStmt::target` + +赋值表达式的左值指针 + +[Ptr](#ptr)<[Expr](#expr)> `AssignStmt::value` + +赋值表达式右边表达式指针 + +## ReturnStmt + +代表return 语句 + +[Ptr](#ptr)<[Expr](#expr)> `ReturnStmt::ret` + +return 语句返回的表达式指针。空指针代表void return + +## BlockStmt + +代表使用`{}`括起来的stmt。 + +[PtrList](#ptrlist)<[Stmt](#stmt)> `BlockStmt::body` + +该block中所有stmt指针的列表 + +## EmptyStmt + +空语句 + +## ExprStmt + +表达式语句 + +[Ptr](#ptr)<[Expr](#exp)> `ExprStmt::exp` + +表达式语句对应表达式的指针 + +## Expr + +所有表达式的基类 + +## CondExpr + +所有条件表达式的基类 + +## AddExpr + +所有算术表达式的基类 + +## UnaryCondExpr + +单目条件表达式 + +`UnaryCondOp UnaryCondExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `UnaryCondExpr::rhs` + +操作符右端表达式指针 + +## BinaryCondExpr + +双目条件表达式 + +`BinaryCondOp BinaryCondExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `BinaryCondExpr::lhs, rhs` + +操作符左右两端表达式指针 + +## BinaryExpr + +双目算术表达式 + +`BinOp BinaryExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `BinaryExpr::lhs, rhs` + +操作符左右两端表达式指针 + +## UnaryExpr + +单目算术表达式 + +`UnaryOp UnaryExpr::op` + +操作符 + +[Ptr](#ptr)<[Expr](#expr)> `UnaryExpr::rhs` + +操作符右端表达式指针 + +## LVal + +左值表达式 + +`std::string Lval::name` + +变量名 + +[PtrList](#ptrlist)<[Expr](#expr)> `LVal::array_index` + +数组索引的指针列表。若不是数组,则为空 + +## Literal + +语义值类型,包含整数和字符串 + +`bool Literal::is_int` + +是否为整形 + +`int Literal::int_const` + +整数语义值 + +`std::string Literal::str` + +字符串语义值(未处理转义) + +## FuncCallStmt + +函数调用 + +`std::string FuncCallStmt::name` + +被调用的函数名 + +[PtrList](#ptrlist)<[Expr](#expr)> `FuncCallStmt::params` + +存放函数实参表达式指针的列表 + +## FuncParam + +单个函数形参 + +`std::string FuncParam::name` + +形参名 + +[Type](#type) `FuncParam::param_type` + +形参类型 + +[PtrList](#ptrlist)<[Expr](#expr)> `FuncParam::array_index` + +形参的数组维度列表,存放每一维的表达式指针。若非数组则为空 + +## FuncFParamList + +存放一个函数的所有形参 + +[PtrList](#ptrlist)<[FuncParam](#funcparam)> `FuncFParamList::params` + +存放所有形参指针的列表 + +## IfStmt + +表示如下结构: +```c++ +if(cond_exp) + if_stmt +或 +if(cond_exp) + if_stmt +else + else_stmt +``` + +[Ptr](#ptr)<[Expr](#expr)> `IfStmt::cond_exp` + +cond_exp的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `IfStmt::if_statement` + +if_stmt的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `IfStmt::else_statement` + +else_stmt的指针(若无else,则为空) + + +## WhileStmt + +表示如下结构 +```c++ +while(cond_exp) + stmt +``` + +[Ptr](#ptr)<[Expr](#expr)> `WhileStmt::cond_exp` + +cond_exp的指针 + +[Ptr](#ptr)<[Stmt](#stmt)> `WhileStmt::statement` + +stmt的指针 + + +## BreakStmt + +表示一个break语句 + +## ContinueStmt + +表示一个continue语句 + +## Visitor + +访问者模式的基类,用于访问AST。需要重写其中的visit函数。 \ No newline at end of file diff --git a/doc/SysYFIR.md b/doc/SysYFIR.md new file mode 100644 index 0000000..8a9cc30 --- /dev/null +++ b/doc/SysYFIR.md @@ -0,0 +1,620 @@ +# SysYF IR + +- [SysYF IR](#sysyf-ir) + - [IR](#ir) + - [IR Features](#ir-features) + - [IR Format](#ir-format) + - [Instruction](#instruction) + - [Terminator Instructions](#terminator-instructions) + - [Ret](#ret) + - [Br](#br) + - [Standard binary operators](#standard-binary-operators) + - [Add FAdd](#add-fadd) + - [Sub FSub](#sub-fsub) + - [Mul FMul](#mul-fmul) + - [SDiv FDiv](#sdiv-fdiv) + - [SRem](#srem) + - [Memory operators](#memory-operators) + - [Alloca](#alloca) + - [Load](#load) + - [Store](#store) + - [CastInst](#castinst) + - [ZExt](#zext) + - [FpToSi](#fptosi) + - [SiToFp](#sitofp) + - [Other operators](#other-operators) + - [ICmp FCmp](#icmp-fcmp) + - [Call](#call) + - [GetElementPtr](#getelementptr) + - [C++ APIs](#c-apis) + - [核心类概念图](#核心类概念图) + - [BasicBlock](#basicblock) + - [Constant](#constant) + - [Function](#function) + - [GlobalVariable](#globalvariable) + - [IRStmtBuilder](#irstmtbuilder) + - [Instruction](#instruction-1) + - [Module](#module) + - [Type](#type) + - [User](#user) + - [Value](#value) + - [总结](#总结) + +## IR + +### IR Features +- 采用类型化三地址代码的方式 + - 区别于 X86 汇编的目标和源寄存器共用的模式: ADD EAX, EBX + - %2 = add i32 %0, %1 +- 静态单赋值 (SSA) 形式 + 无限寄存器 + - 每个变量都只被赋值一次 + - 容易确定操作间的依赖关系,便于优化分析 +- 强类型系统 + - 每个 Value 都具备自身的类型, + - IR类型系统: + - `i1`:1位宽的整数类型 + - `i32`:32位宽的整数类型 + - `float`:单精度浮点数类型 + - `pointer`:指针类型 + - 例如:`i32*, [10 x i32*]` + - `label` bb的标识符类型 + - `functiontype`函数类型,包括函数返回值类型与参数类型(下述文档未提及) + +### IR Format +下面以`easy.c`与`easy.ll`为例进行说明。 +通过命令`clang -S -emit-llvm easy.c`可以得到对应的`easy.ll`如下(其中增加了额外的注释)。`.ll`文件中注释以`;`开头。 + +- `easy.c`: + ``` c + int main(){ + int a; + int b; + a = 1; + b = 2; + if(a < b) + b = 3; + return a + b; + } + ``` +- `easy.ll`: + ``` c + ; 注释: .ll文件中注释以';'开头 + ; ModuleID = 'easy.c' + source_filename = "easy.c" + ; 注释: target的开始 + target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" + target triple = "x86_64-unknown-linux-gnu" + ; 注释: target的结束 + + ; 注释: 全局main函数的定义 + ; Function Attrs: noinline nounwind optnone uwtable + define dso_local i32 @main() #0 { + ; 注释: 第一个基本块的开始 + %1 = alloca i32, align 4 + %2 = alloca i32, align 4 + %3 = alloca i32, align 4 + store i32 0, i32* %1, align 4 + store i32 1, i32* %2, align 4 + store i32 2, i32* %3, align 4 + %4 = load i32, i32* %2, align 4 + %5 = load i32, i32* %3, align 4 + %6 = icmp slt i32 %4, %5 + br i1 %6, label %7, label %8 + ; 注释: 第一个基本块的结束 + + ; 注释: 第二个基本块的开始 + 7: ; preds = %0 + store i32 3, i32* %3, align 4 + br label %8 + ; 注释: 第二个基本块的结束 + + ; 注释: 第三个基本块的开始 + 8: ; preds = %7, %0 + %9 = load i32, i32* %2, align 4 + %10 = load i32, i32* %3, align 4 + %11 = add nsw i32 %9, %10 + ret i32 %11 ; 注释: 返回语句 + ; 注释: 第三个基本块的结束 + } + + attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } + + !llvm.module.flags = !{!0} + !llvm.ident = !{!1} + + !0 = !{i32 1, !"wchar_size", i32 4} + !1 = !{!"clang version 10.0.1 "} + ``` +每个program由1个或多个module组成,每个module对应1个程序文件,module之间由LLVM Linker进行链接形成1个可执行文件或者库。 +每个module组成如下: +- Target Information: + ``` c + target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" + target triple = "x86_64-unknown-linux-gnu" + ``` +- Global Symbols: main函数的定义 +- Others:尾部其他信息 + +每个函数的组成如下: +- 头部:函数返回值类型、函数名、函数参数 +- 一个或多个基本块: + - 每个基本块由Label和Instruction组成。 + ``` c + 8: ; preds = %7, %0 + %9 = load i32, i32* %2, align 4 + %10 = load i32, i32* %3, align 4 + %11 = add nsw i32 %9, %10 + ret i32 %11 + ``` + 这个例子中,`8`就是Label。 + `%9 = load i32, i32* %2, align 4`中的`%9`是目的操作数,`load`是指令助记符,`i32`是`int32`的类型,`i32*`是指向`int32`的地址类型,`%2`是源操作数,`align 4`表示对齐。 +### Instruction +#### Terminator Instructions +**注**:ret与br都是Terminator Instructions也就是终止指令,在llvm基本块的定义里,基本块是单进单出的,因此只能有一条终止指令(ret或br)。当一个基本块有两条终止指令,clang 在做解析时会认为第一个终结指令是此基本块的结束,并会开启一个新的匿名的基本块(并占用了下一个编号)。 +##### Ret +- 格式 + - `ret ` + - `ret void` +- 例子: + - `ret i32 %0` + - `ret void` +- 概念:` ret`指令用于将控制流(以及可选的值)从函数返回给调用者。`ret`指令有两种形式:一种返回值,然后终结函数,另一种仅终结函数。 + +##### Br +- 格式: + - `br i1 , label , label ` + - `br label ` +- 例子: + - `br i1 %cond label %truebb label %falsebb` + - `br label %bb` +- 概念:`br`指令用于使控制流转移到当前功能中的另一个基本块。 该指令有两种形式,分别对应于条件分支和无条件分支。 + +#### Standard binary operators +##### Add FAdd +- 格式: + - ` = add , ` + - ` = fadd , ` +- 例子: + - `%2 = add i32 %1, %0` + - `%2 = fadd float %1, %0` +- 概念:`add`指令返回其两个`i32`类型的操作数之和,返回值为`i32`类型,`fadd`指令返回其两个`float`类型的操作数之和,返回值为`float`类型 + +##### Sub FSub +- 格式与例子与`add`,`fadd`类似 +- 概念:`sub`指令返回其两个`i32`类型的操作数之差,返回值为`i32`类型,`fsub`指令返回其两个`float`类型的操作数之差,返回值为`float`类型 + +##### Mul FMul +- 格式与例子与`add`,`fadd`类似 +- 概念:`mul`指令返回其两个`i32`类型的操作数之积,返回值为`i32`类型,`fmul`指令返回其两个`float`类型的操作数之积,返回值为`float`类型 + +##### SDiv FDiv +- 格式与例子与`add`,`fadd`类似 +- 概念:`sdiv`指令返回其两个`i32`类型的操作数之商,返回值为`i32`类型,`fdiv`指令返回其两个`float`类型的操作数之商,返回值为`float`类型 + +##### SRem +- 格式与例子与`add`类似 +- 概念:`srem`指令返回其两个`i32`类型的操作数之模,返回值为`i32`类型 + +#### Memory operators +##### Alloca +- 格式:` = alloca ` +- 例子: + - `%ptr = alloca i32` + - `%ptr = alloca [10 x i32]` +- 概念: `alloca`指令在当前执行函数的栈帧上分配内存,当该函数返回其调用者时将自动释放该内存。 始终在地址空间中为数据布局中指示的分配资源分配对象 + +##### Load +- 格式:` = load , * ` +- 例子:`%val = load i32, i32* %ptr` +- 概念:`load`指令用于从内存中读取。 + +##### Store +- 格式:`store , * ` +- 例子:`store i32 3, i32* %ptr` +- 概念:`store`指令用于写入内存 + +#### CastInst +##### ZExt +- 格式:` = zext to ` +- 例子:`%1 = zext i1 %0 to i32` +- 概念:`zext`指令将其操作数**零**扩展为`type2`类型。 + +##### FpToSi +- 概念:`fptosi`指令将浮点值转换为`type2`(整数)类型。 +- 格式:` = fptosi to ` +- 例子:`%Y = fptosi float 1.0E-247 to i32` + +##### SiToFp +- 格式:` = sitofp to ` +- 例子:`%X = sitofp i32 257 to float` +- 概念:`sitofp`指令将有符号整数转换为`type2`(浮点数)类型。 + +#### Other operators +##### ICmp FCmp +- 格式: + - ` = icmp , ` + - ` = eq | ne | sgt | sge | slt | sle` + - ` = fcmp , ` + - ` = eq | ne | ugt | uge | ult | ule` +- 例子:`i1 %2 = icmp sge i32 %0, %1` +- 概念:`icmp`指令根据两个整数的比较返回布尔值,`fcmp`指令根据两个浮点数的比较返回布尔值。 + +##### Call +- 格式: + - ` = call () ` +- 例子: + - `%0 = call i32 @func( i32 %1, i32* %0)` + - `call @func( i32 %arg)` +- 概念:`call`指令用于使控制流转移到指定的函数,其传入参数绑定到指定的值。 在被调用函数中执行`ret`指令后,控制流程将在函数调用后继续执行该指令,并且该函数的返回值绑定到`result`参数。 + +##### GetElementPtr +- 格式:` = getelementptr , * [, ]` +- 例子: + - `%2 = getelementptr [10 x i32], [10 x i32]* %1, i32 0, i32 %0` + - `%2 = getelementptr i32, i32* %1 i32 %0` +- 参数解释:第一个参数是计算基础类型,第二第三个参数表示索引开始的指针类型及指针,`[]`表示可重复参数,里面表示的数组索引的偏移类型及偏移值。(思考指针类型为`[10 x i32]`指针和`i32`指针`getelementptr`用法的不同) +- 概念:`getelementptr`指令用于获取数组结构的元素的地址。 它仅执行地址计算,并且不访问内存。 + +## C++ APIs + +### 核心类概念图 + +![](figs/核心类概念图.png) + +### BasicBlock +- 继承:从[value](#value)继承 + +- 含义:基本块,是一个是单入单出的代码块,该类维护了一个指令链表,基本块本身属于 Value, 类型是 \,会被分支指令调用 + +- 成员: + + - instr_list_:指令链表 + - pre_bbs_: bb前驱集合 + - succ_bbs_:bb后继集合 + +- API: + + ```c++ + // 创建并返回BB块,参数分别是BB块所属的Module,name是其名字默认为空,BB块所属的Function + static Ptr create(Ptr m, const std::string &name ,Ptr parent ) + // 返回BB块所属的函数 + Ptr get_parent(); + // 返回BB块所属的Module + Ptr get_module(); + // 返回BB块的终止指令(ret|br),若BB块最后一条指令不是终止指令返回null + Ptr get_terminator(); + // 将instr指令添加到此BB块指令链表结尾,调用IRBuilder里来创建函数会自动调用此方法 + void add_instruction(Ptr instr); + // 将instr指令添加到此BB块指令链表开头 + void add_instr_begin(Ptr instr); + // 将instr指令从BB块指令链表中移除,同时调用api维护好instr的操作数的use链表 + void delete_instr(Ptr instr); + // BB块中指令数为空返回true + bool empty(); + // 返回BB块中指令的数目 + int get_num_of_instr(); + //返回BB块的指令链表 + PtrList &get_instructions(); + // 将此BB块从所属函数的bb链表中移除 + void erase_from_parent(); + + /****************api about cfg****************/ + PtrList &get_pre_basic_blocks() // 返回前驱块集合 + PtrList &get_succ_basic_blocks() // 返回后继块集合 + void add_pre_basic_block(Ptr bb) // 添加前驱块 + void add_succ_basic_block(Ptr bb) // 添加后继块 + void remove_pre_basic_block(Ptr bb) // 移除前驱块 + void remove_succ_basic_block(Ptr bb) // 移除后继块 + /****************api about cfg****************/ + + ``` + + +### Constant +- 继承:从[User](#user)继承 +- 含义:常数,各种类型常量的基类 +- 子类: + - ConstantInt + - 含义:int类型的常数 + + - 成员 + + - value_:常数值 + + - API + + ```cpp + int get_value() // 返回该常数类型中存的常数值 + static int get_value(Ptr const_val)// 返回该常数类型const_val中存的常数值 + static Ptr get(int val, Ptr m) // 以val值来创建常数类 + static Ptr get(bool val, Ptr m) // 以val值来创建bool常数类 + ``` + + - ConstantFloat + - 含义:float类型的常数 + + - 成员 + + - value_:常数值 + + - API + + ```cpp + static Ptr get(float val, Ptr m) // 以val值创建并返回浮点数常量类 + float get_value() // 返回该常数类型中存的常数值 + ``` + + - ConstantZero + + - 含义:用于全局变量初始化的常量0值。 + + - API + + ```cpp + static Ptr get(Ptr ty, Ptr m);// 创建并返回ConstantZero常量类 + ``` + + - ConstantArray + + - 含义:数组类型的常数 + - 成员 + - const_array:数组常量值 + + - API:cminus语法不需要数组常量的支持(本次实验不需要用到),在此不过多解释。感兴趣可以自行查看源代码。 +### Function +- 继承:从[Value](#value)继承 + +- 含义:函数,该类描述 LLVM 的一个简单过程,维护基本块表,格式化参数表 + +- 成员 + - basic_blocks_:基本块列表 + - arguments_:形参列表 + - parent_:函数属于的module + +- API + + ```cpp + static Ptr create(Ptr ty, const std::string &name, Ptr parent); + // 创建并返回Function,参数依次是待创建函数类型ty、函数名字name(不可为空)、函数所属的Module + Ptr get_function_type() const; + // 返回此函数类的函数类型 + Ptr get_return_type() const; + // 返回此函数类型的返回值类型 + void add_basic_block(Ptr bb); + // 将bb添加至Function的bb链表上(调用bb里的创建函数时会自动调用此函数挂在function的bb链表上) + unsigned get_num_of_args() const; + // 得到函数形参数数量 + unsigned get_num_basic_blocks() const; + // 得到函数基本块数量 + Ptr get_parent() const; + // 得到函数所属的Module + PtrList::iterator arg_begin() + // 得到函数形参的list的起始迭代器 + PtrList::iterator arg_end() + // 得到函数形参的list的终止迭代器 + void remove(Ptr bb) + // 从函数的bb链表中删除一个bb + PtrList &get_basic_blocks() + // 返回函数bb链表 + PtrList &get_args() + // 返回函数的形参链表 + void set_instr_name(); + // 给函数中未命名的基本块和指令命名 + ``` + + + +- 相关类 + - Argument + - 含义:参数 + + - 成员 + - arg_no_:参数序号 + - parent_:参数属于哪个函数 + + - API + + ```cpp + Ptr get_parent() // 返回参数的所属函数 + unsigned get_arg_no() const // 返回参数在所在函数的第几个参数 + ``` +### GlobalVariable +- 继承:从[User](#user)继承 +- 含义:全局变量,该类用于表示全局变量,是 GlobalValue 的子类,根据地址来访问 +- 成员: + - is_const:是否为常量 + - init_val_:初始值 +- API:由于cminusf语义要求所有的全局变量都默认初始化为0,故`GlobalVariable`中成员和API再构造CminusFBuilder用不到 +### IRStmtBuilder +- 含义:生成IR的辅助类,该类提供了独立的接口创建各种 IR 指令,并将它们插入基本块中, 该辅助类不做任何类型检查。 + +- API + + ```cpp + Ptr get_insert_block()// 返回正在插入指令的BB + void set_insert_point(Ptr bb)// 设置当前需要插入指令的bb + ptr create_[instr_type]()// 创建instr_type(具体名字参考IRStmtBuilder.h代码)的指令并对应插入到正在插入的BB块,这种类型的指令看函数名字和参数名字和IR文档是一一对应的。 + ``` + + +### Instruction +- 继承:从[User](#user)继承 +- 含义:指令,该类是所有 LLVM 指令的基类,主要维护指令的操作码(指令类别),指令所属的基本块,指令的操作数个数信息 +- 成员 + - parent_:指令所属的BasicBlock + - op_id_:指令的类型id + - num_ops_指令的操作数个数 +- 子类 + - BinaryInst:双目运算指令包括add、sub、mul、div + - 其他子类和前述文档中提到的指令一一对应,不在此赘述。 +- API:所有指令的创建都要通过 IRStmtBuilder 进行,不需要关注Instruction类的实现细节,(**注**:不通过 IRStmtBuilder 来创建指令,而直接调用指令子类的创建方法未经助教完善的测试) +### Module +- 含义:一个编译单元,在此源语言的意义下是一个文件 + +- 成员 + - function_list_:函数链表,记录了这个编译单元的所有函数 + - global_list_:全局变量链表 + - instr_id2string_:通过指令类型id得到其打印的string + - module_name_, source_file_name:未使用 + - 从module中能取到的基本类型 + +- API + + ```cpp + Ptr get_void_type(); + // 得到IR中的void类型其他类型可以用类似的API得到(推荐取得类型采用lab3助教提供的方法Type::get()) + void add_function(Ptr f); + // 将f挂在module的function链表上,在function被创建的时候会自动调用此方法来添加function + void add_global_variable(Ptr g); + // 将g挂在module的GlobalVariable链表上,在GlobalVariable被创建的时候会自动调用此方法来添加GlobalVariable + PtrList &get_global_variable(); + // 获取全局变量列表 + std::string get_instr_op_name( Instruction::OpID instr ); + // 获取instr对应的指令名(打印ir时调用) + void set_print_name(); + // 设置打印ir的指令与bb名字; + ``` + + +### Type +- 含义:IR的类型,该类是所有类型的超类 + +- 成员 + + - tid_:枚举类型,表示type的类型(包含VoidType、LabelType、FloatType、Int1、Int32、ArrayType、PointerType) + +- 子类 + - IntegerType + - 含义:int 类型 + + - 成员 + + - num_bits:长度(i1或者i32) + + - API + + ```cpp + unsigned get_num_bits();// 返回int的位数 + ``` + - FloatType + + - 含义:float 类型 + - FunctionType + - 含义:函数类型 + + - 成员 + - result_:返回值类型 + - args_:参数类型列表 + + - API + + ```cpp + static Ptr get(Ptr result, PtrVec params); + // 返回函数类型,参数依次是返回值类型result,形参类型列表params + unsigned get_num_of_args() const; + // 返回形参个数 + Ptr get_param_type(unsigned i) const; + // 返回第i个形参的类型 + PtrVec::iterator param_begin() + // 返回形参类型列表的起始迭代器 + PtrVec::iterator param_end() + // 返回形参类型列表的终止迭代器 + Ptr get_return_type() const; + // 返回函数类型中的返回值类型 + ``` + - ArrayType + - 含义:数组类型 + + - 成员 + - contained_:数组成员的类型 + - num_elements_:数组维数 + + - API + + ```cpp + static Ptr get(Ptr contained, unsigned num_elements); + // 返回数组类型,参数依次是 数组元素的类型contained,数组元素个数num_elements + Ptr get_element_type() const + // 返回数组元素类型 + unsigned get_num_of_elements() const + // 返回数组元素个数 + ``` + - PointerType + - 含义:指针类型 + + - 成员 + + - contained_:指针指向的类型 + + - API + + ```cpp + Ptr get_element_type() const { return contained_; } + // 返回指针指向的类型 + static Ptr get(Ptr contained); + // 返回contained类型的指针类型 + Ptr get_pointer_element_type();// 若是PointerType则返回指向的类型,若不是则返回nullptr。 + static Ptr create(Ptr contained); + // 创建指向contained类型的指针类型 + ``` + +- API + + ```cpp + bool is_void_type()// 判断是否是void类型其他类型有类似API请查看Type.h + static Ptr get_void_type(Ptr m);// 得到void类型 + Ptr get_pointer_element_type();// 若是PointerType则返回指向的类型,若不是则返回nullptr。 + Ptr get_array_element_type();// 若是ArrayType则返回指向的类型,若不是则返回nullptr。 + ``` + + +### User +- 继承:从[value](#value)继承 + +- 含义:使用者,提供一个操作数表,表中每个操作数都直接指向一个 Value, 提供了 use-def 信息,它本身是 Value 的子类, Value 类会维护一个该数据使用者的列表,提供def-use信息。简单来说操作数表表示我用了谁,该数据使用者列表表示谁用了我。这两个表在后续的**优化实验**会比较重要请务必理解。 + +- 成员 + - operands_:参数列表,表示这个使用者所用到的参数 + - num_ops_:表示该使用者使用的参数的个数 + +- API + + ```cpp + Ptr get_operand(unsigned i) const; + // 从user的操作数链表中取出第i个操作数 + void set_operand(unsigned i, Ptr v); + // 将user的第i个操作数设为v + void add_operand(Ptr v); + // 将v挂到User的操作数链表上 + unsigned get_num_operand() const; + // 得到操作数链表的大小 + void remove_use_of_ops(); + // 从User的操作数链表中的所有操作数处的use_list_ 移除该User; + void remove_operands(int index1, int index2); + // 移除操作数链表中索引为index1-index2的操作数,例如想删除第0个操作数:remove_operands(0,0) + ``` + +### Value +- 含义:最基础的类,代表一个操作数,代表一个可能用于指令操作数的带类型数据 + +- 成员 + - use_list_:记录了所有使用该操作数的指令的列表 + - name_:名字 + - type_:类型,一个type类,表示操作数的类型 + +- API + + ```cpp + Ptr get_type() const //返回这个操作数的类型 + std::list &get_use_list() // 返回value的使用者链表 + void add_use(Ptr val, unsigned arg_no = 0); + // 添加val至this的使用者链表上 + void replace_all_use_with(Ptr new_val); + // 将this在所有的地方用new_val替代,并且维护好use_def与def_use链表 + void remove_use(Ptr val); + // 将val从this的use_list_中移除 + ``` + +### 总结 + +在本文档里提供了为SysYF语言程序生成LLVM IR可能需要用到的SysYF IR应用编程接口,如果对这些API有问题的请移步issue讨论,本次`SysYF IR`应用编程接口由助教自行设计实现,并做了大量测试,如有对助教的实现方法有异议或者建议的也请移步issue讨论,**除了选做内容无需修改助教代码**。 diff --git a/doc/SysYF语言定义.pdf b/doc/SysYF语言定义.pdf new file mode 100755 index 0000000..3b50c12 Binary files /dev/null and b/doc/SysYF语言定义.pdf differ diff --git a/doc/figs/核心类概念图.png b/doc/figs/核心类概念图.png new file mode 100755 index 0000000..be5dec7 Binary files /dev/null and b/doc/figs/核心类概念图.png differ diff --git a/doc/phase1.md b/doc/phase1.md new file mode 100644 index 0000000..1a66121 --- /dev/null +++ b/doc/phase1.md @@ -0,0 +1,79 @@ +[TOC] + +--- + +### 任务描述 +**本关任务**:熟悉LLVM IR,并根据给出的4个SysYF程序(文件扩展名为sy)手写相应的LLVM IR的ll文件,以实现相同功能。 + +### 相关知识 +#### LLVM IR介绍 +[LLVM](https://llvm.org/)是一个开源的编译器基础设施,用C++语言编写,包含一系列模块化的编译器组件和工具链,用来支持编译器前端和后端的开发。IR的全称是Intermediate Representation,即中间表示。LLVM IR是一种类型化的三地址中间表示,是类似于汇编的底层语言。 +LLVM IR的具体指令可以参考[Reference Manual](http://llvm.org/docs/LangRef.html)。但是你会发现其内容庞杂,为便于你尽快了解本实训项目需要涉及的LLVM IR指令子集,请查看本实训提供的**精简的IR Reference手册**`doc/SysYFIR.md`。 +作为一开始的参考,你可以先阅读其中的`IR Features`和`IR Format`两节,后续有需要再反复参考。 + +#### 样例学习 +
+ go_upstairs.c(点击展开) + +```c +int num[2] = {4, 8}; +int x[1]; +int n; +int tmp = 1; + +int climbStairs(int n) { + if(n < 4) + return n; + int dp[10]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + int i; + i = 3; + while(i + + +- 阅读`Student/task1/demo/go_upstairs.c`。 +- 进入`Student/task1/demo`文件夹,输入命令 + + ```clang -S -emit-llvm go_upstairs.c``` +你可以得到对应的`go_upstairs.ll`。 +你需要结合`go_upstairs.c`阅读`go_upstairs.ll`,理解其中每条LLVM IR指令与C代码的对应情况。 +- 通过执行命令 + ```lli go_upstairs.ll; echo $?``` +你可以测试`go_upstairs.ll`执行结果的正确性。 + +### 本关具体任务 +1. 在`Student/task1/student_sy/`内提供了四个简单的SysYF 程序:`assign_test.sy`,`func_test.sy`,`if_test.sy`,`while_test.sy`。 +你需要在`Student/task1/ll/`目录下手工编写`assign_hand.ll`,`func_hand.ll`,`if_hand.ll`,`while_hand.ll`文件,以实现与上述 SysYF 程序相同的逻辑功能。 +你需要在`ll`文件内添加必要的注释,`ll`文件的注释是以`;`开头的。 +必要的情况下,你可以参考`clang -S -emit-llvm`的输出,但是你提交的结果必须避免同此输出一字不差。 +2. 在`report.md`内回答[思考题](#思考题) + +### 运行说明 +- 你需要使用 `clang --version` 和 `lli --version` 检查本机的Clang和LLVM版本 +- 你可以使用 `which lli` 来查找 `lli` 命令的位置 +- 利用LLVM的命令 `lli`,可以执行`*.ll`文件;如果版本过低,可能会遇到`error: expected top-level entity`等问题 +- 你也可以使用 `clang go_upstairs.ll -o go_upstairs` 来生成可执行文件 +- `$?`的内容是上一条命令所返回的结果,而`echo $?`可以将其输出到终端中 +- 使用`clang`时,注意扩展名为`sy`的文件是SysYF语言的程序文件,`clang`是无法直接识别的,你可以将`sy`文件复制为`c`文件来用`clang`编译 + +### 思考题 +请在`report/report.md`中详细回答下述思考题: +1-1 请给出while语句对应的LLVM IR的代码布局特点,重点解释其中涉及的几个`br`指令的含义(包含各个参数的含义) +1-2 请简述函数调用语句对应的LLVM IR的代码特点 diff --git a/doc/phase2.md b/doc/phase2.md new file mode 100644 index 0000000..1998775 --- /dev/null +++ b/doc/phase2.md @@ -0,0 +1,128 @@ +[TOC] + +--- + +### 任务描述 +**本关任务**:熟悉SysYF IR的应用编程接口,并根据给出的4个SysYF程序手写调用SysYF IR应用编程接口的C++代码,生成与sy文件功能相同的ll文件。 + +### 相关知识 +#### SysYF IR 应用编程接口 +由于LLVM IR官方的C++应用编程接口的文档内容繁多,本实训项目提供SysYF IR应用编程接口库,该库用C++编写,可以用于生成LLVM IR的子集。你需要阅读**SysYF IR核心类的介绍**`doc/SysYFIR.md`。 +本关要求你根据AST,使用SysYF IR应用编程接口来构建生成LLVM IR。你需要先仔细阅读文档`doc/SysYFIR.md`以了解其接口的设计。 + +#### 样例学习 +
+ go_upstairs_gen.cpp核心部分(点击展开) + +```cpp + // 全局数组,num,x + auto arrayType_num = ArrayType::get(Int32Type, 2); + auto arrayType_x = ArrayType::get(Int32Type, 1); + auto zero_initializer = ConstantZero::create(Int32Type, module); + std::vector> init_val; + init_val.push_back(CONST_INT(4)); + init_val.push_back(CONST_INT(8)); + auto num_initializer = ConstantArray::create(arrayType_num, init_val); + auto num = GlobalVariable::create("num", module, arrayType_num, false, num_initializer);// 是否是常量定义,初始化常量(ConstantZero类) + auto x = GlobalVariable::create("x", module, arrayType_x, false, zero_initializer);// 参数解释: 名字name,所属module,全局变量类型type, + + auto n = GlobalVariable::create("n", module, Int32Type, false, zero_initializer); + auto tmp = GlobalVariable::create("tmp", module, Int32Type, false, CONST_INT(1)); + + // climbStairs函数 + // 函数参数类型的vector + std::vector> Ints(1, Int32Type); + + //通过返回值类型与参数类型列表得到函数类型 + auto climbStairsFunTy = FunctionType::create(Int32Type, Ints); + + // 由函数类型得到函数 + auto climbStairsFun = Function::create(climbStairsFunTy, + "climbStairs", module); + + // BB的名字在生成中无所谓,但是可以方便阅读 + auto bb = BasicBlock::create(module, "entry", climbStairsFun); + + builder->set_insert_point(bb); // 一个BB的开始,将当前插入指令点的位置设在bb + + auto retAlloca = builder->create_alloca(Int32Type); // 在内存中分配返回值的位置 + auto nAlloca = builder->create_alloca(Int32Type); // 在内存中分配参数n的位置 + + std::vector> args; // 获取climbStairs函数的形参,通过Function中的iterator + for (auto arg = climbStairsFun->arg_begin(); arg != climbStairsFun->arg_end(); arg++) { + args.push_back(*arg); // * 号运算符是从迭代器中取出迭代器当前指向的元素 + } + + builder->create_store(args[0], nAlloca); // store参数n + + auto retBB = BasicBlock::create( + module, "", climbStairsFun); // return分支,提前create,以便true分支可以br + + auto nLoad = builder->create_load(nAlloca); // 将参数n load上来 + auto icmp = builder->create_icmp_lt(nLoad, CONST_INT(4)); // n和4的比较,注意ICMPLT + + auto trueBB = BasicBlock::create(module, "trueBB_if", climbStairsFun); // true分支 + auto falseBB = BasicBlock::create(module, "falseBB_if", climbStairsFun); // false分支 + + builder->create_cond_br(icmp, trueBB, falseBB); // 条件BR + DEBUG_OUTPUT // 我调试的时候故意留下来的,以醒目地提醒你这个调试用的宏定义方法 + builder->set_insert_point(trueBB); // if true; 分支的开始需要SetInsertPoint设置 + nLoad = builder->create_load(nAlloca); + builder->create_store(nLoad, retAlloca); + builder->create_br(retBB); // br retBB + + builder->set_insert_point(falseBB); // if false + auto arrayType_dp = ArrayType::get(Int32Type, 10); + auto dpAlloca = builder->create_alloca(arrayType_dp); + + auto dp0Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(0)}); + builder->create_store(CONST_INT(0), dp0Gep); + + auto dp1Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(1)}); + builder->create_store(CONST_INT(1), dp1Gep); + + auto dp2Gep = builder->create_gep(dpAlloca, {CONST_INT(0), CONST_INT(2)}); + builder->create_store(CONST_INT(2), dp2Gep); + + auto iAlloca = builder->create_alloca(Int32Type); + builder->create_store(CONST_INT(3), iAlloca); + + auto condBB = BasicBlock::create(module, "condBB_while", climbStairsFun); // 条件BB + trueBB = BasicBlock::create(module, "trueBB_while", climbStairsFun); // true分支 + falseBB = BasicBlock::create(module, "falseBB_while", climbStairsFun); // false分支 + + builder->create_br(condBB); + + builder->set_insert_point(condBB); + //后略, 详细见代码文件 +``` +
+ +为了更直观地感受并学会使用 SysYF IR应用编程接口,本实训项目提供了示例代码,位于`Student/task2/demo/go_upstairs_gen.cpp`。 +该C++程序会生成与go_upstairs.c逻辑相同的LLVM IR文件,在该C++程序中提供了详尽的注释,请阅读理解,以便更好地开展你的实验! + +### 本关具体任务 +1. 你需要在`Student/task2/cpp/`文件夹中,调用SysYF IR应用编程接口,编写自己的 `assign_gen.cpp`,`func_gen.cpp`,`if_gen.cpp`,`while_gen.cpp`程序,以生成与第1关的四个sy 程序相同逻辑功能的ll文件。 +2. 在`report.md`内回答[思考题](#思考题) + +### 编译、运行和验证 +在 `Student/task2/build/` 下执行: +``` shell +# 如果存在 CMakeCache.txt 要先删除 +# rm CMakeCache.txt +cmake .. +make +``` +你可以得到对应 `assign_gen.cpp`,`func_gen.cpp`,`if_gen.cpp`,`while_gen.cpp`,`go_upstairs_gen.cpp`的可执行文件`assign_generator`,`func_generator`,`if_generator`,`while_generator`,`go_upstairs_generator`。 +之后直接执行可执行文件,即可得到对应的ll文件: +``` shell +# 在build文件夹内 +./go_upstairs_generator +``` + +### 思考题 +请在`report/report.md`中详细回答下述思考题: + +2-1. 请给出`SysYFIR.md`中提到的两种getelementptr用法的区别, 并解释原因: + - `%2 = getelementptr [10 x i32], [10 x i32]* %1, i32 0, i32 %0` + - `%2 = getelementptr i32, i32* %1, i32 %0` \ No newline at end of file diff --git a/doc/phase3.md b/doc/phase3.md new file mode 100644 index 0000000..376599b --- /dev/null +++ b/doc/phase3.md @@ -0,0 +1,132 @@ +[TOC] + +--- + +### 任务描述 +**本关任务**:编写`IRBuilder.cpp`文件,实现低级中间代码生成器,为SysYF语言程序生成兼容的LLVM IR代码。 + +### 相关知识 +#### 实验框架 +本实训项目提供用C++语言编写的SysYF IR 应用编程库,用于构建 LLVM IR的子集。为了简化你的实验,本实训的实验框架代码已完成了SysYF源程序到 C++ 上的抽象语法树的转换。 + +##### Scope +在`IRBuilder.h`中,还定义了一个用于存储作用域的类`Scope`。它的作用是在遍历语法树时,辅助管理不同作用域中的变量。它提供了以下接口: +```cpp +// 进入一个新的作用域 +void enter(); +// 退出一个作用域 +void exit(); +// 往当前作用域插入新的名字->值映射 +bool push(std::string name, Ptr val); +// 根据名字,以及是否为函数的bool值寻找到对应值 +// isfunc 为 true 时为寻找函数,否则为寻找其他变量对应的值 +Ptr find(std::string name, bool isfunc); +// 判断当前是否在全局作用域内 +bool in_global(); +``` +你需要根据语义合理调用`enter`与`exit`,并且在变量声明和使用时正确调用`push`与`find`。在类`SysYFIRBuilder`中,有一个`Scope`类型的成员变量`scope`,它在初始化时已经将特殊函数加入了作用域中。因此,你在进行名字查找时不需要顾虑是否需要对特殊函数进行特殊操作。 + +##### shared_ptr +为了防止内存泄漏,助教将框架中的裸指针换成了智能指针,相关的类型定义在`include/internal_types`中,其中以下的类型转换方法: +```cpp +using std::static_pointer_cast; +using std::dynamic_pointer_cast; +using std::const_pointer_cast; +``` +static_pointer_cast和dynamic_pointer_cast用于智能指针的类型转换,隐式完成了拆包、类型转换、重新包装和内存控制块维护,const_pointer_cast在转换时去除const属性,含义和使用方法类似于static_cast、dynamic_cast和const_cast: +```cpp +std::vector> ducks; +ducks.push_back(std::static_pointer_cast(std::make_shared())); +``` + +##### shared_from_this +这是助教在更新代码框架时涉及的部分,在实验中并不会用到,有兴趣的同学了解即可。由于改成了智能指针,我们在使用create方法创建IR中的Value对象时,需要在初始化的时候生成它的智能指针并返回,我们使用了`include/internal_macros.h`中的宏来定义使用了智能指针后新的初始化过程,先创建该对象的智能指针,然后对该智能指针调用init方法,而在init的过程中可能会用到它自身的智能指针,比如`src/SysYFIR\BasicBlock.cpp`中的`parent_->add_basic_block(dynamic_pointer_cast(shared_from_this()));`,这时需要用shared_from_this,原因参考[cpp smart pointer](https://www.cyhone.com/articles/right-way-to-use-cpp-smart-pointer/)。 + +当然,如果你企图直接使用构造函数而不用create方法的话,你会很惊讶地发现你做不到,因为助教已经很贴心地将构造函数设为private或者protected了,所以不用担心不小心的使用,而之所以不在构造函数中使用,原因参考[shared_from_this说明1](https://blog.csdn.net/weixin_38927079/article/details/115505724)和[shared_from_this说明2](https://blog.csdn.net/u012398613/article/details/52243764) + +### 本关具体任务 +1. 你需要在`src/SysYFIRBuilder`文件夹中,调用SysYF IR应用编程接口,填写`IRBuilder.cpp`文件,以实现 LLVM IR 的自动生成。注意以下几点: + * a. 创建include/SysYFIR中的对象时,只能通过create方法,而不能直接使用构造函数(原因参考[shared_from_this](#shared_from_this)),如下: + ```cpp + auto fun = Function::create(fun_type, node.name, module); + ``` + 而不是: + ```cpp + auto fun = new Function(fun_type, node.name, module); + ``` + * b. 尽量不要使用裸指针,而是使用shared_ptr和相关的类型转换方法,即`include/internal_types`定义的类型和方法 +2. 在`report.md`内回答[思考题](#思考题) +3. 在`contribution.md`内由组长填写各组员的贡献比 + +### 编译、运行与验证 + +#### 编译运行 SysYFCompiler + +```sh +mkdir build +cd build +cmake .. +make +``` +请注意,你会发现CMakeLists.txt中的CMAKE_CXX_FLAGS多了很多参数,我们介绍其中一部分(参考[gcc warning options](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html)): + * -Wextra:打印一些额外的warning信息 + * -Wno-unused:不警告未使用的变量,框架中一些函数有一些不用的参数 + * -Wshadow:如果一个局部变量隐藏掉了其他的变量、参数等,报告warning + * -Werror:将所有的warning都视为error,也就是说如果你觉得你的warning并不对程序正确性有影响,你可以把-Werror删除。 + +编译后会产生 `SysYFCompiler` 程序,它能将SysYF源程序(sy文件)输出为LLVM IR。 +当需要对 sy 文件测试时,可以这样使用: + +```sh +SysYFCompiler test.sy -emit-ir -o test.ll +``` +得到对应的ll文件。 + +#### 自动测试 + +本实训项目提供了自动评测脚本, 在`Student/task3/`目录下执行`python3 test.py`, 即可得到评测信息 + +### 思考题 +请在`report/report.md`中详细回答下述思考题。 + +3-1. 在`scope`内单独处理`func`的好处有哪些。 + + +### 选做 + +本实训项目提供了选做内容, 若你能完成选做部分, 将会有额外加分(仅针对本次实验的团队代码得分, 并且分数不能超过该部分得分上限)。 + +选做部分验收方式为线下验收,你需要在线下检查时提供对应代码通过助教给出的选做部分测试样例,并且讲解你的代码。 + +选做部分说明如下:(每个班只展示一部分) + - H班: + - 多维数组 + - 网安班: + - 多维数组 + - 将一维数组指针作为参数 + - 逻辑运算(\&\&, \|\|, \!), 重点考察短路计算 + +#### 多维数组 + +目前给出的SysYF IR应用编程接口并不支持多维数组的实现,因此你需要修改接口,以实现多维数组的声明、初始化和使用,你可以修改的内容为文件夹`include/SysYFIR`,`include/SysYFIRBuilder`,`src/SysYFIR`,`src/SysYFIRBuilder`内的所有内容 + +多维数组在目前的接口基础上,一般有两种做法: +- 直接实现,可以参考 clang 生成的 LLVM IR,修改当前接口使其支持多维的数组类型 +- 展平,把高维数组当成一维数组存储,修改当前接口使其能保存一些必要信息 + +在初始化多维数组时,与一维数组不同的是,存在对齐问题,这里假设多维数组的初始化为完全对齐(在每个大括号处均对齐),以下两种初始化是等价的: +`int a[5][2] = {1,{2,3},{4},{5,6,7}}` +`int a[5][2] = {{1,0},{2,3},{4,0},{5,6},{7,0}}` + +#### 数组指针参数 & 逻辑运算 + +目前给出的SysYF IR接口支持数组指针参数和逻辑运算的短路计算,因此你不需要修改接口。 +注意`pointer`和`array`的区别以及文法中`&&`和`||`的优先级。 + +### 备注 + +测试样例除了位于版本库中的公开测例外,还包含不开放的隐藏测例。 + +平台上第三关的评测只判断公开测例是否完全通过, 第三关的分数由助教线下检查后,根据公开测例和隐藏测例的通过情况确定, 因此请自行设计合法测例测试你们的代码,确保你们的代码考虑了足够多情况以通过尽可能多的隐藏测例。 + +请将你编写的测例代码上传到`Student/task3/test_stu/`。 diff --git a/include/AST/SyntaxTree.h b/include/AST/SyntaxTree.h new file mode 100755 index 0000000..59bd387 --- /dev/null +++ b/include/AST/SyntaxTree.h @@ -0,0 +1,330 @@ +#ifndef _SYSYF_SYNTAX_TREE_H_ +#define _SYSYF_SYNTAX_TREE_H_ + +#include +#include +#include + +#include "location.hh" +#include "internal_types.h" + +namespace SysYF +{ +namespace SyntaxTree +{ + +using Position = yy::location; + +// Enumerations +enum class Type +{ + INT = 0, + VOID, + STRING, + BOOL, + FLOAT +}; + +enum class BinOp +{ + PLUS = 0, + MINUS, + MULTIPLY, + DIVIDE, + MODULO +}; + +enum class UnaryOp +{ + PLUS = 0, + MINUS +}; + +enum class UnaryCondOp +{ + NOT = 0 +}; + +enum class BinaryCondOp +{ + LT = 0, + LTE, + GT, + GTE, + EQ, + NEQ, + LAND, + LOR +}; + +// Forward declaration +struct Node; +struct Assembly; +struct GlobalDef; +struct FuncDef; + +struct Expr; +struct CondExpr; +struct AddExpr; +struct BinaryExpr; +struct BinaryCondExpr; +struct UnaryCondExpr; +struct UnaryExpr; +struct LVal; +struct Literal; + +struct Stmt; +struct VarDef; +struct AssignStmt; +struct FuncCallStmt; +struct ReturnStmt; +struct BlockStmt; +struct EmptyStmt; +struct ExprStmt; + +struct FuncParam; +struct FuncFParamList; + +struct IfStmt; +struct WhileStmt; +struct BreakStmt; +struct ContinueStmt; +struct InitVal; + +class Visitor; + +// Virtual base of all kinds of syntax tree nodes. +struct Node +{ + Position loc; + // Used in Visitor. Irrelevant to syntax tree generation. + virtual void accept(Visitor &visitor) = 0; +}; + +//node for initial value +struct InitVal: Node{ + bool isExp; + PtrVec elementList; + //std::vector> elementList; + Ptr expr; + void accept(Visitor &visitor) final; +}; + +// Root node of an ordinary syntax tree. +struct Assembly : Node +{ + PtrVec global_defs; + void accept(Visitor &visitor) final; +}; + +// Virtual base of global definitions, function or variable one. +struct GlobalDef : virtual Node +{ + void accept(Visitor &visitor) override = 0; +}; + +// Function definition. +struct FuncDef : GlobalDef +{ + Type ret_type; + Ptr param_list; + std::string name; + Ptr body; + void accept(Visitor &visitor) final; +}; + +// Virtual base for statements. +struct Stmt : virtual Node +{ + void accept(Visitor &visitor) override = 0; +}; + +// Variable definition. Multiple of this would be both a statement and a global definition; however, itself only +// represents a single variable definition. +struct VarDef : Stmt, GlobalDef +{ + bool is_constant; + Type btype; + std::string name; + bool is_inited; // This is used to verify `{}` + PtrVec array_length; // empty for non-array variables + Ptr initializers; + void accept(Visitor &visitor) final; +}; + +// Assignment statement. +struct AssignStmt : Stmt +{ + Ptr target; + Ptr value; + void accept(Visitor &visitor) final; +}; + +// Return statement. +struct ReturnStmt : Stmt +{ + Ptr ret; // nullptr for void return + void accept(Visitor &visitor) final; +}; + +// BlockStmt statement. +struct BlockStmt : Stmt +{ + PtrVec body; + void accept(Visitor &visitor) final; +}; + +// Empty statement (aka a single ';'). +struct EmptyStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +struct ExprStmt : Stmt +{ + Ptr exp; + void accept(Visitor &visitor) final; +}; + +// Virtual base of expressions. +struct Expr : Node +{ + void accept(Visitor &visitor) override = 0; +}; + +struct CondExpr : Expr +{ + void accept(Visitor &visitor) override = 0; +}; + +struct AddExpr : Expr +{ + void accept(Visitor &visitor) override = 0; +}; + + +struct UnaryCondExpr : CondExpr{ + UnaryCondOp op; + Ptr rhs; + void accept(Visitor &visitor) final; +}; + +struct BinaryCondExpr : CondExpr{ + BinaryCondOp op; + Ptr lhs,rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `lhs op rhs`. +struct BinaryExpr : AddExpr +{ + BinOp op; + Ptr lhs, rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `op rhs`. +struct UnaryExpr : AddExpr +{ + UnaryOp op; + Ptr rhs; + void accept(Visitor &visitor) final; +}; + +// Expression like `ident` or `ident[exp]`. +struct LVal : AddExpr +{ + std::string name; + PtrVec array_index; // nullptr if not indexed as array + void accept(Visitor &visitor) final; +}; + +// Expression constructed by a literal number. +struct Literal : AddExpr +{ + Type literal_type; + int int_const; + // std::string str; + double float_const; + void accept(Visitor &visitor) final; +}; + +// Function call statement. +struct FuncCallStmt : AddExpr +{ + std::string name; + PtrVec params; + void accept(Visitor &visitor) final; +}; + +struct FuncParam : Node +{ + std::string name; + Type param_type; + PtrVec array_index; // nullptr if not indexed as array + void accept(Visitor &visitor) final; +}; + +struct FuncFParamList : Node +{ + PtrVec params; + void accept(Visitor &visitor) final; +}; + +struct IfStmt : Stmt +{ + Ptr cond_exp; + Ptr if_statement; + Ptr else_statement; + void accept(Visitor &visitor) final; +}; + +struct WhileStmt : Stmt +{ + Ptr cond_exp; + Ptr statement; + void accept(Visitor &visitor) final; +}; + +struct BreakStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +struct ContinueStmt : Stmt +{ + void accept(Visitor &visitor) final; +}; + +// Visitor base type +class Visitor +{ +public: + virtual void visit(Assembly &node) = 0; + virtual void visit(FuncDef &node) = 0; + virtual void visit(BinaryExpr &node) = 0; + virtual void visit(UnaryExpr &node) = 0; + virtual void visit(LVal &node) = 0; + virtual void visit(Literal &node) = 0; + virtual void visit(ReturnStmt &node) = 0; + virtual void visit(VarDef &node) = 0; + virtual void visit(AssignStmt &node) = 0; + virtual void visit(FuncCallStmt &node) = 0; + virtual void visit(BlockStmt &node) = 0; + virtual void visit(EmptyStmt &node) = 0; + virtual void visit(ExprStmt &node) = 0; + virtual void visit(FuncParam &node) = 0; + virtual void visit(FuncFParamList &node) = 0; + virtual void visit(IfStmt &node) = 0; + virtual void visit(WhileStmt &node) = 0; + virtual void visit(BreakStmt &node) = 0; + virtual void visit(ContinueStmt &node) = 0; + virtual void visit(UnaryCondExpr &node) = 0; + virtual void visit(BinaryCondExpr &node) = 0; + virtual void visit(InitVal &node) = 0; +}; + +} +} + +#endif // _SYSYF_SYNTAX_TREE_H_ diff --git a/include/AST/SyntaxTreePrinter.h b/include/AST/SyntaxTreePrinter.h new file mode 100755 index 0000000..8991451 --- /dev/null +++ b/include/AST/SyntaxTreePrinter.h @@ -0,0 +1,43 @@ +#ifndef _SYSYF_SYNTAX_TREE_PRINTER_H_ +#define _SYSYF_SYNTAX_TREE_PRINTER_H_ + +#include "SyntaxTree.h" + +namespace SysYF +{ +namespace SyntaxTree +{ +class SyntaxTreePrinter : public SyntaxTree::Visitor +{ +public: + virtual void visit(SyntaxTree::Assembly &node) override; + virtual void visit(SyntaxTree::FuncDef &node) override; + virtual void visit(SyntaxTree::BinaryExpr &node) override; + virtual void visit(SyntaxTree::UnaryExpr &node) override; + virtual void visit(SyntaxTree::LVal &node) override; + virtual void visit(SyntaxTree::Literal &node) override; + virtual void visit(SyntaxTree::ReturnStmt &node) override; + virtual void visit(SyntaxTree::VarDef &node) override; + virtual void visit(SyntaxTree::AssignStmt &node) override; + virtual void visit(SyntaxTree::FuncCallStmt &node) override; + virtual void visit(SyntaxTree::BlockStmt &node) override; + virtual void visit(SyntaxTree::EmptyStmt &node) override; + virtual void visit(SyntaxTree::ExprStmt &node) override; + virtual void visit(SyntaxTree::FuncParam &node) override; + virtual void visit(SyntaxTree::FuncFParamList &node) override; + virtual void visit(SyntaxTree::BinaryCondExpr &node) override; + virtual void visit(SyntaxTree::UnaryCondExpr &node) override; + virtual void visit(SyntaxTree::IfStmt &node) override; + virtual void visit(SyntaxTree::WhileStmt &node) override; + virtual void visit(SyntaxTree::BreakStmt &node) override; + virtual void visit(SyntaxTree::ContinueStmt &node) override; + virtual void visit(SyntaxTree::InitVal &node) override; + void print_indent(); +private: + int indent = 0; +}; + +} +} + +#endif // _SYSYF_SYNTAX_TREE_PRINTER_H_ diff --git a/include/ErrorReporter/ErrorReporter.h b/include/ErrorReporter/ErrorReporter.h new file mode 100755 index 0000000..afbab92 --- /dev/null +++ b/include/ErrorReporter/ErrorReporter.h @@ -0,0 +1,29 @@ +#ifndef _SYSYF_ERROR_REPORTER_H_ +#define _SYSYF_ERROR_REPORTER_H_ + +#include +#include +#include +#include +#include "SyntaxTree.h" + +namespace SysYF +{ +class ErrorReporter +{ +public: + using Position = SyntaxTree::Position; + explicit ErrorReporter(std::ostream &error_stream); + + void error(Position pos, const std::string &msg); + void warn(Position pos, const std::string &msg); + +protected: + virtual void report(Position pos, const std::string &msg, const std::string &prefix); + +private: + std::ostream &err; +}; + +} +#endif // _SYSYF_ERROR_REPORTER_H_ diff --git a/include/Frontend/FlexLexer.h b/include/Frontend/FlexLexer.h new file mode 100644 index 0000000..b725b1f --- /dev/null +++ b/include/Frontend/FlexLexer.h @@ -0,0 +1,225 @@ +// -*-C++-*- +// FlexLexer.h -- define interfaces for lexical analyzer classes generated +// by flex + +// Copyright (c) 1993 The Regents of the University of California. +// All rights reserved. +// +// This code is derived from software contributed to Berkeley by +// Kent Williams and Tom Epperly. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: + +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. + +// Neither the name of the University nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. + +// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR +// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE. + +// This file defines FlexLexer, an abstract class which specifies the +// external interface provided to flex C++ lexer objects, and yyFlexLexer, +// which defines a particular lexer class. +// +// If you want to create multiple lexer classes, you use the -P flag +// to rename each yyFlexLexer to some other xxFlexLexer. You then +// include in your other sources once per lexer class: +// +// #undef yyFlexLexer +// #define yyFlexLexer xxFlexLexer +// #include +// +// #undef yyFlexLexer +// #define yyFlexLexer zzFlexLexer +// #include +// ... + +#ifndef __FLEX_LEXER_H +// Never included before - need to define base class. +#define __FLEX_LEXER_H + +#include +# ifndef FLEX_STD +# define FLEX_STD std:: +# endif + +extern "C++" { + +struct yy_buffer_state; +typedef int yy_state_type; + +class FlexLexer { +public: + virtual ~FlexLexer() { } + + const char* YYText() const { return yytext; } + int YYLeng() const { return yyleng; } + + virtual void + yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0; + virtual struct yy_buffer_state* + yy_create_buffer( FLEX_STD istream* s, int size ) = 0; + virtual struct yy_buffer_state* + yy_create_buffer( FLEX_STD istream& s, int size ) = 0; + virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0; + virtual void yyrestart( FLEX_STD istream* s ) = 0; + virtual void yyrestart( FLEX_STD istream& s ) = 0; + + virtual int yylex() = 0; + + // Call yylex with new input/output sources. + int yylex( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ) + { + switch_streams( new_in, new_out ); + return yylex(); + } + + int yylex( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0) + { + switch_streams( new_in, new_out ); + return yylex(); + } + + // Switch to new input/output streams. A nil stream pointer + // indicates "keep the current one". + virtual void switch_streams( FLEX_STD istream* new_in, + FLEX_STD ostream* new_out ) = 0; + virtual void switch_streams( FLEX_STD istream& new_in, + FLEX_STD ostream& new_out ) = 0; + + int lineno() const { return yylineno; } + + int debug() const { return yy_flex_debug; } + void set_debug( int flag ) { yy_flex_debug = flag; } + +protected: + char* yytext; + int yyleng; + int yylineno; // only maintained if you use %option yylineno + int yy_flex_debug; // only has effect with -d or "%option debug" +}; + +} +#endif // FLEXLEXER_H + +#if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce) +// Either this is the first time through (yyFlexLexerOnce not defined), +// or this is a repeated include to define a different flavor of +// yyFlexLexer, as discussed in the flex manual. +#define yyFlexLexerOnce + +extern "C++" { + +class yyFlexLexer : public FlexLexer { +public: + // arg_yyin and arg_yyout default to the cin and cout, but we + // only make that assignment when initializing in yylex(). + yyFlexLexer( FLEX_STD istream& arg_yyin, FLEX_STD ostream& arg_yyout ); + yyFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 ); +private: + void ctor_common(); + +public: + + virtual ~yyFlexLexer(); + + void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ); + struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size ); + struct yy_buffer_state* yy_create_buffer( FLEX_STD istream& s, int size ); + void yy_delete_buffer( struct yy_buffer_state* b ); + void yyrestart( FLEX_STD istream* s ); + void yyrestart( FLEX_STD istream& s ); + + void yypush_buffer_state( struct yy_buffer_state* new_buffer ); + void yypop_buffer_state(); + + virtual int yylex(); + virtual void switch_streams( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ); + virtual void switch_streams( FLEX_STD istream* new_in = 0, FLEX_STD ostream* new_out = 0 ); + virtual int yywrap(); + +protected: + virtual int LexerInput( char* buf, int max_size ); + virtual void LexerOutput( const char* buf, int size ); + virtual void LexerError( const char* msg ); + + void yyunput( int c, char* buf_ptr ); + int yyinput(); + + void yy_load_buffer_state(); + void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream& s ); + void yy_flush_buffer( struct yy_buffer_state* b ); + + int yy_start_stack_ptr; + int yy_start_stack_depth; + int* yy_start_stack; + + void yy_push_state( int new_state ); + void yy_pop_state(); + int yy_top_state(); + + yy_state_type yy_get_previous_state(); + yy_state_type yy_try_NUL_trans( yy_state_type current_state ); + int yy_get_next_buffer(); + + FLEX_STD istream yyin; // input source for default LexerInput + FLEX_STD ostream yyout; // output sink for default LexerOutput + + // yy_hold_char holds the character lost when yytext is formed. + char yy_hold_char; + + // Number of characters read into yy_ch_buf. + int yy_n_chars; + + // Points to current character in buffer. + char* yy_c_buf_p; + + int yy_init; // whether we need to initialize + int yy_start; // start state number + + // Flag which is used to allow yywrap()'s to do buffer switches + // instead of setting up a fresh yyin. A bit of a hack ... + int yy_did_buffer_switch_on_eof; + + + size_t yy_buffer_stack_top; /**< index of top of stack. */ + size_t yy_buffer_stack_max; /**< capacity of stack. */ + struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */ + void yyensure_buffer_stack(void); + + // The following are not always needed, but may be depending + // on use of certain flex features (like REJECT or yymore()). + + yy_state_type yy_last_accepting_state; + char* yy_last_accepting_cpos; + + yy_state_type* yy_state_buf; + yy_state_type* yy_state_ptr; + + char* yy_full_match; + int* yy_full_state; + int yy_full_lp; + + int yy_lp; + int yy_looking_for_trail_begin; + + int yy_more_flag; + int yy_more_len; + int yy_more_offset; + int yy_prev_more_offset; +}; + +} + +#endif // yyFlexLexer || ! yyFlexLexerOnce + diff --git a/include/Frontend/SysYFDriver.h b/include/Frontend/SysYFDriver.h new file mode 100755 index 0000000..1bd8e96 --- /dev/null +++ b/include/Frontend/SysYFDriver.h @@ -0,0 +1,50 @@ +#ifndef _SYSYF_DRIVER_H_ +#define _SYSYF_DRIVER_H_ + +#include +#include +#include + +// Generated by bison: +#include "SysYFParser.h" + +#include "SysYFFlexLexer.h" + +// Conducting the whole scanning and parsing of SysYF. +class SysYFDriver +{ +public: + SysYFDriver(); + virtual ~SysYFDriver(); + + std::map variables; + + int result; + + // SysYF lexer + SysYFFlexLexer lexer; + + std::ifstream instream; + + // Handling the SysYF scanner. + void scan_begin(); + void scan_end(); + bool trace_scanning; + + // Run the parser on file F. + // Return 0 on success. + SysYF::Ptr parse(const std::string& f); + // The name of the file being parsed. + // Used later to pass the file name to the location tracker. + std::string file; + // Whether parser traces should be generated. + bool trace_parsing; + + // Error handling. + void error(const yy::location& l, const std::string& m); + void error(const std::string& m); + + SysYF::Ptr root = nullptr; +}; + +#endif // _SYSYF_DRIVER_H_ diff --git a/include/Frontend/SysYFFlexLexer.h b/include/Frontend/SysYFFlexLexer.h new file mode 100755 index 0000000..f567ebe --- /dev/null +++ b/include/Frontend/SysYFFlexLexer.h @@ -0,0 +1,37 @@ +#ifndef _SYSYF_FLEX_LEXER_H_ +#define _SYSYF_FLEX_LEXER_H_ + +#ifndef YY_DECL +#define YY_DECL \ + yy::SysYFParser::symbol_type SysYFFlexLexer::yylex(SysYFDriver& driver) +#endif + +// We need this for yyFlexLexer. If we don't #undef yyFlexLexer, the +// preprocessor chokes on the line `#define yyFlexLexer yyFlexLexer` +// in `FlexLexer.h`: +#undef yyFlexLexer +#include + +// We need this for the yy::SysYFParser::symbol_type: +#include "SysYFParser.h" + +// We need this for the yy::location type: +#include "location.hh" + +class SysYFFlexLexer : public yyFlexLexer { +public: + // Use the superclass's constructor: + using yyFlexLexer::yyFlexLexer; + + // Provide the interface to `yylex`; `flex` will emit the + // definition into `SysYFScanner.cpp`: + yy::SysYFParser::symbol_type yylex(SysYFDriver& driver); + + // This seems like a reasonable place to put the location object + // rather than it being static (in the sense of having internal + // linkage at translation unit scope, not in the sense of being a + // class variable): + yy::location loc; +}; + +#endif // _SYSYF_FLEX_LEXER_H_ diff --git a/include/Frontend/SysYFParser.h b/include/Frontend/SysYFParser.h new file mode 100644 index 0000000..c39daa3 --- /dev/null +++ b/include/Frontend/SysYFParser.h @@ -0,0 +1,2911 @@ +// A Bison parser, made by GNU Bison 3.8.2. + +// Skeleton interface for Bison LALR(1) parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + + +/** + ** \file ./SysYFParser.h + ** Define the yy::parser class. + */ + +// C++ LALR(1) parser skeleton written by Akim Demaille. + +// DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, +// especially those whose name start with YY_ or yy_. They are +// private implementation details that can be changed or removed. + +#ifndef YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_SYSYFPARSER_H_INCLUDED +# define YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_SYSYFPARSER_H_INCLUDED +// "%code requires" blocks. +#line 12 "../../grammar/SysYFParser.yy" + +#include +#include "SyntaxTree.h" +class SysYFDriver; + +#line 55 "./SysYFParser.h" + +# include +# include // std::abort +# include +# include +# include +# include + +#if defined __cplusplus +# define YY_CPLUSPLUS __cplusplus +#else +# define YY_CPLUSPLUS 199711L +#endif + +// Support move semantics when possible. +#if 201103L <= YY_CPLUSPLUS +# define YY_MOVE std::move +# define YY_MOVE_OR_COPY move +# define YY_MOVE_REF(Type) Type&& +# define YY_RVREF(Type) Type&& +# define YY_COPY(Type) Type +#else +# define YY_MOVE +# define YY_MOVE_OR_COPY copy +# define YY_MOVE_REF(Type) Type& +# define YY_RVREF(Type) const Type& +# define YY_COPY(Type) const Type& +#endif + +// Support noexcept when possible. +#if 201103L <= YY_CPLUSPLUS +# define YY_NOEXCEPT noexcept +# define YY_NOTHROW +#else +# define YY_NOEXCEPT +# define YY_NOTHROW throw () +#endif + +// Support constexpr when possible. +#if 201703 <= YY_CPLUSPLUS +# define YY_CONSTEXPR constexpr +#else +# define YY_CONSTEXPR +#endif +# include "location.hh" +#include +#ifndef YY_ASSERT +# include +# define YY_ASSERT assert +#endif + + +#ifndef YY_ATTRIBUTE_PURE +# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__)) +# else +# define YY_ATTRIBUTE_PURE +# endif +#endif + +#ifndef YY_ATTRIBUTE_UNUSED +# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__) +# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__)) +# else +# define YY_ATTRIBUTE_UNUSED +# endif +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YY_USE(E) ((void) (E)) +#else +# define YY_USE(E) /* empty */ +#endif + +/* Suppress an incorrect diagnostic about yylval being uninitialized. */ +#if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__ +# if __GNUC__ * 100 + __GNUC_MINOR__ < 407 +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") +# else +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \ + _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# endif +# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ + _Pragma ("GCC diagnostic pop") +#else +# define YY_INITIAL_VALUE(Value) Value +#endif +#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_END +#endif +#ifndef YY_INITIAL_VALUE +# define YY_INITIAL_VALUE(Value) /* Nothing. */ +#endif + +#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__ +# define YY_IGNORE_USELESS_CAST_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"") +# define YY_IGNORE_USELESS_CAST_END \ + _Pragma ("GCC diagnostic pop") +#endif +#ifndef YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_BEGIN +# define YY_IGNORE_USELESS_CAST_END +#endif + +# ifndef YY_CAST +# ifdef __cplusplus +# define YY_CAST(Type, Val) static_cast (Val) +# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast (Val) +# else +# define YY_CAST(Type, Val) ((Type) (Val)) +# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val)) +# endif +# endif +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 1 +#endif + +namespace yy { +#line 195 "./SysYFParser.h" + + + + + /// A Bison parser. + class SysYFParser + { + public: +#ifdef YYSTYPE +# ifdef __GNUC__ +# pragma GCC message "bison: do not #define YYSTYPE in C++, use %define api.value.type" +# endif + typedef YYSTYPE value_type; +#else + /// A buffer to store and retrieve objects. + /// + /// Sort of a variant, but does not keep track of the nature + /// of the stored data, since that knowledge is available + /// via the current parser state. + class value_type + { + public: + /// Type of *this. + typedef value_type self_type; + + /// Empty construction. + value_type () YY_NOEXCEPT + : yyraw_ () + , yytypeid_ (YY_NULLPTR) + {} + + /// Construct and fill. + template + value_type (YY_RVREF (T) t) + : yytypeid_ (&typeid (T)) + { + YY_ASSERT (sizeof (T) <= size); + new (yyas_ ()) T (YY_MOVE (t)); + } + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + value_type (const self_type&) = delete; + /// Non copyable. + self_type& operator= (const self_type&) = delete; +#endif + + /// Destruction, allowed only if empty. + ~value_type () YY_NOEXCEPT + { + YY_ASSERT (!yytypeid_); + } + +# if 201103L <= YY_CPLUSPLUS + /// Instantiate a \a T in here from \a t. + template + T& + emplace (U&&... u) + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (std::forward (u)...); + } +# else + /// Instantiate an empty \a T in here. + template + T& + emplace () + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (); + } + + /// Instantiate a \a T in here from \a t. + template + T& + emplace (const T& t) + { + YY_ASSERT (!yytypeid_); + YY_ASSERT (sizeof (T) <= size); + yytypeid_ = & typeid (T); + return *new (yyas_ ()) T (t); + } +# endif + + /// Instantiate an empty \a T in here. + /// Obsolete, use emplace. + template + T& + build () + { + return emplace (); + } + + /// Instantiate a \a T in here from \a t. + /// Obsolete, use emplace. + template + T& + build (const T& t) + { + return emplace (t); + } + + /// Accessor to a built \a T. + template + T& + as () YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == typeid (T)); + YY_ASSERT (sizeof (T) <= size); + return *yyas_ (); + } + + /// Const accessor to a built \a T (for %printer). + template + const T& + as () const YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == typeid (T)); + YY_ASSERT (sizeof (T) <= size); + return *yyas_ (); + } + + /// Swap the content with \a that, of same type. + /// + /// Both variants must be built beforehand, because swapping the actual + /// data requires reading it (with as()), and this is not possible on + /// unconstructed variants: it would require some dynamic testing, which + /// should not be the variant's responsibility. + /// Swapping between built and (possibly) non-built is done with + /// self_type::move (). + template + void + swap (self_type& that) YY_NOEXCEPT + { + YY_ASSERT (yytypeid_); + YY_ASSERT (*yytypeid_ == *that.yytypeid_); + std::swap (as (), that.as ()); + } + + /// Move the content of \a that to this. + /// + /// Destroys \a that. + template + void + move (self_type& that) + { +# if 201103L <= YY_CPLUSPLUS + emplace (std::move (that.as ())); +# else + emplace (); + swap (that); +# endif + that.destroy (); + } + +# if 201103L <= YY_CPLUSPLUS + /// Move the content of \a that to this. + template + void + move (self_type&& that) + { + emplace (std::move (that.as ())); + that.destroy (); + } +#endif + + /// Copy the content of \a that to this. + template + void + copy (const self_type& that) + { + emplace (that.as ()); + } + + /// Destroy the stored \a T. + template + void + destroy () + { + as ().~T (); + yytypeid_ = YY_NULLPTR; + } + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + value_type (const self_type&); + /// Non copyable. + self_type& operator= (const self_type&); +#endif + + /// Accessor to raw memory as \a T. + template + T* + yyas_ () YY_NOEXCEPT + { + void *yyp = yyraw_; + return static_cast (yyp); + } + + /// Const accessor to raw memory as \a T. + template + const T* + yyas_ () const YY_NOEXCEPT + { + const void *yyp = yyraw_; + return static_cast (yyp); + } + + /// An auxiliary type to compute the largest semantic type. + union union_type + { + // CompUnit + char dummy1[sizeof (SysYF::Ptr)]; + + // Block + char dummy2[sizeof (SysYF::Ptr)]; + + // OptionRet + // Exp + // RelExp + // EqExp + // LAndExp + // LOrExp + // CondExp + char dummy3[sizeof (SysYF::Ptr)]; + + // FuncDef + char dummy4[sizeof (SysYF::Ptr)]; + + // FuncFParam + char dummy5[sizeof (SysYF::Ptr)]; + + // InitVal + // InitValList + // CommaInitValList + char dummy6[sizeof (SysYF::Ptr)]; + + // LVal + char dummy7[sizeof (SysYF::Ptr)]; + + // Number + char dummy8[sizeof (SysYF::Ptr)]; + + // Stmt + // IfStmt + char dummy9[sizeof (SysYF::Ptr)]; + + // ConstDef + // VarDef + char dummy10[sizeof (SysYF::Ptr)]; + + // ArrayExpList + // ExpList + // CommaExpList + char dummy11[sizeof (SysYF::PtrVec)]; + + // FParamList + // CommaFParamList + char dummy12[sizeof (SysYF::PtrVec)]; + + // GlobalDecl + char dummy13[sizeof (SysYF::PtrVec)]; + + // BlockItemList + // BlockItem + char dummy14[sizeof (SysYF::PtrVec)]; + + // ConstDecl + // ConstDefList + // VarDecl + // VarDefList + char dummy15[sizeof (SysYF::PtrVec)]; + + // BType + char dummy16[sizeof (SysYF::SyntaxTree::Type)]; + + // FLOATCONST + char dummy17[sizeof (float)]; + + // INTCONST + char dummy18[sizeof (int)]; + + // IDENTIFIER + // STRINGCONST + char dummy19[sizeof (std::string)]; + }; + + /// The size of the largest semantic type. + enum { size = sizeof (union_type) }; + + /// A buffer to store semantic values. + union + { + /// Strongest alignment constraints. + long double yyalign_me_; + /// A buffer large enough to store any of the semantic values. + char yyraw_[size]; + }; + + /// Whether the content is built: if defined, the name of the stored type. + const std::type_info *yytypeid_; + }; + +#endif + /// Backward compatibility (Bison 3.8). + typedef value_type semantic_type; + + /// Symbol locations. + typedef location location_type; + + /// Syntax errors thrown from user actions. + struct syntax_error : std::runtime_error + { + syntax_error (const location_type& l, const std::string& m) + : std::runtime_error (m) + , location (l) + {} + + syntax_error (const syntax_error& s) + : std::runtime_error (s.what ()) + , location (s.location) + {} + + ~syntax_error () YY_NOEXCEPT YY_NOTHROW; + + location_type location; + }; + + /// Token kinds. + struct token + { + enum token_kind_type + { + TOK_YYEMPTY = -2, + TOK_YYEOF = 0, // "end of file" + TOK_YYerror = 256, // error + TOK_YYUNDEF = 304, // "invalid token" + TOK_END = 305, // END + TOK_ERROR = 258, // ERROR + TOK_PLUS = 259, // PLUS + TOK_MINUS = 260, // MINUS + TOK_MULTIPLY = 261, // MULTIPLY + TOK_DIVIDE = 262, // DIVIDE + TOK_MODULO = 263, // MODULO + TOK_LTE = 264, // LTE + TOK_GT = 265, // GT + TOK_GTE = 266, // GTE + TOK_EQ = 267, // EQ + TOK_NEQ = 268, // NEQ + TOK_ASSIGN = 269, // ASSIGN + TOK_SEMICOLON = 270, // SEMICOLON + TOK_COMMA = 271, // COMMA + TOK_LPARENTHESE = 272, // LPARENTHESE + TOK_RPARENTHESE = 273, // RPARENTHESE + TOK_LBRACKET = 274, // LBRACKET + TOK_RBRACKET = 275, // RBRACKET + TOK_LBRACE = 276, // LBRACE + TOK_RBRACE = 277, // RBRACE + TOK_ELSE = 278, // ELSE + TOK_IF = 279, // IF + TOK_INT = 280, // INT + TOK_RETURN = 281, // RETURN + TOK_VOID = 282, // VOID + TOK_WHILE = 283, // WHILE + TOK_IDENTIFIER = 284, // IDENTIFIER + TOK_FLOATCONST = 285, // FLOATCONST + TOK_INTCONST = 286, // INTCONST + TOK_LETTER = 287, // LETTER + TOK_EOL = 288, // EOL + TOK_COMMENT = 289, // COMMENT + TOK_BLANK = 290, // BLANK + TOK_CONST = 291, // CONST + TOK_BREAK = 292, // BREAK + TOK_CONTINUE = 293, // CONTINUE + TOK_NOT = 294, // NOT + TOK_AND = 295, // AND + TOK_OR = 296, // OR + TOK_MOD = 297, // MOD + TOK_FLOAT = 298, // FLOAT + TOK_LOGICAND = 299, // LOGICAND + TOK_LOGICOR = 300, // LOGICOR + TOK_LT = 301, // LT + TOK_STRINGCONST = 302, // STRINGCONST + TOK_LRBRACKET = 303, // LRBRACKET + TOK_UPLUS = 306, // UPLUS + TOK_UMINUS = 307, // UMINUS + TOK_UNOT = 308 // UNOT + }; + /// Backward compatibility alias (Bison 3.6). + typedef token_kind_type yytokentype; + }; + + /// Token kind, as returned by yylex. + typedef token::token_kind_type token_kind_type; + + /// Backward compatibility alias (Bison 3.6). + typedef token_kind_type token_type; + + /// Symbol kinds. + struct symbol_kind + { + enum symbol_kind_type + { + YYNTOKENS = 53, ///< Number of tokens. + S_YYEMPTY = -2, + S_YYEOF = 0, // "end of file" + S_YYerror = 1, // error + S_YYUNDEF = 2, // "invalid token" + S_END = 3, // END + S_ERROR = 4, // ERROR + S_PLUS = 5, // PLUS + S_MINUS = 6, // MINUS + S_MULTIPLY = 7, // MULTIPLY + S_DIVIDE = 8, // DIVIDE + S_MODULO = 9, // MODULO + S_LTE = 10, // LTE + S_GT = 11, // GT + S_GTE = 12, // GTE + S_EQ = 13, // EQ + S_NEQ = 14, // NEQ + S_ASSIGN = 15, // ASSIGN + S_SEMICOLON = 16, // SEMICOLON + S_COMMA = 17, // COMMA + S_LPARENTHESE = 18, // LPARENTHESE + S_RPARENTHESE = 19, // RPARENTHESE + S_LBRACKET = 20, // LBRACKET + S_RBRACKET = 21, // RBRACKET + S_LBRACE = 22, // LBRACE + S_RBRACE = 23, // RBRACE + S_ELSE = 24, // ELSE + S_IF = 25, // IF + S_INT = 26, // INT + S_RETURN = 27, // RETURN + S_VOID = 28, // VOID + S_WHILE = 29, // WHILE + S_IDENTIFIER = 30, // IDENTIFIER + S_FLOATCONST = 31, // FLOATCONST + S_INTCONST = 32, // INTCONST + S_LETTER = 33, // LETTER + S_EOL = 34, // EOL + S_COMMENT = 35, // COMMENT + S_BLANK = 36, // BLANK + S_CONST = 37, // CONST + S_BREAK = 38, // BREAK + S_CONTINUE = 39, // CONTINUE + S_NOT = 40, // NOT + S_AND = 41, // AND + S_OR = 42, // OR + S_MOD = 43, // MOD + S_FLOAT = 44, // FLOAT + S_LOGICAND = 45, // LOGICAND + S_LOGICOR = 46, // LOGICOR + S_LT = 47, // LT + S_STRINGCONST = 48, // STRINGCONST + S_LRBRACKET = 49, // LRBRACKET + S_UPLUS = 50, // UPLUS + S_UMINUS = 51, // UMINUS + S_UNOT = 52, // UNOT + S_YYACCEPT = 53, // $accept + S_Begin = 54, // Begin + S_CompUnit = 55, // CompUnit + S_GlobalDecl = 56, // GlobalDecl + S_ConstDecl = 57, // ConstDecl + S_ConstDefList = 58, // ConstDefList + S_BType = 59, // BType + S_ConstDef = 60, // ConstDef + S_VarDecl = 61, // VarDecl + S_VarDefList = 62, // VarDefList + S_VarDef = 63, // VarDef + S_ArrayExpList = 64, // ArrayExpList + S_InitVal = 65, // InitVal + S_InitValList = 66, // InitValList + S_CommaInitValList = 67, // CommaInitValList + S_ExpList = 68, // ExpList + S_CommaExpList = 69, // CommaExpList + S_FuncFParam = 70, // FuncFParam + S_FParamList = 71, // FParamList + S_CommaFParamList = 72, // CommaFParamList + S_FuncDef = 73, // FuncDef + S_Block = 74, // Block + S_BlockItemList = 75, // BlockItemList + S_BlockItem = 76, // BlockItem + S_Stmt = 77, // Stmt + S_IfStmt = 78, // IfStmt + S_OptionRet = 79, // OptionRet + S_LVal = 80, // LVal + S_Exp = 81, // Exp + S_RelExp = 82, // RelExp + S_EqExp = 83, // EqExp + S_LAndExp = 84, // LAndExp + S_LOrExp = 85, // LOrExp + S_CondExp = 86, // CondExp + S_Number = 87 // Number + }; + }; + + /// (Internal) symbol kind. + typedef symbol_kind::symbol_kind_type symbol_kind_type; + + /// The number of tokens. + static const symbol_kind_type YYNTOKENS = symbol_kind::YYNTOKENS; + + /// A complete symbol. + /// + /// Expects its Base type to provide access to the symbol kind + /// via kind (). + /// + /// Provide access to semantic value and location. + template + struct basic_symbol : Base + { + /// Alias to Base. + typedef Base super_type; + + /// Default constructor. + basic_symbol () YY_NOEXCEPT + : value () + , location () + {} + +#if 201103L <= YY_CPLUSPLUS + /// Move constructor. + basic_symbol (basic_symbol&& that) + : Base (std::move (that)) + , value () + , location (std::move (that.location)) + { + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SysYF::Ptr > (std::move (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SysYF::PtrVec > (std::move (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SysYF::PtrVec > (std::move (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SysYF::PtrVec > (std::move (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SysYF::PtrVec > (std::move (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SysYF::PtrVec > (std::move (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SysYF::SyntaxTree::Type > (std::move (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (std::move (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (std::move (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (std::move (that.value)); + break; + + default: + break; + } + + } +#endif + + /// Copy constructor. + basic_symbol (const basic_symbol& that); + + /// Constructors for typed symbols. +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, location_type&& l) + : Base (t) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const location_type& l) + : Base (t) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::Ptr&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::Ptr& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::PtrVec&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::PtrVec& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::PtrVec&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::PtrVec& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::PtrVec&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::PtrVec& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::PtrVec&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::PtrVec& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::PtrVec&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::PtrVec& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, SysYF::SyntaxTree::Type&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const SysYF::SyntaxTree::Type& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, float&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const float& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, int&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const int& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + +#if 201103L <= YY_CPLUSPLUS + basic_symbol (typename Base::kind_type t, std::string&& v, location_type&& l) + : Base (t) + , value (std::move (v)) + , location (std::move (l)) + {} +#else + basic_symbol (typename Base::kind_type t, const std::string& v, const location_type& l) + : Base (t) + , value (v) + , location (l) + {} +#endif + + /// Destroy the symbol. + ~basic_symbol () + { + clear (); + } + + + + /// Destroy contents, and record that is empty. + void clear () YY_NOEXCEPT + { + // User destructor. + symbol_kind_type yykind = this->kind (); + basic_symbol& yysym = *this; + (void) yysym; + switch (yykind) + { + default: + break; + } + + // Value type destructor. +switch (yykind) + { + case symbol_kind::S_CompUnit: // CompUnit + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_Block: // Block + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_LVal: // LVal + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_Number: // Number + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.template destroy< SysYF::Ptr > (); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.template destroy< SysYF::PtrVec > (); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.template destroy< SysYF::PtrVec > (); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.template destroy< SysYF::PtrVec > (); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.template destroy< SysYF::PtrVec > (); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.template destroy< SysYF::PtrVec > (); + break; + + case symbol_kind::S_BType: // BType + value.template destroy< SysYF::SyntaxTree::Type > (); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.template destroy< float > (); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.template destroy< int > (); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.template destroy< std::string > (); + break; + + default: + break; + } + + Base::clear (); + } + + /// The user-facing name of this symbol. + std::string name () const YY_NOEXCEPT + { + return SysYFParser::symbol_name (this->kind ()); + } + + /// Backward compatibility (Bison 3.6). + symbol_kind_type type_get () const YY_NOEXCEPT; + + /// Whether empty. + bool empty () const YY_NOEXCEPT; + + /// Destructive move, \a s is emptied into this. + void move (basic_symbol& s); + + /// The semantic value. + value_type value; + + /// The location. + location_type location; + + private: +#if YY_CPLUSPLUS < 201103L + /// Assignment operator. + basic_symbol& operator= (const basic_symbol& that); +#endif + }; + + /// Type access provider for token (enum) based symbols. + struct by_kind + { + /// The symbol kind as needed by the constructor. + typedef token_kind_type kind_type; + + /// Default constructor. + by_kind () YY_NOEXCEPT; + +#if 201103L <= YY_CPLUSPLUS + /// Move constructor. + by_kind (by_kind&& that) YY_NOEXCEPT; +#endif + + /// Copy constructor. + by_kind (const by_kind& that) YY_NOEXCEPT; + + /// Constructor from (external) token numbers. + by_kind (kind_type t) YY_NOEXCEPT; + + + + /// Record that this symbol is empty. + void clear () YY_NOEXCEPT; + + /// Steal the symbol kind from \a that. + void move (by_kind& that); + + /// The (internal) type number (corresponding to \a type). + /// \a empty when empty. + symbol_kind_type kind () const YY_NOEXCEPT; + + /// Backward compatibility (Bison 3.6). + symbol_kind_type type_get () const YY_NOEXCEPT; + + /// The symbol kind. + /// \a S_YYEMPTY when empty. + symbol_kind_type kind_; + }; + + /// Backward compatibility for a private implementation detail (Bison 3.6). + typedef by_kind by_type; + + /// "External" symbols: returned by the scanner. + struct symbol_type : basic_symbol + { + /// Superclass. + typedef basic_symbol super_type; + + /// Empty symbol. + symbol_type () YY_NOEXCEPT {} + + /// Constructor for valueless symbols, and symbols from each type. +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, location_type l) + : super_type (token_kind_type (tok), std::move (l)) +#else + symbol_type (int tok, const location_type& l) + : super_type (token_kind_type (tok), l) +#endif + { +#if !defined _MSC_VER || defined __clang__ + YY_ASSERT (tok == token::TOK_YYEOF + || tok == token::TOK_YYerror + || (token::TOK_YYUNDEF <= tok && tok <= token::TOK_END) + || (token::TOK_ERROR <= tok && tok <= token::TOK_WHILE) + || (token::TOK_LETTER <= tok && tok <= token::TOK_LT) + || tok == token::TOK_LRBRACKET + || (token::TOK_UPLUS <= tok && tok <= token::TOK_UNOT)); +#endif + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, float v, location_type l) + : super_type (token_kind_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const float& v, const location_type& l) + : super_type (token_kind_type (tok), v, l) +#endif + { +#if !defined _MSC_VER || defined __clang__ + YY_ASSERT (tok == token::TOK_FLOATCONST); +#endif + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, int v, location_type l) + : super_type (token_kind_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const int& v, const location_type& l) + : super_type (token_kind_type (tok), v, l) +#endif + { +#if !defined _MSC_VER || defined __clang__ + YY_ASSERT (tok == token::TOK_INTCONST); +#endif + } +#if 201103L <= YY_CPLUSPLUS + symbol_type (int tok, std::string v, location_type l) + : super_type (token_kind_type (tok), std::move (v), std::move (l)) +#else + symbol_type (int tok, const std::string& v, const location_type& l) + : super_type (token_kind_type (tok), v, l) +#endif + { +#if !defined _MSC_VER || defined __clang__ + YY_ASSERT (tok == token::TOK_IDENTIFIER + || tok == token::TOK_STRINGCONST); +#endif + } + }; + + /// Build a parser object. + SysYFParser (SysYFDriver& driver_yyarg); + virtual ~SysYFParser (); + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + SysYFParser (const SysYFParser&) = delete; + /// Non copyable. + SysYFParser& operator= (const SysYFParser&) = delete; +#endif + + /// Parse. An alias for parse (). + /// \returns 0 iff parsing succeeded. + int operator() (); + + /// Parse. + /// \returns 0 iff parsing succeeded. + virtual int parse (); + +#if YYDEBUG + /// The current debugging stream. + std::ostream& debug_stream () const YY_ATTRIBUTE_PURE; + /// Set the current debugging stream. + void set_debug_stream (std::ostream &); + + /// Type for debugging levels. + typedef int debug_level_type; + /// The current debugging level. + debug_level_type debug_level () const YY_ATTRIBUTE_PURE; + /// Set the current debugging level. + void set_debug_level (debug_level_type l); +#endif + + /// Report a syntax error. + /// \param loc where the syntax error is found. + /// \param msg a description of the syntax error. + virtual void error (const location_type& loc, const std::string& msg); + + /// Report a syntax error. + void error (const syntax_error& err); + + /// The user-facing name of the symbol whose (internal) number is + /// YYSYMBOL. No bounds checking. + static std::string symbol_name (symbol_kind_type yysymbol); + + // Implementation of make_symbol for each token kind. +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYEOF (location_type l) + { + return symbol_type (token::TOK_YYEOF, std::move (l)); + } +#else + static + symbol_type + make_YYEOF (const location_type& l) + { + return symbol_type (token::TOK_YYEOF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYerror (location_type l) + { + return symbol_type (token::TOK_YYerror, std::move (l)); + } +#else + static + symbol_type + make_YYerror (const location_type& l) + { + return symbol_type (token::TOK_YYerror, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_YYUNDEF (location_type l) + { + return symbol_type (token::TOK_YYUNDEF, std::move (l)); + } +#else + static + symbol_type + make_YYUNDEF (const location_type& l) + { + return symbol_type (token::TOK_YYUNDEF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_END (location_type l) + { + return symbol_type (token::TOK_END, std::move (l)); + } +#else + static + symbol_type + make_END (const location_type& l) + { + return symbol_type (token::TOK_END, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ERROR (location_type l) + { + return symbol_type (token::TOK_ERROR, std::move (l)); + } +#else + static + symbol_type + make_ERROR (const location_type& l) + { + return symbol_type (token::TOK_ERROR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_PLUS (location_type l) + { + return symbol_type (token::TOK_PLUS, std::move (l)); + } +#else + static + symbol_type + make_PLUS (const location_type& l) + { + return symbol_type (token::TOK_PLUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MINUS (location_type l) + { + return symbol_type (token::TOK_MINUS, std::move (l)); + } +#else + static + symbol_type + make_MINUS (const location_type& l) + { + return symbol_type (token::TOK_MINUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MULTIPLY (location_type l) + { + return symbol_type (token::TOK_MULTIPLY, std::move (l)); + } +#else + static + symbol_type + make_MULTIPLY (const location_type& l) + { + return symbol_type (token::TOK_MULTIPLY, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_DIVIDE (location_type l) + { + return symbol_type (token::TOK_DIVIDE, std::move (l)); + } +#else + static + symbol_type + make_DIVIDE (const location_type& l) + { + return symbol_type (token::TOK_DIVIDE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MODULO (location_type l) + { + return symbol_type (token::TOK_MODULO, std::move (l)); + } +#else + static + symbol_type + make_MODULO (const location_type& l) + { + return symbol_type (token::TOK_MODULO, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LTE (location_type l) + { + return symbol_type (token::TOK_LTE, std::move (l)); + } +#else + static + symbol_type + make_LTE (const location_type& l) + { + return symbol_type (token::TOK_LTE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_GT (location_type l) + { + return symbol_type (token::TOK_GT, std::move (l)); + } +#else + static + symbol_type + make_GT (const location_type& l) + { + return symbol_type (token::TOK_GT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_GTE (location_type l) + { + return symbol_type (token::TOK_GTE, std::move (l)); + } +#else + static + symbol_type + make_GTE (const location_type& l) + { + return symbol_type (token::TOK_GTE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_EQ (location_type l) + { + return symbol_type (token::TOK_EQ, std::move (l)); + } +#else + static + symbol_type + make_EQ (const location_type& l) + { + return symbol_type (token::TOK_EQ, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_NEQ (location_type l) + { + return symbol_type (token::TOK_NEQ, std::move (l)); + } +#else + static + symbol_type + make_NEQ (const location_type& l) + { + return symbol_type (token::TOK_NEQ, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ASSIGN (location_type l) + { + return symbol_type (token::TOK_ASSIGN, std::move (l)); + } +#else + static + symbol_type + make_ASSIGN (const location_type& l) + { + return symbol_type (token::TOK_ASSIGN, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_SEMICOLON (location_type l) + { + return symbol_type (token::TOK_SEMICOLON, std::move (l)); + } +#else + static + symbol_type + make_SEMICOLON (const location_type& l) + { + return symbol_type (token::TOK_SEMICOLON, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_COMMA (location_type l) + { + return symbol_type (token::TOK_COMMA, std::move (l)); + } +#else + static + symbol_type + make_COMMA (const location_type& l) + { + return symbol_type (token::TOK_COMMA, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LPARENTHESE (location_type l) + { + return symbol_type (token::TOK_LPARENTHESE, std::move (l)); + } +#else + static + symbol_type + make_LPARENTHESE (const location_type& l) + { + return symbol_type (token::TOK_LPARENTHESE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RPARENTHESE (location_type l) + { + return symbol_type (token::TOK_RPARENTHESE, std::move (l)); + } +#else + static + symbol_type + make_RPARENTHESE (const location_type& l) + { + return symbol_type (token::TOK_RPARENTHESE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LBRACKET (location_type l) + { + return symbol_type (token::TOK_LBRACKET, std::move (l)); + } +#else + static + symbol_type + make_LBRACKET (const location_type& l) + { + return symbol_type (token::TOK_LBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RBRACKET (location_type l) + { + return symbol_type (token::TOK_RBRACKET, std::move (l)); + } +#else + static + symbol_type + make_RBRACKET (const location_type& l) + { + return symbol_type (token::TOK_RBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LBRACE (location_type l) + { + return symbol_type (token::TOK_LBRACE, std::move (l)); + } +#else + static + symbol_type + make_LBRACE (const location_type& l) + { + return symbol_type (token::TOK_LBRACE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RBRACE (location_type l) + { + return symbol_type (token::TOK_RBRACE, std::move (l)); + } +#else + static + symbol_type + make_RBRACE (const location_type& l) + { + return symbol_type (token::TOK_RBRACE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_ELSE (location_type l) + { + return symbol_type (token::TOK_ELSE, std::move (l)); + } +#else + static + symbol_type + make_ELSE (const location_type& l) + { + return symbol_type (token::TOK_ELSE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_IF (location_type l) + { + return symbol_type (token::TOK_IF, std::move (l)); + } +#else + static + symbol_type + make_IF (const location_type& l) + { + return symbol_type (token::TOK_IF, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_INT (location_type l) + { + return symbol_type (token::TOK_INT, std::move (l)); + } +#else + static + symbol_type + make_INT (const location_type& l) + { + return symbol_type (token::TOK_INT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_RETURN (location_type l) + { + return symbol_type (token::TOK_RETURN, std::move (l)); + } +#else + static + symbol_type + make_RETURN (const location_type& l) + { + return symbol_type (token::TOK_RETURN, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_VOID (location_type l) + { + return symbol_type (token::TOK_VOID, std::move (l)); + } +#else + static + symbol_type + make_VOID (const location_type& l) + { + return symbol_type (token::TOK_VOID, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_WHILE (location_type l) + { + return symbol_type (token::TOK_WHILE, std::move (l)); + } +#else + static + symbol_type + make_WHILE (const location_type& l) + { + return symbol_type (token::TOK_WHILE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_IDENTIFIER (std::string v, location_type l) + { + return symbol_type (token::TOK_IDENTIFIER, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_IDENTIFIER (const std::string& v, const location_type& l) + { + return symbol_type (token::TOK_IDENTIFIER, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_FLOATCONST (float v, location_type l) + { + return symbol_type (token::TOK_FLOATCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_FLOATCONST (const float& v, const location_type& l) + { + return symbol_type (token::TOK_FLOATCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_INTCONST (int v, location_type l) + { + return symbol_type (token::TOK_INTCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_INTCONST (const int& v, const location_type& l) + { + return symbol_type (token::TOK_INTCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LETTER (location_type l) + { + return symbol_type (token::TOK_LETTER, std::move (l)); + } +#else + static + symbol_type + make_LETTER (const location_type& l) + { + return symbol_type (token::TOK_LETTER, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_EOL (location_type l) + { + return symbol_type (token::TOK_EOL, std::move (l)); + } +#else + static + symbol_type + make_EOL (const location_type& l) + { + return symbol_type (token::TOK_EOL, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_COMMENT (location_type l) + { + return symbol_type (token::TOK_COMMENT, std::move (l)); + } +#else + static + symbol_type + make_COMMENT (const location_type& l) + { + return symbol_type (token::TOK_COMMENT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_BLANK (location_type l) + { + return symbol_type (token::TOK_BLANK, std::move (l)); + } +#else + static + symbol_type + make_BLANK (const location_type& l) + { + return symbol_type (token::TOK_BLANK, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_CONST (location_type l) + { + return symbol_type (token::TOK_CONST, std::move (l)); + } +#else + static + symbol_type + make_CONST (const location_type& l) + { + return symbol_type (token::TOK_CONST, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_BREAK (location_type l) + { + return symbol_type (token::TOK_BREAK, std::move (l)); + } +#else + static + symbol_type + make_BREAK (const location_type& l) + { + return symbol_type (token::TOK_BREAK, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_CONTINUE (location_type l) + { + return symbol_type (token::TOK_CONTINUE, std::move (l)); + } +#else + static + symbol_type + make_CONTINUE (const location_type& l) + { + return symbol_type (token::TOK_CONTINUE, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_NOT (location_type l) + { + return symbol_type (token::TOK_NOT, std::move (l)); + } +#else + static + symbol_type + make_NOT (const location_type& l) + { + return symbol_type (token::TOK_NOT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_AND (location_type l) + { + return symbol_type (token::TOK_AND, std::move (l)); + } +#else + static + symbol_type + make_AND (const location_type& l) + { + return symbol_type (token::TOK_AND, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_OR (location_type l) + { + return symbol_type (token::TOK_OR, std::move (l)); + } +#else + static + symbol_type + make_OR (const location_type& l) + { + return symbol_type (token::TOK_OR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_MOD (location_type l) + { + return symbol_type (token::TOK_MOD, std::move (l)); + } +#else + static + symbol_type + make_MOD (const location_type& l) + { + return symbol_type (token::TOK_MOD, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_FLOAT (location_type l) + { + return symbol_type (token::TOK_FLOAT, std::move (l)); + } +#else + static + symbol_type + make_FLOAT (const location_type& l) + { + return symbol_type (token::TOK_FLOAT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LOGICAND (location_type l) + { + return symbol_type (token::TOK_LOGICAND, std::move (l)); + } +#else + static + symbol_type + make_LOGICAND (const location_type& l) + { + return symbol_type (token::TOK_LOGICAND, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LOGICOR (location_type l) + { + return symbol_type (token::TOK_LOGICOR, std::move (l)); + } +#else + static + symbol_type + make_LOGICOR (const location_type& l) + { + return symbol_type (token::TOK_LOGICOR, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LT (location_type l) + { + return symbol_type (token::TOK_LT, std::move (l)); + } +#else + static + symbol_type + make_LT (const location_type& l) + { + return symbol_type (token::TOK_LT, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_STRINGCONST (std::string v, location_type l) + { + return symbol_type (token::TOK_STRINGCONST, std::move (v), std::move (l)); + } +#else + static + symbol_type + make_STRINGCONST (const std::string& v, const location_type& l) + { + return symbol_type (token::TOK_STRINGCONST, v, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_LRBRACKET (location_type l) + { + return symbol_type (token::TOK_LRBRACKET, std::move (l)); + } +#else + static + symbol_type + make_LRBRACKET (const location_type& l) + { + return symbol_type (token::TOK_LRBRACKET, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UPLUS (location_type l) + { + return symbol_type (token::TOK_UPLUS, std::move (l)); + } +#else + static + symbol_type + make_UPLUS (const location_type& l) + { + return symbol_type (token::TOK_UPLUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UMINUS (location_type l) + { + return symbol_type (token::TOK_UMINUS, std::move (l)); + } +#else + static + symbol_type + make_UMINUS (const location_type& l) + { + return symbol_type (token::TOK_UMINUS, l); + } +#endif +#if 201103L <= YY_CPLUSPLUS + static + symbol_type + make_UNOT (location_type l) + { + return symbol_type (token::TOK_UNOT, std::move (l)); + } +#else + static + symbol_type + make_UNOT (const location_type& l) + { + return symbol_type (token::TOK_UNOT, l); + } +#endif + + + class context + { + public: + context (const SysYFParser& yyparser, const symbol_type& yyla); + const symbol_type& lookahead () const YY_NOEXCEPT { return yyla_; } + symbol_kind_type token () const YY_NOEXCEPT { return yyla_.kind (); } + const location_type& location () const YY_NOEXCEPT { return yyla_.location; } + + /// Put in YYARG at most YYARGN of the expected tokens, and return the + /// number of tokens stored in YYARG. If YYARG is null, return the + /// number of expected tokens (guaranteed to be less than YYNTOKENS). + int expected_tokens (symbol_kind_type yyarg[], int yyargn) const; + + private: + const SysYFParser& yyparser_; + const symbol_type& yyla_; + }; + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + SysYFParser (const SysYFParser&); + /// Non copyable. + SysYFParser& operator= (const SysYFParser&); +#endif + + + /// Stored state numbers (used for stacks). + typedef unsigned char state_type; + + /// The arguments of the error message. + int yy_syntax_error_arguments_ (const context& yyctx, + symbol_kind_type yyarg[], int yyargn) const; + + /// Generate an error message. + /// \param yyctx the context in which the error occurred. + virtual std::string yysyntax_error_ (const context& yyctx) const; + /// Compute post-reduction state. + /// \param yystate the current state + /// \param yysym the nonterminal to push on the stack + static state_type yy_lr_goto_state_ (state_type yystate, int yysym); + + /// Whether the given \c yypact_ value indicates a defaulted state. + /// \param yyvalue the value to check + static bool yy_pact_value_is_default_ (int yyvalue) YY_NOEXCEPT; + + /// Whether the given \c yytable_ value indicates a syntax error. + /// \param yyvalue the value to check + static bool yy_table_value_is_error_ (int yyvalue) YY_NOEXCEPT; + + static const signed char yypact_ninf_; + static const signed char yytable_ninf_; + + /// Convert a scanner token kind \a t to a symbol kind. + /// In theory \a t should be a token_kind_type, but character literals + /// are valid, yet not members of the token_kind_type enum. + static symbol_kind_type yytranslate_ (int t) YY_NOEXCEPT; + + /// Convert the symbol name \a n to a form suitable for a diagnostic. + static std::string yytnamerr_ (const char *yystr); + + /// For a symbol, its name in clear. + static const char* const yytname_[]; + + + // Tables. + // YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + // STATE-NUM. + static const short yypact_[]; + + // YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. + // Performed when YYTABLE does not specify something else to do. Zero + // means the default is an error. + static const signed char yydefact_[]; + + // YYPGOTO[NTERM-NUM]. + static const short yypgoto_[]; + + // YYDEFGOTO[NTERM-NUM]. + static const signed char yydefgoto_[]; + + // YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If + // positive, shift that token. If negative, reduce the rule whose + // number is the opposite. If YYTABLE_NINF, syntax error. + static const short yytable_[]; + + static const unsigned char yycheck_[]; + + // YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of + // state STATE-NUM. + static const signed char yystos_[]; + + // YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. + static const signed char yyr1_[]; + + // YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. + static const signed char yyr2_[]; + + +#if YYDEBUG + // YYRLINE[YYN] -- Source line where rule number YYN was defined. + static const short yyrline_[]; + /// Report on the debug stream that the rule \a r is going to be reduced. + virtual void yy_reduce_print_ (int r) const; + /// Print the state stack on the debug stream. + virtual void yy_stack_print_ () const; + + /// Debugging level. + int yydebug_; + /// Debug stream. + std::ostream* yycdebug_; + + /// \brief Display a symbol kind, value and location. + /// \param yyo The output stream. + /// \param yysym The symbol. + template + void yy_print_ (std::ostream& yyo, const basic_symbol& yysym) const; +#endif + + /// \brief Reclaim the memory associated to a symbol. + /// \param yymsg Why this token is reclaimed. + /// If null, print nothing. + /// \param yysym The symbol. + template + void yy_destroy_ (const char* yymsg, basic_symbol& yysym) const; + + private: + /// Type access provider for state based symbols. + struct by_state + { + /// Default constructor. + by_state () YY_NOEXCEPT; + + /// The symbol kind as needed by the constructor. + typedef state_type kind_type; + + /// Constructor. + by_state (kind_type s) YY_NOEXCEPT; + + /// Copy constructor. + by_state (const by_state& that) YY_NOEXCEPT; + + /// Record that this symbol is empty. + void clear () YY_NOEXCEPT; + + /// Steal the symbol kind from \a that. + void move (by_state& that); + + /// The symbol kind (corresponding to \a state). + /// \a symbol_kind::S_YYEMPTY when empty. + symbol_kind_type kind () const YY_NOEXCEPT; + + /// The state number used to denote an empty symbol. + /// We use the initial state, as it does not have a value. + enum { empty_state = 0 }; + + /// The state. + /// \a empty when empty. + state_type state; + }; + + /// "Internal" symbol: element of the stack. + struct stack_symbol_type : basic_symbol + { + /// Superclass. + typedef basic_symbol super_type; + /// Construct an empty symbol. + stack_symbol_type (); + /// Move or copy construction. + stack_symbol_type (YY_RVREF (stack_symbol_type) that); + /// Steal the contents from \a sym to build this. + stack_symbol_type (state_type s, YY_MOVE_REF (symbol_type) sym); +#if YY_CPLUSPLUS < 201103L + /// Assignment, needed by push_back by some old implementations. + /// Moves the contents of that. + stack_symbol_type& operator= (stack_symbol_type& that); + + /// Assignment, needed by push_back by other implementations. + /// Needed by some other old implementations. + stack_symbol_type& operator= (const stack_symbol_type& that); +#endif + }; + + /// A stack with random access from its top. + template > + class stack + { + public: + // Hide our reversed order. + typedef typename S::iterator iterator; + typedef typename S::const_iterator const_iterator; + typedef typename S::size_type size_type; + typedef typename std::ptrdiff_t index_type; + + stack (size_type n = 200) YY_NOEXCEPT + : seq_ (n) + {} + +#if 201103L <= YY_CPLUSPLUS + /// Non copyable. + stack (const stack&) = delete; + /// Non copyable. + stack& operator= (const stack&) = delete; +#endif + + /// Random access. + /// + /// Index 0 returns the topmost element. + const T& + operator[] (index_type i) const + { + return seq_[size_type (size () - 1 - i)]; + } + + /// Random access. + /// + /// Index 0 returns the topmost element. + T& + operator[] (index_type i) + { + return seq_[size_type (size () - 1 - i)]; + } + + /// Steal the contents of \a t. + /// + /// Close to move-semantics. + void + push (YY_MOVE_REF (T) t) + { + seq_.push_back (T ()); + operator[] (0).move (t); + } + + /// Pop elements from the stack. + void + pop (std::ptrdiff_t n = 1) YY_NOEXCEPT + { + for (; 0 < n; --n) + seq_.pop_back (); + } + + /// Pop all elements from the stack. + void + clear () YY_NOEXCEPT + { + seq_.clear (); + } + + /// Number of elements on the stack. + index_type + size () const YY_NOEXCEPT + { + return index_type (seq_.size ()); + } + + /// Iterator on top of the stack (going downwards). + const_iterator + begin () const YY_NOEXCEPT + { + return seq_.begin (); + } + + /// Bottom of the stack. + const_iterator + end () const YY_NOEXCEPT + { + return seq_.end (); + } + + /// Present a slice of the top of a stack. + class slice + { + public: + slice (const stack& stack, index_type range) YY_NOEXCEPT + : stack_ (stack) + , range_ (range) + {} + + const T& + operator[] (index_type i) const + { + return stack_[range_ - i]; + } + + private: + const stack& stack_; + index_type range_; + }; + + private: +#if YY_CPLUSPLUS < 201103L + /// Non copyable. + stack (const stack&); + /// Non copyable. + stack& operator= (const stack&); +#endif + /// The wrapped container. + S seq_; + }; + + + /// Stack type. + typedef stack stack_type; + + /// The stack. + stack_type yystack_; + + /// Push a new state on the stack. + /// \param m a debug message to display + /// if null, no trace is output. + /// \param sym the symbol + /// \warning the contents of \a s.value is stolen. + void yypush_ (const char* m, YY_MOVE_REF (stack_symbol_type) sym); + + /// Push a new look ahead token on the state on the stack. + /// \param m a debug message to display + /// if null, no trace is output. + /// \param s the state + /// \param sym the symbol (for its value and location). + /// \warning the contents of \a sym.value is stolen. + void yypush_ (const char* m, state_type s, YY_MOVE_REF (symbol_type) sym); + + /// Pop \a n symbols from the stack. + void yypop_ (int n = 1) YY_NOEXCEPT; + + /// Constants. + enum + { + yylast_ = 194, ///< Last index in yytable_. + yynnts_ = 35, ///< Number of nonterminal symbols. + yyfinal_ = 14 ///< Termination state number. + }; + + + // User arguments. + SysYFDriver& driver; + + }; + + inline + SysYFParser::symbol_kind_type + SysYFParser::yytranslate_ (int t) YY_NOEXCEPT + { + // YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to + // TOKEN-NUM as returned by yylex. + static + const signed char + translate_table[] = + { + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 2, 3, 50, 51, 52 + }; + // Last valid token kind. + const int code_max = 308; + + if (t <= 0) + return symbol_kind::S_YYEOF; + else if (t <= code_max) + return static_cast (translate_table[t]); + else + return symbol_kind::S_YYUNDEF; + } + + // basic_symbol. + template + SysYFParser::basic_symbol::basic_symbol (const basic_symbol& that) + : Base (that) + , value () + , location (that.location) + { + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.copy< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.copy< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.copy< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.copy< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.copy< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.copy< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.copy< SysYF::SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.copy< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.copy< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.copy< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + + } + + + + + template + SysYFParser::symbol_kind_type + SysYFParser::basic_symbol::type_get () const YY_NOEXCEPT + { + return this->kind (); + } + + + template + bool + SysYFParser::basic_symbol::empty () const YY_NOEXCEPT + { + return this->kind () == symbol_kind::S_YYEMPTY; + } + + template + void + SysYFParser::basic_symbol::move (basic_symbol& s) + { + super_type::move (s); + switch (this->kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SysYF::Ptr > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SysYF::PtrVec > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SysYF::PtrVec > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SysYF::PtrVec > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SysYF::PtrVec > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SysYF::PtrVec > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SysYF::SyntaxTree::Type > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (YY_MOVE (s.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (YY_MOVE (s.value)); + break; + + default: + break; + } + + location = YY_MOVE (s.location); + } + + // by_kind. + inline + SysYFParser::by_kind::by_kind () YY_NOEXCEPT + : kind_ (symbol_kind::S_YYEMPTY) + {} + +#if 201103L <= YY_CPLUSPLUS + inline + SysYFParser::by_kind::by_kind (by_kind&& that) YY_NOEXCEPT + : kind_ (that.kind_) + { + that.clear (); + } +#endif + + inline + SysYFParser::by_kind::by_kind (const by_kind& that) YY_NOEXCEPT + : kind_ (that.kind_) + {} + + inline + SysYFParser::by_kind::by_kind (token_kind_type t) YY_NOEXCEPT + : kind_ (yytranslate_ (t)) + {} + + + + inline + void + SysYFParser::by_kind::clear () YY_NOEXCEPT + { + kind_ = symbol_kind::S_YYEMPTY; + } + + inline + void + SysYFParser::by_kind::move (by_kind& that) + { + kind_ = that.kind_; + that.clear (); + } + + inline + SysYFParser::symbol_kind_type + SysYFParser::by_kind::kind () const YY_NOEXCEPT + { + return kind_; + } + + + inline + SysYFParser::symbol_kind_type + SysYFParser::by_kind::type_get () const YY_NOEXCEPT + { + return this->kind (); + } + + +} // yy +#line 2907 "./SysYFParser.h" + + + + +#endif // !YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_SYSYFPARSER_H_INCLUDED diff --git a/include/Frontend/location.hh b/include/Frontend/location.hh new file mode 100644 index 0000000..a4d88d2 --- /dev/null +++ b/include/Frontend/location.hh @@ -0,0 +1,304 @@ +// A Bison parser, made by GNU Bison 3.8.2. + +// Locations for Bison parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + +/** + ** \file ./location.hh + ** Define the yy::location class. + */ + +#ifndef YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_LOCATION_HH_INCLUDED +# define YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_LOCATION_HH_INCLUDED + +# include +# include + +# ifndef YY_NULLPTR +# if defined __cplusplus +# if 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# else +# define YY_NULLPTR ((void*)0) +# endif +# endif + +namespace yy { +#line 58 "./location.hh" + + /// A point in a source file. + class position + { + public: + /// Type for file name. + typedef const std::string filename_type; + /// Type for line and column numbers. + typedef int counter_type; + + /// Construct a position. + explicit position (filename_type* f = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + : filename (f) + , line (l) + , column (c) + {} + + + /// Initialization. + void initialize (filename_type* fn = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + { + filename = fn; + line = l; + column = c; + } + + /** \name Line and Column related manipulators + ** \{ */ + /// (line related) Advance to the COUNT next lines. + void lines (counter_type count = 1) + { + if (count) + { + column = 1; + line = add_ (line, count, 1); + } + } + + /// (column related) Advance to the COUNT next columns. + void columns (counter_type count = 1) + { + column = add_ (column, count, 1); + } + /** \} */ + + /// File name to which this position refers. + filename_type* filename; + /// Current line number. + counter_type line; + /// Current column number. + counter_type column; + + private: + /// Compute max (min, lhs+rhs). + static counter_type add_ (counter_type lhs, counter_type rhs, counter_type min) + { + return lhs + rhs < min ? min : lhs + rhs; + } + }; + + /// Add \a width columns, in place. + inline position& + operator+= (position& res, position::counter_type width) + { + res.columns (width); + return res; + } + + /// Add \a width columns. + inline position + operator+ (position res, position::counter_type width) + { + return res += width; + } + + /// Subtract \a width columns, in place. + inline position& + operator-= (position& res, position::counter_type width) + { + return res += -width; + } + + /// Subtract \a width columns. + inline position + operator- (position res, position::counter_type width) + { + return res -= width; + } + + /** \brief Intercept output stream redirection. + ** \param ostr the destination output stream + ** \param pos a reference to the position to redirect + */ + template + std::basic_ostream& + operator<< (std::basic_ostream& ostr, const position& pos) + { + if (pos.filename) + ostr << *pos.filename << ':'; + return ostr << pos.line << '.' << pos.column; + } + + /// Two points in a source file. + class location + { + public: + /// Type for file name. + typedef position::filename_type filename_type; + /// Type for line and column numbers. + typedef position::counter_type counter_type; + + /// Construct a location from \a b to \a e. + location (const position& b, const position& e) + : begin (b) + , end (e) + {} + + /// Construct a 0-width location in \a p. + explicit location (const position& p = position ()) + : begin (p) + , end (p) + {} + + /// Construct a 0-width location in \a f, \a l, \a c. + explicit location (filename_type* f, + counter_type l = 1, + counter_type c = 1) + : begin (f, l, c) + , end (f, l, c) + {} + + + /// Initialization. + void initialize (filename_type* f = YY_NULLPTR, + counter_type l = 1, + counter_type c = 1) + { + begin.initialize (f, l, c); + end = begin; + } + + /** \name Line and Column related manipulators + ** \{ */ + public: + /// Reset initial location to final location. + void step () + { + begin = end; + } + + /// Extend the current location to the COUNT next columns. + void columns (counter_type count = 1) + { + end += count; + } + + /// Extend the current location to the COUNT next lines. + void lines (counter_type count = 1) + { + end.lines (count); + } + /** \} */ + + + public: + /// Beginning of the located region. + position begin; + /// End of the located region. + position end; + }; + + /// Join two locations, in place. + inline location& + operator+= (location& res, const location& end) + { + res.end = end.end; + return res; + } + + /// Join two locations. + inline location + operator+ (location res, const location& end) + { + return res += end; + } + + /// Add \a width columns to the end position, in place. + inline location& + operator+= (location& res, location::counter_type width) + { + res.columns (width); + return res; + } + + /// Add \a width columns to the end position. + inline location + operator+ (location res, location::counter_type width) + { + return res += width; + } + + /// Subtract \a width columns to the end position, in place. + inline location& + operator-= (location& res, location::counter_type width) + { + return res += -width; + } + + /// Subtract \a width columns to the end position. + inline location + operator- (location res, location::counter_type width) + { + return res -= width; + } + + /** \brief Intercept output stream redirection. + ** \param ostr the destination output stream + ** \param loc a reference to the location to redirect + ** + ** Avoid duplicate information. + */ + template + std::basic_ostream& + operator<< (std::basic_ostream& ostr, const location& loc) + { + location::counter_type end_col + = 0 < loc.end.column ? loc.end.column - 1 : 0; + ostr << loc.begin; + if (loc.end.filename + && (!loc.begin.filename + || *loc.begin.filename != *loc.end.filename)) + ostr << '-' << loc.end.filename << ':' << loc.end.line << '.' << end_col; + else if (loc.begin.line < loc.end.line) + ostr << '-' << loc.end.line << '.' << end_col; + else if (loc.begin.column < end_col) + ostr << '-' << end_col; + return ostr; + } + +} // yy +#line 303 "./location.hh" + +#endif // !YY_YY_HOME_CJB_COMPILER_EDUCODER_EDUCODER_2021FALL_COMPILER_IR_LAB_SYSYF_TA_BUILD_LOCATION_HH_INCLUDED diff --git a/include/Frontend/position.hh b/include/Frontend/position.hh new file mode 100644 index 0000000..1bd8e26 --- /dev/null +++ b/include/Frontend/position.hh @@ -0,0 +1,11 @@ +// A Bison parser, made by GNU Bison 3.8.2. + +// Starting with Bison 3.2, this file is useless: the structure it +// used to define is now defined in "location.hh". +// +// To get rid of this file: +// 1. add '%require "3.2"' (or newer) to your grammar file +// 2. remove references to this file from your build system +// 3. if you used to include it, include "location.hh" instead. + +#include "location.hh" diff --git a/include/Frontend/stack.hh b/include/Frontend/stack.hh new file mode 100644 index 0000000..746965d --- /dev/null +++ b/include/Frontend/stack.hh @@ -0,0 +1,8 @@ +// A Bison parser, made by GNU Bison 3.8.2. + +// Starting with Bison 3.2, this file is useless: the structure it +// used to define is now defined with the parser itself. +// +// To get rid of this file: +// 1. add '%require "3.2"' (or newer) to your grammar file +// 2. remove references to this file from your build system. diff --git a/include/SysYFIR/BasicBlock.h b/include/SysYFIR/BasicBlock.h new file mode 100644 index 0000000..4f9f317 --- /dev/null +++ b/include/SysYFIR/BasicBlock.h @@ -0,0 +1,86 @@ +#ifndef _SYSYF_BASICBLOCK_H_ +#define _SYSYF_BASICBLOCK_H_ + +#include "Value.h" +#include "Instruction.h" +#include "Module.h" +#include "Function.h" + +#include +#include +#include + +namespace SysYF +{ +namespace IR +{ +class Function; +class Instruction; +class Module; + +class BasicBlock : public Value +{ +public: + static Ptr create(Ptr m, const std::string &name , + Ptr parent ) { + auto prefix = name.empty() ? "" : "label_"; + RET_AFTER_INIT(BasicBlock, m, prefix + name, parent); + } + + // return parent, or null if none. + Ptr get_parent() { return parent_; } + + Ptr get_module(); + + /****************api about cfg****************/ + + PtrList &get_pre_basic_blocks() { return pre_bbs_; } + PtrList &get_succ_basic_blocks() { return succ_bbs_; } + void add_pre_basic_block(Ptr bb) { pre_bbs_.push_back(bb); } + void add_succ_basic_block(Ptr bb) { succ_bbs_.push_back(bb); } + + void remove_pre_basic_block(Ptr bb) { pre_bbs_.remove(bb); } + void remove_succ_basic_block(Ptr bb) { succ_bbs_.remove(bb); } + + /****************api about cfg****************/ + + /// Returns the terminator instruction if the block is well formed or null + /// if the block is not well formed. + const Ptr get_terminator() const; + Ptr get_terminator() { + return const_pointer_cast( + static_pointer_cast(shared_from_this())->get_terminator()); + } + + void add_instruction(Ptr instr); + void add_instruction(PtrList::iterator instr_pos, Ptr instr); + void add_instr_begin(Ptr instr); + + PtrList::iterator find_instruction(Ptr instr); + + void delete_instr(Ptr instr); + + bool empty() { return instr_list_.empty(); } + + int get_num_of_instr() { return instr_list_.size(); } + PtrList &get_instructions() { return instr_list_; } + + void erase_from_parent(); + + virtual std::string print() override; + +private: + explicit BasicBlock(Ptr m, const std::string &name , + Ptr parent ); + void init(Ptr m, const std::string &name , + Ptr parent ); + PtrList pre_bbs_; + PtrList succ_bbs_; + PtrList instr_list_; + Ptr parent_; +}; + +} +} + +#endif // _SYSYF_BASICBLOCK_H_ \ No newline at end of file diff --git a/include/SysYFIR/Constant.h b/include/SysYFIR/Constant.h new file mode 100644 index 0000000..469ad16 --- /dev/null +++ b/include/SysYFIR/Constant.h @@ -0,0 +1,90 @@ +#ifndef _SYSYF_CONSTANT_H_ +#define _SYSYF_CONSTANT_H_ +#include "User.h" +#include "Value.h" +#include "Type.h" + +namespace SysYF +{ +namespace IR +{ +class Constant : public User +{ +protected: + explicit Constant(Ptr ty, const std::string &name = "", unsigned num_ops = 0) + : User(ty, name, num_ops) {} + void init(Ptr ty, const std::string &name = "", unsigned num_ops = 0) {} + // int value; +public: + ~Constant() = default; +}; + +class ConstantInt : public Constant +{ +private: + int value_; + explicit ConstantInt(Ptr ty, int val) + : Constant(ty,"",0),value_(val) {} + void init(Ptr ty, int val); + +public: + + static int get_value(Ptr const_val) { return const_val->value_; } + int get_value() { return value_; } + static Ptr create(int val, Ptr m); + static Ptr create(bool val, Ptr m); + virtual std::string print() override; +}; + +class ConstantFloat : public Constant +{ +private: + float value_; + explicit ConstantFloat(Ptr ty,float val) + : Constant(ty,"",0),value_(val) {} + void init(Ptr ty, float val); + +public: + + static float get_value(Ptr const_val) { return const_val->value_; } + float get_value() { return value_; } + static Ptr create(float val, Ptr m); + virtual std::string print() override; +}; + +class ConstantArray : public Constant +{ +private: + PtrVec const_array; + explicit ConstantArray(Ptr ty, const PtrVec &val); + void init(Ptr ty, const PtrVec &val); + +public: + + ~ConstantArray() = default; + + Ptr get_element_value(int index); + + unsigned get_size_of_array() { return const_array.size(); } + + static Ptr create(Ptr ty, const PtrVec &val); + + virtual std::string print() override; +}; + +class ConstantZero : public Constant +{ +private: + explicit ConstantZero(Ptr ty) + : Constant(ty,"",0) {} + void init(Ptr ty); + +public: + static Ptr create(Ptr ty, Ptr m); + virtual std::string print() override; +}; + +} +} + +#endif //_SYSYF_CONSTANT_H_ diff --git a/include/SysYFIR/Function.h b/include/SysYFIR/Function.h new file mode 100644 index 0000000..c9921d2 --- /dev/null +++ b/include/SysYFIR/Function.h @@ -0,0 +1,110 @@ +#ifndef _SYSYF_FUNCTION_H_ +#define _SYSYF_FUNCTION_H_ + +#include +#include +#include +#include +#ifdef DEBUG +#include +#endif +#include + +#include "User.h" +#include "Module.h" +#include "BasicBlock.h" +#include "Type.h" + +namespace SysYF +{ +namespace IR +{ +class Module; +class Argument; +class BasicBlock; +class Type; +class FunctionType; + +class Function : public Value +{ +public: + ~Function() = default; + static Ptr create(Ptr ty, const std::string &name, Ptr parent); + + Ptr get_function_type() const; + + Ptr get_return_type() const; + + void add_basic_block(Ptr bb); + + unsigned get_num_of_args() const; + unsigned get_num_basic_blocks() const; + + Ptr get_parent() const; + + PtrList::iterator arg_begin() { return arguments_.begin(); } + PtrList::iterator arg_end() { return arguments_.end(); } + + void remove(Ptr bb); + Ptr get_entry_block() { return *basic_blocks_.begin(); } + + PtrList &get_basic_blocks() { return basic_blocks_; } + PtrList &get_args() { return arguments_; } + std::vector> &get_vreg_set(){ return vreg_set_;} + + bool is_declaration() { return basic_blocks_.empty(); } + void set_unused_reg_num(std::set& set){unused_reg_num_ = set;} + std::set& get_unused_reg_num(){return unused_reg_num_;} + + void set_instr_name(); + std::string print(); + +private: + explicit Function(Ptr ty, const std::string &name, Ptr parent); + void init(Ptr ty, const std::string &name, Ptr parent); + void build_args(); + +private: + PtrList basic_blocks_; // basic blocks + PtrList arguments_; // arguments + std::vector> vreg_set_; + Ptr parent_; + std::set unused_reg_num_; + unsigned seq_cnt_; + // unsigned num_args_; + // We don't need this, all value inside function should be unnamed + // std::map> sym_table_; // Symbol table of args/instructions +}; + +// Argument of Function, does not contain actual value +class Argument : public Value +{ +public: + static Ptr create(Ptr ty, const std::string &name = "", Ptr f = nullptr, + unsigned arg_no = 0); + ~Argument() = default; + + inline const Ptr get_parent() const { return parent_; } + inline Ptr get_parent() { return parent_; } + + /// For example in "void foo(int a, float b)" a is 0 and b is 1. + unsigned get_arg_no() const { +#ifdef DEBUG + assert(parent_ && "can't get number of unparented arg"); +#endif + return arg_no_; + } + + virtual std::string print() override ; +private: + // Argument constructor. + explicit Argument(Ptr ty, const std::string &name = "", Ptr f = nullptr, + unsigned arg_no = 0) + : Value(ty, name), parent_(f), arg_no_(arg_no) {} + Ptr parent_; + unsigned arg_no_; // argument No. +}; + +} +} +#endif // _SYSYF_FUNCTION_H_ diff --git a/include/SysYFIR/GlobalVariable.h b/include/SysYFIR/GlobalVariable.h new file mode 100644 index 0000000..7d251e1 --- /dev/null +++ b/include/SysYFIR/GlobalVariable.h @@ -0,0 +1,31 @@ +#ifndef _SYSYF_GLOBALVARIABLE_H_ +#define _SYSYF_GLOBALVARIABLE_H_ + +#include "Module.h" +#include "User.h" +#include "Constant.h" + +namespace SysYF +{ +namespace IR +{ +class GlobalVariable : public User +{ +private: + bool is_const_ ; + Ptr init_val_; + explicit GlobalVariable(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val = nullptr); + void init(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val = nullptr); + +public: + static Ptr create(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val); + + Ptr get_init() { return init_val_; } + bool is_const() { return is_const_; } + std::string print(); +}; + +} +} + +#endif //_SYSYF_GLOBALVARIABLE_H_ diff --git a/include/SysYFIR/IRPrinter.h b/include/SysYFIR/IRPrinter.h new file mode 100644 index 0000000..e5cae71 --- /dev/null +++ b/include/SysYFIR/IRPrinter.h @@ -0,0 +1,25 @@ +#ifndef _SYSYF_IPRINTER_H_ +#define _SYSYF_IPRINTER_H_ + +#include "Value.h" +#include "Module.h" +#include "Function.h" +#include "GlobalVariable.h" +#include "Constant.h" +#include "BasicBlock.h" +#include "Instruction.h" +#include "User.h" +#include "Type.h" + +namespace SysYF +{ +namespace IR +{ +std::string print_as_op(Ptr v, bool print_ty ); +std::string print_cmp_type(CmpInst::CmpOp op); +std::string print_fcmp_type(FCmpInst::CmpOp op); + +} +} + +#endif diff --git a/include/SysYFIR/IRStmtBuilder.h b/include/SysYFIR/IRStmtBuilder.h new file mode 100644 index 0000000..10b1d8c --- /dev/null +++ b/include/SysYFIR/IRStmtBuilder.h @@ -0,0 +1,84 @@ +#ifndef _SYSYF_IRSTMTBUILDER_H_ +#define _SYSYF_IRSTMTBUILDER_H_ + +#include "BasicBlock.h" +#include "Instruction.h" +#include "Value.h" + +namespace SysYF +{ +namespace IR +{ +class IRStmtBuilder { +private: + Ptr BB_; + Ptr m_; + explicit IRStmtBuilder(Ptr bb, Ptr m) : BB_(bb), m_(m) {}; + void init(Ptr bb, Ptr m) {} +public: + static Ptr create(Ptr bb, Ptr m) { RET_AFTER_INIT(IRStmtBuilder, bb, m); } + ~IRStmtBuilder() = default; + Ptr get_module(){return m_;} + Ptr get_insert_block() { return this->BB_; } + void set_insert_point(Ptr bb) { this->BB_ = bb; } //在某个基本块中插入指令 + Ptr create_iadd( Ptr lhs, Ptr rhs){ return BinaryInst::create_add( lhs, rhs, this->BB_, m_);} //创建加法指令(以及其他算术指令) + Ptr create_isub( Ptr lhs, Ptr rhs){ return BinaryInst::create_sub( lhs, rhs, this->BB_, m_);} + Ptr create_imul( Ptr lhs, Ptr rhs){ return BinaryInst::create_mul( lhs, rhs, this->BB_, m_);} + Ptr create_isdiv( Ptr lhs, Ptr rhs){ return BinaryInst::create_sdiv( lhs, rhs, this->BB_, m_);} + Ptr create_isrem( Ptr lhs, Ptr rhs){ return BinaryInst::create_srem( lhs, rhs, this->BB_, m_);} + + Ptr create_icmp_eq( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::EQ, lhs, rhs, this->BB_, m_); } + Ptr create_icmp_ne( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::NE, lhs, rhs, this->BB_, m_); } + Ptr create_icmp_gt( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::GT, lhs, rhs, this->BB_, m_); } + Ptr create_icmp_ge( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::GE, lhs, rhs, this->BB_, m_); } + Ptr create_icmp_lt( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::LT, lhs, rhs, this->BB_, m_); } + Ptr create_icmp_le( Ptr lhs, Ptr rhs){ return CmpInst::create_cmp(CmpInst::LE, lhs, rhs, this->BB_, m_); } + + Ptr create_fadd( Ptr lhs, Ptr rhs){ return BinaryInst::create_fadd( lhs, rhs, this->BB_, m_);} + Ptr create_fsub( Ptr lhs, Ptr rhs){ return BinaryInst::create_fsub( lhs, rhs, this->BB_, m_);} + Ptr create_fmul( Ptr lhs, Ptr rhs){ return BinaryInst::create_fmul( lhs, rhs, this->BB_, m_);} + Ptr create_fdiv( Ptr lhs, Ptr rhs){ return BinaryInst::create_fdiv( lhs, rhs, this->BB_, m_);} + + Ptr create_fcmp_eq( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::EQ, lhs, rhs, this->BB_, m_); } + Ptr create_fcmp_ne( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::NE, lhs, rhs, this->BB_, m_); } + Ptr create_fcmp_gt( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::GT, lhs, rhs, this->BB_, m_); } + Ptr create_fcmp_ge( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::GE, lhs, rhs, this->BB_, m_); } + Ptr create_fcmp_lt( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::LT, lhs, rhs, this->BB_, m_); } + Ptr create_fcmp_le( Ptr lhs, Ptr rhs){ return FCmpInst::create_fcmp(FCmpInst::LE, lhs, rhs, this->BB_, m_); } + + Ptr create_call(Ptr func, PtrVec args) + { +#ifdef DEBUG + assert( dynamic_pointer_cast(func) && "func must be Ptr type"); +#endif + return CallInst::create(static_pointer_cast(func) ,args, this->BB_); + } + + Ptr create_br(Ptr if_true){ return BranchInst::create_br(if_true, this->BB_); } + Ptr create_cond_br(Ptr cond, Ptr if_true, Ptr if_false){ return BranchInst::create_cond_br(cond, if_true, if_false,this->BB_); } + + Ptr create_ret(Ptr val) { return ReturnInst::create_ret(val,this->BB_); } + Ptr create_void_ret() { return ReturnInst::create_void_ret(this->BB_); } + + Ptr create_gep(Ptr ptr, PtrVec idxs) { return GetElementPtrInst::create_gep(ptr, idxs, this->BB_); } + + Ptr create_store(Ptr val, Ptr ptr) { return StoreInst::create_store(val, ptr, this->BB_ ); } + Ptr create_load(Ptr ty, Ptr ptr) { return LoadInst::create_load(ty, ptr, this->BB_); } + Ptr create_load(Ptr ptr) + { +#ifdef DEBUG + assert( ptr->get_type()->is_pointer_type() && "ptr must be pointer type" ); +#endif + return LoadInst::create_load(ptr->get_type()->get_pointer_element_type(), ptr, this->BB_); + } + + Ptr create_alloca(Ptr ty) { return AllocaInst::create_alloca(ty, this->BB_); } + Ptr create_zext(Ptr val, Ptr ty) { return ZextInst::create_zext(val, ty, this->BB_); } + Ptr create_fptosi(Ptr val, Ptr ty) { return FpToSiInst::create_fptosi(val, ty, this->BB_); } + Ptr create_sitofp(Ptr val, Ptr ty) { return SiToFpInst::create_sitofp(val, ty, this->BB_); } +}; + +} +} + +#endif // _SYSYF_IRSTMTBUILDER_H_ diff --git a/include/SysYFIR/Instruction.h b/include/SysYFIR/Instruction.h new file mode 100644 index 0000000..9b4a420 --- /dev/null +++ b/include/SysYFIR/Instruction.h @@ -0,0 +1,435 @@ +#ifndef _SYSYF_INSTRUCTION_H_ +#define _SYSYF_INSTRUCTION_H_ + +#include "User.h" +#include "Type.h" +#include "Constant.h" +#include "BasicBlock.h" + +namespace SysYF +{ +namespace IR +{ +class BasicBlock; +class Function; +class Instruction; + +class Instruction : public User +{ +public: + enum OpID + { + // Terminator Instructions + ret, + br, + // Standard binary operators + add, + sub, + mul, + sdiv, + srem, + // Float binaru opeartors + fadd, + fsub, + fmul, + fdiv, + // Memory operators + alloca, + load, + store, + // Other operators + cmp, + fcmp, + phi, + call, + getelementptr, + // Zero extend + zext, + // type cast bewteen float and singed integer + fptosi, + sitofp, + }; + inline const Ptr get_parent() const { return parent_; } + inline Ptr get_parent() { return parent_; } + void set_parent(Ptr parent) { this->parent_ = parent; } + // Return the function this instruction belongs to. + Ptr get_function(); + Ptr get_module(); + + OpID get_instr_type() { return op_id_; } + std::string get_instr_op_name() { + switch (op_id_) + { + case ret: return "ret"; break; + case br: return "br"; break; + case add: return "add"; break; + case sub: return "sub"; break; + case mul: return "mul"; break; + case sdiv: return "sdiv"; break; + case srem: return "srem"; break; + case fadd: return "fadd"; break; + case fsub: return "fsub"; break; + case fmul: return "fmul"; break; + case fdiv: return "fdiv"; break; + case alloca: return "alloca"; break; + case load: return "load"; break; + case store: return "store"; break; + case cmp: return "cmp"; break; + case fcmp: return "fcmp"; break; + case phi: return "phi"; break; + case call: return "call"; break; + case getelementptr: return "getelementptr"; break; + case zext: return "zext"; break; + case fptosi: return "fptosi"; break; + case sitofp: return "sitofp"; break; + + default: return ""; break; + } + } + + + + bool is_void() { return ((op_id_ == ret) || (op_id_ == br) || (op_id_ == store) || (op_id_ == call && this->get_type()->is_void_type())); } + + bool is_phi() { return op_id_ == phi; } + bool is_store() { return op_id_ == store; } + bool is_alloca() { return op_id_ == alloca; } + bool is_ret() { return op_id_ == ret; } + bool is_load() { return op_id_ == load; } + bool is_br() { return op_id_ == br; } + + bool is_add() { return op_id_ == add; } + bool is_sub() { return op_id_ == sub; } + bool is_mul() { return op_id_ == mul; } + bool is_div() { return op_id_ == sdiv; } + bool is_rem() { return op_id_ == srem; } + + bool is_fadd() { return op_id_ == fadd; } + bool is_fsub() { return op_id_ == fsub; } + bool is_fmul() { return op_id_ == fmul; } + bool is_fdiv() { return op_id_ == fdiv; } + + bool is_cmp() { return op_id_ == cmp; } + bool is_fcmp() { return op_id_ == fcmp; } + + bool is_call() { return op_id_ == call; } + bool is_gep() { return op_id_ == getelementptr; } + bool is_zext() { return op_id_ == zext; } + bool is_fptosi() { return op_id_ == fptosi; } + bool is_sitofp() { return op_id_ == sitofp; } + + bool isBinary() + { + return (is_add() || is_sub() || is_mul() || is_div() || is_rem() || + is_fadd() || is_fsub() || is_fmul() || is_fdiv()) && + (get_num_operand() == 2); + } + + bool isTerminator() { return is_br() || is_ret(); } + + void set_id(int id){id_ = id;} + int get_id() const{return id_;} + +private: + OpID op_id_; + int id_; + unsigned num_ops_; + Ptr parent_; + // must be called after Instruction() in any derived class + void insert_to_bb(); + +protected: + // create instruction, but not insert to bb (insert to bb in method create in the derived class) + // ty here is result type + explicit Instruction(Ptr ty, OpID id, unsigned num_ops, Ptr parent = nullptr); + void init(Ptr ty, OpID id, unsigned num_ops, Ptr parent = nullptr); +}; + +class BinaryInst : public Instruction +{ +private: + explicit BinaryInst(Ptr ty, OpID id, Ptr v1, Ptr v2, + Ptr bb); + +public: + static Ptr create_add(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_sub(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_mul(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_sdiv(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_srem(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_fadd(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_fsub(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_fmul(Ptr v1, Ptr v2, Ptr bb, Ptr m); + static Ptr create_fdiv(Ptr v1, Ptr v2, Ptr bb, Ptr m); + + virtual std::string print() override; + +private: + void init(Ptr ty, OpID id, Ptr v1, Ptr v2, Ptr bb); + void assertValid() {} +}; + +class CmpInst : public Instruction +{ +public: + enum CmpOp + { + EQ, // == + NE, // != + GT, // > + GE, // >= + LT, // < + LE // <= + }; + +private: + explicit CmpInst(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb); + +public: + static Ptr create_cmp(CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb, Ptr m); + + CmpOp get_cmp_op() { return cmp_op_; } + + virtual std::string print() override; + +private: + CmpOp cmp_op_; + void init(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, Ptr bb); + void assertValid() {} +}; + +class FCmpInst : public Instruction +{ +public: + enum CmpOp + { + EQ, // == + NE, // != + GT, // > + GE, // >= + LT, // < + LE // <= + }; + +private: + explicit FCmpInst(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb); + void init(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, Ptr bb); + +public: + static Ptr create_fcmp(CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb, Ptr m); + + CmpOp get_cmp_op() { return cmp_op_; } + + virtual std::string print() override; + +private: + CmpOp cmp_op_; + + void assertValid() {} +}; + +class CallInst : public Instruction +{ +private: + explicit CallInst(Ptr func, PtrVec args, Ptr bb); + void init(Ptr func, PtrVec args, Ptr bb); + explicit CallInst(Ptr ret_ty, PtrVec args, Ptr bb); + void init(Ptr ret_ty, PtrVec args, Ptr bb); + +public: + static Ptr create(Ptr func, PtrVec args, Ptr bb); + Ptr get_function_type() const; + + virtual std::string print() override; + +}; + +class BranchInst : public Instruction +{ +private: + explicit BranchInst(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb); + void init(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb); + explicit BranchInst(Ptr cond, Ptr bb); + void init(Ptr cond, Ptr bb); + explicit BranchInst(Ptr if_true, Ptr bb); + void init(Ptr if_true, Ptr bb); + explicit BranchInst(Ptr bb); + void init(Ptr bb); + +public: + static Ptr create_cond_br(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb); + static Ptr create_br(Ptr if_true, Ptr bb); + + bool is_cond_br() const; + + virtual std::string print() override; + +}; + +class ReturnInst : public Instruction +{ +private: + explicit ReturnInst(Ptr val, Ptr bb); + void init(Ptr val, Ptr bb); + explicit ReturnInst(Ptr bb); + void init(Ptr bb); + +public: + static Ptr create_ret(Ptr val, Ptr bb); + static Ptr create_void_ret(Ptr bb); + bool is_void_ret() const; + + virtual std::string print() override; + +}; + +class GetElementPtrInst : public Instruction +{ +private: + explicit GetElementPtrInst(Ptr ptr, PtrVec idxs, Ptr bb); + void init(Ptr ptr, PtrVec idxs, Ptr bb); + +public: + static Ptr get_element_type(Ptr ptr, PtrVec idxs); + static Ptr create_gep(Ptr ptr, PtrVec idxs, Ptr bb); + Ptr get_element_type() const; + + virtual std::string print() override; + +private: + Ptr element_ty_; +}; + +class StoreInst : public Instruction +{ +private: + explicit StoreInst(Ptr val, Ptr ptr, Ptr bb); + void init(Ptr val, Ptr ptr, Ptr bb); + +public: + static Ptr create_store(Ptr val, Ptr ptr, Ptr bb); + + Ptr get_rval() { return this->get_operand(0); } + Ptr get_lval() { return this->get_operand(1); } + + virtual std::string print() override; + +}; + +class LoadInst : public Instruction +{ +private: + explicit LoadInst(Ptr ty, Ptr ptr, Ptr bb); + void init(Ptr ty, Ptr ptr, Ptr bb); + +public: + static Ptr create_load(Ptr ty, Ptr ptr, Ptr bb); + Ptr get_lval() { return this->get_operand(0); } + + Ptr get_load_type() const; + + virtual std::string print() override; + +}; + +class AllocaInst : public Instruction +{ +private: + explicit AllocaInst(Ptr ty, Ptr bb); + void init(Ptr ty, Ptr bb); + +public: + static Ptr create_alloca(Ptr ty, Ptr bb); + + Ptr get_alloca_type() const; + + virtual std::string print() override; + +private: + Ptr alloca_ty_; +}; + +class ZextInst : public Instruction +{ +private: + explicit ZextInst(OpID op, Ptr val, Ptr ty, Ptr bb); + void init(OpID op, Ptr val, Ptr ty, Ptr bb); + +public: + static Ptr create_zext(Ptr val, Ptr ty, Ptr bb); + + Ptr get_dest_type() const; + + virtual std::string print() override; + +private: + Ptr dest_ty_; +}; + +class FpToSiInst : public Instruction +{ +private: + explicit FpToSiInst(OpID op, Ptr val, Ptr ty, Ptr bb); + void init(OpID op, Ptr val, Ptr ty, Ptr bb); + +public: + static Ptr create_fptosi(Ptr val, Ptr ty, Ptr bb); + + Ptr get_dest_type() const; + + virtual std::string print() override; + +private: + Ptr dest_ty_; +}; + +class SiToFpInst : public Instruction +{ +private: + explicit SiToFpInst(OpID op, Ptr val, Ptr ty, Ptr bb); + void init(OpID op, Ptr val, Ptr ty, Ptr bb); + +public: + static Ptr create_sitofp(Ptr val, Ptr ty, Ptr bb); + + Ptr get_dest_type() const; + + virtual std::string print() override; + +private: + Ptr dest_ty_; +}; + +class PhiInst : public Instruction +{ +private: + explicit PhiInst(OpID op, PtrVec vals, PtrVec val_bbs, Ptr ty, Ptr bb); + void init(OpID op, PtrVec vals, PtrVec val_bbs, Ptr ty, Ptr bb); + +public: + static Ptr create_phi(Ptr ty, Ptr bb); + Ptr get_lval() { return l_val_; } + void set_lval(Ptr l_val) { l_val_ = l_val; } + void add_phi_pair_operand(Ptr val, Ptr pre_bb) + { + this->add_operand(val); + this->add_operand(pre_bb); + } + virtual std::string print() override; + +private: + Ptr l_val_; + +}; + +} +} + +#endif // _SYSYF_INSTRUCTION_H_ diff --git a/include/SysYFIR/Module.h b/include/SysYFIR/Module.h new file mode 100644 index 0000000..831b29c --- /dev/null +++ b/include/SysYFIR/Module.h @@ -0,0 +1,73 @@ +#ifndef _SYSYF_MODULE_H_ +#define _SYSYF_MODULE_H_ + +#include +#include +#include + +#include "internal_types.h" +#include "internal_macros.h" +#include "Type.h" +#include "GlobalVariable.h" +#include "Value.h" +#include "Function.h" + +namespace SysYF +{ +namespace IR +{ +class GlobalVariable; +class Module; + +class Module : public std::enable_shared_from_this +{ +public: + static Ptr create(std::string name); + ~Module() = default; + + Ptr get_void_type(); + Ptr get_label_type(); + Ptr get_int1_type(); + Ptr get_int32_type(); + Ptr get_float_type(); + Ptr get_int32_ptr_type(); + Ptr get_float_ptr_type(); + + Ptr get_pointer_type(Ptr contained); + Ptr get_array_type(Ptr contained, unsigned num_elements); + + void add_function(Ptr f); + PtrList &get_functions(); + void add_global_variable(Ptr g); + PtrList &get_global_variable(); + std::string get_instr_op_name( Instruction::OpID instr ) { return instr_id2string_[instr]; } + void set_print_name(); + void set_file_name(std::string name){source_file_name_ = name;} + std::string get_file_name(){return source_file_name_;} + virtual std::string print(); +private: + explicit Module(std::string name); + void init(std::string name); + PtrList global_list_; // The Global Variables in the module + PtrList function_list_; // The Functions in the module + std::map> value_sym_; // Symbol table for values + std::map instr_id2string_; // Instruction from opid to string + + std::string module_name_; // Human readable identifier for the module + std::string source_file_name_; // Original source file name for module, for test and debug + +private: + Ptr int1_ty_; + Ptr int32_ty_; + Ptr float32_ty_; + Ptr label_ty_; + Ptr void_ty_; + + std::map , Ptr> pointer_map_; + std::map ,int>, Ptr > array_map_; +}; + +} +} + +#endif // _SYSYF_MODULE_H_ \ No newline at end of file diff --git a/include/SysYFIR/Type.h b/include/SysYFIR/Type.h new file mode 100644 index 0000000..59b7e3f --- /dev/null +++ b/include/SysYFIR/Type.h @@ -0,0 +1,162 @@ +#ifndef _SYSYF_TYPE_H_ +#define _SYSYF_TYPE_H_ + +#include +#include + +#include "internal_types.h" + +namespace SysYF +{ +namespace IR +{ +class Module; +class IntegerType; +class FloatType; +class FunctionType; +class ArrayType; +class PointerType; +class Type; + +class Type : public std::enable_shared_from_this +{ +public: + enum TypeID { + VoidTyID, // Void + LabelTyID, // Labels, e.g., BasicBlock + IntegerTyID, // Integers, include 32 bits and 1 bit + FloatTyID, // Floats, only 32 bits + FunctionTyID, // Functions + ArrayTyID, // Arrays + PointerTyID, // Pointer + }; + + static Ptr create(TypeID tid, Ptr m); + + ~Type() = default; + + TypeID get_type_id() const { return tid_; } + + bool is_void_type() const { return get_type_id() == VoidTyID; } + + bool is_label_type() const { return get_type_id() == LabelTyID; } + + bool is_integer_type() const { return get_type_id() == IntegerTyID; } + + bool is_float_type() const { return get_type_id() == FloatTyID; } + + bool is_function_type() const { return get_type_id() == FunctionTyID; } + + bool is_array_type() const { return get_type_id() == ArrayTyID; } + + bool is_pointer_type() const { return get_type_id() == PointerTyID; } + + static bool is_eq_type(Ptr ty1, Ptr ty2); + + static Ptr get_void_type(Ptr m); + + static Ptr get_label_type(Ptr m); + + static Ptr get_int1_type(Ptr m); + + static Ptr get_int32_type(Ptr m); + + static Ptr get_float_type(Ptr m); + + static Ptr get_int32_ptr_type(Ptr m); + + static Ptr get_float_ptr_type(Ptr m); + + static Ptr get_pointer_type(Ptr contained); + + static Ptr get_array_type(Ptr contained, unsigned num_elements); + + Ptr get_pointer_element_type(); + + Ptr get_array_element_type(); + + int get_size(); + + Ptr get_module(); + + std::string print(); + +protected: + explicit Type(TypeID tid, Ptr m); + void init(TypeID tid, Ptr m) {} + +private: + TypeID tid_; + Ptr m_; +}; + +class IntegerType : public Type { +public: + static Ptr create(unsigned num_bits, Ptr m ); + + unsigned get_num_bits(); +private: + explicit IntegerType(unsigned num_bits ,Ptr m); + void init(unsigned num_bits ,Ptr m) { Type::init(IntegerTyID, m); } + unsigned num_bits_; +}; + +class FloatType : public Type { +public: + static Ptr create(Ptr m); +private: + explicit FloatType(Ptr m); + void init(Ptr m) { Type::init(FloatTyID, m); } +}; + +class FunctionType : public Type { +public: + static Ptr create(Ptr result, PtrVec params); + static bool is_valid_return_type(Ptr ty); + static bool is_valid_argument_type(Ptr ty); + + unsigned get_num_of_args() const; + + Ptr get_param_type(unsigned i) const; + PtrVec::iterator param_begin() { return args_.begin(); } + PtrVec::iterator param_end() { return args_.end(); } + Ptr get_return_type() const; +private: + explicit FunctionType(Ptr result, PtrVec params); + void init(Ptr result, PtrVec params) { Type::init(FunctionTyID, nullptr); } + Ptr result_; + PtrVec args_; +}; + +class ArrayType : public Type { +public: + static bool is_valid_element_type(Ptr ty); + + static Ptr get(Ptr contained, unsigned num_elements); + static Ptr create(Ptr contained, unsigned num_elements); + + Ptr get_element_type() const { return contained_; } + unsigned get_num_of_elements() const { return num_elements_; } + +private: + explicit ArrayType(Ptr contained, unsigned num_elements); + void init(Ptr contained, unsigned num_elements) { Type::init(ArrayTyID, nullptr); } + Ptr contained_; // The element type of the array. + unsigned num_elements_; // Number of elements in the array. +}; + +class PointerType : public Type { +public: + Ptr get_element_type() const { return contained_; } + static Ptr get(Ptr contained); + static Ptr create(Ptr contained); + +private: + explicit PointerType(Ptr contained); + void init(Ptr contained) { Type::init(PointerTyID, nullptr); } + Ptr contained_; // The element type of the ptr. +}; + +} +} +#endif // _SYSYF_TYPE_H_ \ No newline at end of file diff --git a/include/SysYFIR/User.h b/include/SysYFIR/User.h new file mode 100644 index 0000000..88c003e --- /dev/null +++ b/include/SysYFIR/User.h @@ -0,0 +1,41 @@ +#ifndef _SYSYF_USER_H_ +#define _SYSYF_USER_H_ + +#include "Value.h" +#include +// #include + +namespace SysYF +{ +namespace IR +{ +class User : public Value +{ +public: + ~User() = default; + + PtrVec& get_operands(); + + // start from 0 + Ptr get_operand(unsigned i) const; + + // start from 0 + void set_operand(unsigned i, Ptr v); + void add_operand(Ptr v); + + unsigned get_num_operand() const; + + void remove_use_of_ops(); + void remove_operands(int index1,int index2); + +protected: + explicit User(Ptr ty, const std::string &name = "", unsigned num_ops = 0); + +private: + PtrVec operands_; // operands of this value + unsigned num_ops_; +}; + +} +} +#endif // _SYSYF_USER_H_ diff --git a/include/SysYFIR/Value.h b/include/SysYFIR/Value.h new file mode 100644 index 0000000..736c344 --- /dev/null +++ b/include/SysYFIR/Value.h @@ -0,0 +1,63 @@ +#ifndef _SYSYF_VALUE_H_ +#define _SYSYF_VALUE_H_ + +#include +#include +#include +#include + +#include "internal_types.h" + +namespace SysYF +{ +namespace IR +{ + +class Type; +class Value; + +struct Use +{ + Ptr val_; + unsigned arg_no_; // the no. of operand, e.g., func(a, b), a is 0, b is 1 + Use(Ptr val, unsigned no) : val_(val), arg_no_(no) {} +}; + +class Value : public std::enable_shared_from_this +{ +public: + ~Value() = default; + + Ptr get_type() const { return type_; } + + std::list &get_use_list() { return use_list_; } + + void add_use(Ptr val, unsigned arg_no = 0); + + bool set_name(std::string name) { + if (name_ == "") + { + name_=name; + return true; + } + return false; + } + std::string get_name() const; + + void replace_all_use_with(Ptr new_val); + void remove_use(Ptr val); + + virtual std::string print() = 0; + +protected: + explicit Value(Ptr ty, const std::string &name = ""); + +private: + Ptr type_; + std::list use_list_; // who use this value + std::string name_; // should we put name field here ? +}; + +} +} +#endif // _SYSYF_VALUE_H_ diff --git a/include/SysYFIRBuilder/IRBuilder.h b/include/SysYFIRBuilder/IRBuilder.h new file mode 100644 index 0000000..bb59091 --- /dev/null +++ b/include/SysYFIRBuilder/IRBuilder.h @@ -0,0 +1,226 @@ +#ifndef _SYSYF_IR_BUILDER_H_ +#define _SYSYF_IR_BUILDER_H_ +#include "BasicBlock.h" +#include "Constant.h" +#include "Function.h" +#include "IRStmtBuilder.h" +#include "Module.h" +#include "Type.h" +#include +#include "SyntaxTree.h" + +namespace SysYF +{ +namespace IR +{ +class Scope { +public: + // enter a new scope + void enter() { + name2var.push_back({}); + name2func.push_back({}); + } + + // exit a scope + void exit() { + name2var.pop_back(); + name2func.pop_back(); + } + + bool in_global() { + return name2var.size() == 1; + } + + // push a name to scope + // return true if successful + // return false if this name already exits + // but func name could be same with variable name + bool push(std::string name, Ptr val) { + bool result; + if (dynamic_pointer_cast(val)){ + result = (name2func[name2func.size() - 1].insert({name, val})).second; + } + else{ + result = (name2var[name2var.size() - 1].insert({name, val})).second; + } + return result; + } + + Ptr find(std::string name, bool isfunc) { + if (isfunc){ + for (auto s = name2func.rbegin(); s!= name2func.rend();s++) { + auto iter = s->find(name); + if (iter != s->end()) { + return iter->second; + } + } + } + else{ + for (auto s = name2var.rbegin(); s!= name2var.rend();s++) { + auto iter = s->find(name); + if (iter != s->end()) { + return iter->second; + } + } + } + return nullptr; + } + + +private: + std::vector >> name2var; + std::vector >> name2func; +}; + +class IRBuilder: public SyntaxTree::Visitor +{ +private: + virtual void visit(SyntaxTree::InitVal &) override final; + virtual void visit(SyntaxTree::Assembly &) override final; + virtual void visit(SyntaxTree::FuncDef &) override final; + virtual void visit(SyntaxTree::VarDef &) override final; + virtual void visit(SyntaxTree::AssignStmt &) override final; + virtual void visit(SyntaxTree::ReturnStmt &) override final; + virtual void visit(SyntaxTree::BlockStmt &) override final; + virtual void visit(SyntaxTree::EmptyStmt &) override final; + virtual void visit(SyntaxTree::ExprStmt &) override final; + virtual void visit(SyntaxTree::UnaryCondExpr &) override final; + virtual void visit(SyntaxTree::BinaryCondExpr &) override final; + virtual void visit(SyntaxTree::BinaryExpr &) override final; + virtual void visit(SyntaxTree::UnaryExpr &) override final; + virtual void visit(SyntaxTree::LVal &) override final; + virtual void visit(SyntaxTree::Literal &) override final; + virtual void visit(SyntaxTree::FuncCallStmt &) override final; + virtual void visit(SyntaxTree::FuncParam &) override final; + virtual void visit(SyntaxTree::FuncFParamList &) override final; + virtual void visit(SyntaxTree::IfStmt &) override final; + virtual void visit(SyntaxTree::WhileStmt &) override final; + virtual void visit(SyntaxTree::BreakStmt &) override final; + virtual void visit(SyntaxTree::ContinueStmt &) override final; + + Ptr builder; + Scope scope; + Ptr module; + + IRBuilder() { + module = Module::create("SysYF code"); + builder = IRStmtBuilder::create(nullptr, module); + auto TyVoid = Type::get_void_type(module); + auto TyInt32 = Type::get_int32_type(module); + auto TyInt32Ptr = Type::get_int32_ptr_type(module); + auto TyFloat = Type::get_float_type(module); + auto TyFloatPtr = Type::get_float_ptr_type(module); + + auto input_type = FunctionType::create(TyInt32, {}); + auto get_int = + Function::create( + input_type, + "get_int", + module); + + input_type = FunctionType::create(TyFloat, {}); + auto get_float = + Function::create( + input_type, + "get_float", + module); + + input_type = FunctionType::create(TyInt32, {}); + auto get_char = + Function::create( + input_type, + "get_char", + module); + + PtrVec input_params; + PtrVec ().swap(input_params); + input_params.push_back(TyInt32Ptr); + input_type = FunctionType::create(TyInt32, input_params); + auto get_int_array = + Function::create( + input_type, + "get_int_array", + module); + + PtrVec ().swap(input_params); + input_params.push_back(TyFloatPtr); + input_type = FunctionType::create(TyInt32, input_params); + auto get_float_array = + Function::create( + input_type, + "get_float_array", + module); + + PtrVec output_params; + PtrVec ().swap(output_params); + output_params.push_back(TyInt32); + auto output_type = FunctionType::create(TyVoid, output_params); + auto put_int = + Function::create( + output_type, + "put_int", + module); + + PtrVec ().swap(output_params); + output_params.push_back(TyFloat); + output_type = FunctionType::create(TyVoid, output_params); + auto put_float = + Function::create( + output_type, + "put_float", + module); + + PtrVec ().swap(output_params); + output_params.push_back(TyInt32); + output_type = FunctionType::create(TyVoid, output_params); + auto put_char = + Function::create( + output_type, + "put_char", + module); + + PtrVec ().swap(output_params); + output_params.push_back(TyInt32); + output_params.push_back(TyInt32Ptr); + output_type = FunctionType::create(TyVoid, output_params); + auto put_int_array = + Function::create( + output_type, + "put_int_array", + module); + + PtrVec ().swap(output_params); + output_params.push_back(TyInt32); + output_params.push_back(TyFloatPtr); + output_type = FunctionType::create(TyVoid, output_params); + auto put_float_array = + Function::create( + output_type, + "put_float_array", + module); + + scope.enter(); + scope.push("getint", get_int); + scope.push("getfloat", get_float); + scope.push("getch", get_char); + scope.push("getarray", get_int_array); + scope.push("get_float_array", get_float_array); + scope.push("putint", put_int); + scope.push("putfloat", put_float); + scope.push("putch", put_char); + scope.push("putarray", put_int_array); + scope.push("putfloatarray", put_float_array); + } +public: + static Ptr create() { + return Ptr(new IRBuilder()); + } + Ptr getModule() { + return module; + } +}; + +} +} + +#endif // _SYSYF_IR_BUILDER_H_ diff --git a/include/internal_macros.h b/include/internal_macros.h new file mode 100644 index 0000000..a7f87b7 --- /dev/null +++ b/include/internal_macros.h @@ -0,0 +1,20 @@ +#ifndef _SYSYF_INTERNAL_MACROS_H_ +#define _SYSYF_INTERNAL_MACROS_H_ + +#include "internal_types.h" + +namespace SysYF +{ + +#define _RET_AFTER_INIT(t, ...) \ + { \ + auto tmp = Ptr(new t(__VA_ARGS__)); \ + tmp->init(__VA_ARGS__) ; \ + return tmp; \ + } + +#define RET_AFTER_INIT(t, ...) _RET_AFTER_INIT(t, ##__VA_ARGS__) + +} + +#endif // _SYSYF_INTERNAL_MACROS_H_ \ No newline at end of file diff --git a/include/internal_types.h b/include/internal_types.h new file mode 100644 index 0000000..f412810 --- /dev/null +++ b/include/internal_types.h @@ -0,0 +1,34 @@ +#ifndef _SYSYF_INTERNAL_TYPES_H_ +#define _SYSYF_INTERNAL_TYPES_H_ + +#include +#include +#include +#include + +namespace SysYF +{ + +template +using Ptr = std::shared_ptr; + +// Vector of reference of type +template +using PtrVec = std::vector>; + +// List of reference of type +template +using PtrList = std::list>; + +// Set of reference of type +template +using PtrSet = std::set>; + +using std::static_pointer_cast; +using std::dynamic_pointer_cast; +using std::const_pointer_cast; + +} + + +#endif // !_SYSYF_INTERNAL_TYPES_H_ \ No newline at end of file diff --git a/lib/lib.c b/lib/lib.c new file mode 100644 index 0000000..1fa6ff2 --- /dev/null +++ b/lib/lib.c @@ -0,0 +1,30 @@ +#include +/* Input & output functions */ +int get_int(){int t; scanf("%d",&t); return t; } +float get_float(){float t; scanf("%f",&t); return t; } +int get_char(){char c; scanf("%c",&c); return (int)c; } +int get_int_array(int a[]){ + int n; + scanf("%d",&n); + for(int i=0;i 1-1 请给出while语句对应的LLVM IR的代码布局特点,重点解释其中涉及的几个`br`指令的含义(包含各个参数的含义) + +**1-1:** +生成代码并对主要部分加入注释如下: +```llvm +@b = dso_local global i32 0, align 4 ; 定义一个全局变量b,初始值为0,对齐方式为4 +@a = dso_local global i32 0, align 4 ; 定义一个全局变量a,初始值为0,对齐方式为4 + +; Function Attrs: noinline nounwind optnone uwtable +define dso_local i32 @main() #0 { ; 定义一个名为main的函数,返回类型为i32 + %1 = alloca i32, align 4 ; 在栈上分配一个i32类型的空间,对齐方式为4 + store i32 0, i32* %1, align 4 ; 将0存储到%1指向的地址,对齐方式为4 + store i32 0, i32* @b, align 4 ; 将0存储到全局变量b,对齐方式为4 + store i32 3, i32* @a, align 4 ; 将3存储到全局变量a,对齐方式为4 + br label %2 ; 无条件跳转到标签2 + +2: ; 标签2(循环条件判断基本块) + %3 = load i32, i32* @a, align 4 ; 从全局变量a中加载一个i32类型的值,对齐方式为4 + %4 = icmp sgt i32 %3, 0 ; 比较%3和0的大小关系,结果存储在%4中 + br i1 %4, label %5, label %11 ; 根据%4的值进行条件跳转,如果为真跳转到标签5,否则跳转到标签11 + +5: ; 标签5(循环体基本块) + %6 = load i32, i32* @b, align 4 ; 从全局变量b中加载一个i32类型的值,对齐方式为4 + %7 = load i32, i32* @a, align 4 ; 从全局变量a中加载一个i32类型的值,对齐方式为4 + %8 = add nsw i32 %6, %7 ; 将%6和%7相加,结果存储在%8中 + store i32 %8, i32* @b, align 4 ; 将%8存储到全局变量b,对齐方式为4 + %9 = load i32, i32* @a, align 4 ; 从全局变量a中加载一个i32类型的值,对齐方式为4 + %10 = sub nsw i32 %9, 1 ; 将%9减1,结果存储在%10中 + store i32 %10, i32* @a, align 4 ; 将%10存储到全局变量a,对齐方式为4 + br label %2 ; 无条件跳转到标签2 + +11: ; 标签11(循环结束后基本块) + %12 = load i32, i32* @b, align 4 ; 从全局变量b中加载一个i32类型的值,对齐方式为4 + ret i32 %12 ; 返回%12作为函数的返回值 +} +``` + +注意到如下的while语句对应的LLVM IR的代码布局特点: +1. while语句的条件判断部分和循环体部分分别对应一个基本块, +2. 循环体部分的最后一条语句为无条件跳转到条件判断部分的基本块, +3. 条件判断部分的最后一条语句为条件跳转到循环体部分的基本块或者跳转到循环体部分之后的基本块。 + + +> 1-2 请简述函数调用语句对应的LLVM IR的代码特点 + +**1-2:** +生成代码并对主要部分加入注释如下: +```llvm +define dso_local i32 @add(i32 %0, i32 %1) #0 { + %3 = alloca i32, align 4 ; 在栈上分配一个i32类型的空间,对齐方式为4 + %4 = alloca i32, align 4 ; 在栈上分配另一个i32类型的空间,对齐方式为4 + store i32 %0, i32* %3, align 4 ; 将参数%0的值存储到%3指向的地址中,对齐方式为4 + store i32 %1, i32* %4, align 4 ; 将参数%1的值存储到%4指向的地址中,对齐方式为4 + %5 = load i32, i32* %3, align 4 ; 从%3指向的地址中加载一个i32类型的值,对齐方式为4 + %6 = load i32, i32* %4, align 4 ; 从%4指向的地址中加载一个i32类型的值,对齐方式为4 + %7 = add nsw i32 %5, %6 ; 将%5和%6相加,结果存储在%7中 + %8 = sub nsw i32 %7, 1 ; 将%7减1,结果存储在%8中 + ret i32 %8 ; 返回%8 +} + +define dso_local i32 @main() #0 { ; 定义一个名为main的函数,返回类型为i32 + %1 = alloca i32, align 4 ; 在栈上分配一个i32类型的空间,对齐方式为4 + store i32 3, i32* %1, align 4 ; 将值3存储到%1指向的地址中,对齐方式为4 + %2 = alloca i32, align 4 ; 在栈上分配另一个i32类型的空间,对齐方式为4 + store i32 2, i32* %2, align 4 ; 将值2存储到%2指向的地址中,对齐方式为4 + %3 = load i32, i32* %1, align 4 ; 从%1指向的地址中加载一个i32类型的值,对齐方式为4 + %4 = load i32, i32* %2, align 4 ; 从%2指向的地址中加载一个i32类型的值,对齐方式为4 + %5 = call i32 @add(i32 %3, i32 %4) ; 调用add函数,传入参数%3和%4,并将返回值存储到%5中 + %6 = add nsw i32 %5, 1 ; 将%5加1,结果存储在%6中 + ret i32 %6 ; 从函数中返回%6的值 +} +``` + +注意到如下的函数调用语句对应的LLVM IR的代码特点: +1. 函数调用语句对应的LLVM IR的代码中,会先将函数的参数存储到栈上分配的空间中,然后再调用函数。 +2. 函数调用语句对应的LLVM IR的代码中,会将函数的返回值存储到一个临时变量中,然后再对临时变量进行操作。 +3. 调用者使用`call`指令调用被调用者,被调用者使用`ret`指令返回调用者。 + + + +## 实验设计 + +## 实验难点及解决方案 + +## 实验总结 + +## 实验反馈 + +## 组间交流 diff --git a/src/AST/CMakeLists.txt b/src/AST/CMakeLists.txt new file mode 100644 index 0000000..e54cadb --- /dev/null +++ b/src/AST/CMakeLists.txt @@ -0,0 +1,9 @@ +add_library( + ASTLib STATIC + SyntaxTree.cpp +) + +add_library( + ASTPrinter + SyntaxTreePrinter.cpp +) diff --git a/src/AST/SyntaxTree.cpp b/src/AST/SyntaxTree.cpp new file mode 100755 index 0000000..f60f0ca --- /dev/null +++ b/src/AST/SyntaxTree.cpp @@ -0,0 +1,31 @@ +#include "SyntaxTree.h" + +namespace SysYF +{ +namespace SyntaxTree +{ +void Assembly::accept(Visitor &visitor) { visitor.visit(*this); } +void FuncDef::accept(Visitor &visitor) { visitor.visit(*this); } +void BinaryExpr::accept(Visitor &visitor) { visitor.visit(*this); } +void UnaryExpr::accept(Visitor &visitor) { visitor.visit(*this); } +void LVal::accept(Visitor &visitor) { visitor.visit(*this); } +void Literal::accept(Visitor &visitor) { visitor.visit(*this); } +void ReturnStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void VarDef::accept(Visitor &visitor) { visitor.visit(*this); } +void AssignStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void FuncCallStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void BlockStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void EmptyStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void ExprStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void FuncParam::accept(Visitor &visitor) { visitor.visit(*this); } +void FuncFParamList::accept(Visitor &visitor) { visitor.visit(*this); } +void IfStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void WhileStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void BreakStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void ContinueStmt::accept(Visitor &visitor) { visitor.visit(*this); } +void UnaryCondExpr::accept(Visitor &visitor) { visitor.visit(*this); } +void BinaryCondExpr::accept(Visitor &visitor) { visitor.visit(*this); } +void InitVal::accept(Visitor &visitor) { visitor.visit(*this); } + +} +} \ No newline at end of file diff --git a/src/AST/SyntaxTreePrinter.cpp b/src/AST/SyntaxTreePrinter.cpp new file mode 100755 index 0000000..812ace1 --- /dev/null +++ b/src/AST/SyntaxTreePrinter.cpp @@ -0,0 +1,317 @@ +#include "SyntaxTreePrinter.h" +#include "ErrorReporter.h" +#include +#include +#include + +namespace SysYF +{ +namespace SyntaxTree +{ +std::map type2str = { + {Type::INT, "int"}, + {Type::VOID, "void"}, + {Type::FLOAT, "float"} +}; + +std::map bincondop2str = { + {BinaryCondOp::EQ,"=="}, + {BinaryCondOp::NEQ,"!="}, + {BinaryCondOp::GT,">"}, + {BinaryCondOp::GTE,">="}, + {BinaryCondOp::LT,"<"}, + {BinaryCondOp::LTE,"<="}, + {BinaryCondOp::LAND,"&&"}, + {BinaryCondOp::LOR,"||"} +}; + +std::map binop2str = { + {BinOp::PLUS, "+"}, + {BinOp::MINUS, "-"}, + {BinOp::MULTIPLY, "*"}, + {BinOp::DIVIDE, "/"}, + {BinOp::MODULO, "%"} +}; + +std::map unarycondop2str = { + {UnaryCondOp::NOT,"!"} +}; + +std::map unaryop2str = { + {UnaryOp::PLUS, "+"}, + {UnaryOp::MINUS, "-"} +}; + +void SyntaxTreePrinter::print_indent() +{ + for (int i = 0; i < indent; i++) + std::cout << " "; +} + +void SyntaxTreePrinter::visit(Assembly &node) +{ + indent = 0; + for (auto def : node.global_defs) { + def->accept(*this); + } +} + +void SyntaxTreePrinter::visit(FuncDef &node) +{ + std::cout << type2str[node.ret_type] << " " + << node.name << "("; + node.param_list->accept(*this); + std::cout << ")" << std::endl; + node.body->accept(*this); + indent = 0; +} + +void SyntaxTreePrinter::visit(BlockStmt &node) +{ + print_indent(); + std::cout << "{" << std::endl; + indent += 4; + for (auto stmt : node.body) { + stmt->accept(*this); + } + indent -= 4; + print_indent(); + std::cout << "}" << std::endl; +} + +void SyntaxTreePrinter::visit(VarDef &node) +{ + print_indent(); + if (node.is_constant) + std::cout << "const "; + std::cout << type2str[node.btype] << " " << node.name; + for (auto length : node.array_length) { + std::cout << "["; + length->accept(*this); + std::cout << "]"; + } + if (node.is_inited) { + int tmp = indent; + indent = 0; + std::cout << " = "; + node.initializers->accept(*this); + indent = tmp; + } + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(InitVal &node){ + if(node.isExp){ + node.expr->accept(*this); + } + else{ + std::cout << "{"; + int i = 0; + int num = node.elementList.size(); + for(auto item: node.elementList){ + item->accept(*this); + i++; + if(i < num) std::cout << ", "; + } + std::cout << "}"; + } + return; +} + +void SyntaxTreePrinter::visit(BinaryExpr &node) +{ + std::cout << "("; + node.lhs->accept(*this); + std::cout << binop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(UnaryExpr &node) +{ + std::cout << "("; + std::cout << unaryop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(LVal &node) +{ + std::cout << node.name; + for (auto index : node.array_index) { + std::cout << "["; + index->accept(*this); + std::cout << "]"; + } +} + +void SyntaxTreePrinter::visit(Literal &node) +{ + if (node.literal_type == Type::INT) + std::cout << node.int_const; + else if(node.literal_type == Type::FLOAT) + std::cout << node.float_const; + else { + ErrorReporter error(std::cerr); + error.error(node.loc,"unsupported literal type!"); + abort(); + } +} + +void SyntaxTreePrinter::visit(ReturnStmt &node) +{ + print_indent(); + std::cout << "return"; + //indent = 0; + if (node.ret.get()) { + std::cout << " "; + node.ret->accept(*this); + } + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(AssignStmt &node) +{ + print_indent(); + node.target->accept(*this); + std::cout << " = "; + node.value->accept(*this); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(FuncCallStmt &node) +{ + //print_indent(); + std::cout << node.name << "("; + size_t num = 0; + for(auto exp:node.params) + { + exp->accept(*this); + if(num < node.params.size() - 1) + { + std::cout <<", "; + } + num++; + } + std::cout <<")"; +} + +void SyntaxTreePrinter::visit(EmptyStmt &) +{ + print_indent(); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(ExprStmt &node) +{ + print_indent(); + node.exp->accept(*this); + std::cout << ";" << std::endl; +} + +void SyntaxTreePrinter::visit(FuncParam &node) +{ + std::cout << type2str[node.param_type] << " " << node.name; + for(auto exp:node.array_index) + { + std::cout << "["; + if (exp != nullptr) + exp->accept(*this); + std::cout << "]"; + } +} + +void SyntaxTreePrinter::visit(FuncFParamList &node) +{ + size_t num = 0; + for(auto param:node.params) + { + param->accept(*this); + if(num < node.params.size() - 1) + { + std::cout << ", "; + } + num++; + } +} + +void SyntaxTreePrinter::visit(BinaryCondExpr &node) +{ + std::cout << "("; + node.lhs->accept(*this); + std::cout << bincondop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(UnaryCondExpr &node) +{ + std::cout <<"("; + std::cout << unarycondop2str[node.op]; + node.rhs->accept(*this); + std::cout << ")"; +} + +void SyntaxTreePrinter::visit(IfStmt &node) +{ + print_indent(); + std::cout << "if"; + std::cout << " "; + std::cout << "("; + node.cond_exp->accept(*this); + std::cout << ")" << std::endl; + if(dynamic_cast(node.if_statement.get())){ + node.if_statement->accept(*this); + } + else{ + indent+=4; + node.if_statement->accept(*this); + indent-=4; + } + if (node.else_statement != nullptr) { + print_indent(); + std::cout << "else" << std::endl; + if(dynamic_cast(node.else_statement.get())){ + node.else_statement->accept(*this); + }else { + indent+=4; + node.else_statement->accept(*this); + indent-=4; + } + } +} + +void SyntaxTreePrinter::visit(WhileStmt &node) +{ + print_indent(); + std::cout << "while"; + std::cout << " "; + std::cout << "("; + node.cond_exp->accept(*this); + std::cout << ")"<< std::endl; + if(dynamic_cast(node.statement.get())){ + node.statement->accept(*this); + } + else{ + indent+=4; + node.statement->accept(*this); + indent-=4; + } +} + +void SyntaxTreePrinter::visit(BreakStmt &node) +{ + print_indent(); + std::cout << "break"; + std::cout << ";" < SysYFDriver::parse(const std::string &f) +{ + file = f; + + // lexer begin + scan_begin(); + yy::SysYFParser parser(*this); + parser.set_debug_level(trace_parsing); + // parser begin + parser.parse(); + // lexer end + scan_end(); + + return this->root; +} + +void SysYFDriver::error(const yy::location& l, const std::string& m) +{ + std::cerr << l << ": " << m << std::endl; +} + +void SysYFDriver::error(const std::string& m) +{ + std::cerr << m << std::endl; +} + + +void SysYFDriver::scan_begin() +{ + lexer.set_debug(trace_scanning); + + // Try to open the file: + instream.open(file); + + if(instream.good()) { + lexer.switch_streams(&instream, 0); + } + else if(file == "-") { + lexer.switch_streams(&std::cin, 0); + } + else { + error("Cannot open file '" + file + "'."); + exit(EXIT_FAILURE); + } +} + +void SysYFDriver::scan_end() +{ + instream.close(); +} diff --git a/src/Frontend/SysYFParser.cpp b/src/Frontend/SysYFParser.cpp new file mode 100644 index 0000000..b11d783 --- /dev/null +++ b/src/Frontend/SysYFParser.cpp @@ -0,0 +1,2479 @@ +// A Bison parser, made by GNU Bison 3.8.2. + +// Skeleton implementation for Bison LALR(1) parsers in C++ + +// Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc. + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +// As a special exception, you may create a larger work that contains +// part or all of the Bison parser skeleton and distribute that work +// under terms of your choice, so long as that work isn't itself a +// parser generator using the skeleton or a modified version thereof +// as a parser skeleton. Alternatively, if you modify or redistribute +// the parser skeleton itself, you may (at your option) remove this +// special exception, which will cause the skeleton and the resulting +// Bison output files to be licensed under the GNU General Public +// License without this special exception. + +// This special exception was added by the Free Software Foundation in +// version 2.2 of Bison. + +// DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual, +// especially those whose name start with YY_ or yy_. They are +// private implementation details that can be changed or removed. + + + + + +#include "SysYFParser.h" + + +// Unqualified %code blocks. +#line 35 "../../grammar/SysYFParser.yy" + +#include "SysYFDriver.h" +#define yylex driver.lexer.yylex + +#line 51 "./SysYFParser.cpp" + + +#ifndef YY_ +# if defined YYENABLE_NLS && YYENABLE_NLS +# if ENABLE_NLS +# include // FIXME: INFRINGES ON USER NAME SPACE. +# define YY_(msgid) dgettext ("bison-runtime", msgid) +# endif +# endif +# ifndef YY_ +# define YY_(msgid) msgid +# endif +#endif + + +// Whether we are compiled with exception support. +#ifndef YY_EXCEPTIONS +# if defined __GNUC__ && !defined __EXCEPTIONS +# define YY_EXCEPTIONS 0 +# else +# define YY_EXCEPTIONS 1 +# endif +#endif + +#define YYRHSLOC(Rhs, K) ((Rhs)[K].location) +/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. + If N is 0, then set CURRENT to the empty location which ends + the previous symbol: RHS[0] (always defined). */ + +# ifndef YYLLOC_DEFAULT +# define YYLLOC_DEFAULT(Current, Rhs, N) \ + do \ + if (N) \ + { \ + (Current).begin = YYRHSLOC (Rhs, 1).begin; \ + (Current).end = YYRHSLOC (Rhs, N).end; \ + } \ + else \ + { \ + (Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \ + } \ + while (false) +# endif + + +// Enable debugging if requested. +#if YYDEBUG + +// A pseudo ostream that takes yydebug_ into account. +# define YYCDEBUG if (yydebug_) (*yycdebug_) + +# define YY_SYMBOL_PRINT(Title, Symbol) \ + do { \ + if (yydebug_) \ + { \ + *yycdebug_ << Title << ' '; \ + yy_print_ (*yycdebug_, Symbol); \ + *yycdebug_ << '\n'; \ + } \ + } while (false) + +# define YY_REDUCE_PRINT(Rule) \ + do { \ + if (yydebug_) \ + yy_reduce_print_ (Rule); \ + } while (false) + +# define YY_STACK_PRINT() \ + do { \ + if (yydebug_) \ + yy_stack_print_ (); \ + } while (false) + +#else // !YYDEBUG + +# define YYCDEBUG if (false) std::cerr +# define YY_SYMBOL_PRINT(Title, Symbol) YY_USE (Symbol) +# define YY_REDUCE_PRINT(Rule) static_cast (0) +# define YY_STACK_PRINT() static_cast (0) + +#endif // !YYDEBUG + +#define yyerrok (yyerrstatus_ = 0) +#define yyclearin (yyla.clear ()) + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab +#define YYRECOVERING() (!!yyerrstatus_) + +namespace yy { +#line 143 "./SysYFParser.cpp" + + /// Build a parser object. + SysYFParser::SysYFParser (SysYFDriver& driver_yyarg) +#if YYDEBUG + : yydebug_ (false), + yycdebug_ (&std::cerr), +#else + : +#endif + driver (driver_yyarg) + {} + + SysYFParser::~SysYFParser () + {} + + SysYFParser::syntax_error::~syntax_error () YY_NOEXCEPT YY_NOTHROW + {} + + /*---------. + | symbol. | + `---------*/ + + + + // by_state. + SysYFParser::by_state::by_state () YY_NOEXCEPT + : state (empty_state) + {} + + SysYFParser::by_state::by_state (const by_state& that) YY_NOEXCEPT + : state (that.state) + {} + + void + SysYFParser::by_state::clear () YY_NOEXCEPT + { + state = empty_state; + } + + void + SysYFParser::by_state::move (by_state& that) + { + state = that.state; + that.clear (); + } + + SysYFParser::by_state::by_state (state_type s) YY_NOEXCEPT + : state (s) + {} + + SysYFParser::symbol_kind_type + SysYFParser::by_state::kind () const YY_NOEXCEPT + { + if (state == empty_state) + return symbol_kind::S_YYEMPTY; + else + return YY_CAST (symbol_kind_type, yystos_[+state]); + } + + SysYFParser::stack_symbol_type::stack_symbol_type () + {} + + SysYFParser::stack_symbol_type::stack_symbol_type (YY_RVREF (stack_symbol_type) that) + : super_type (YY_MOVE (that.state), YY_MOVE (that.location)) + { + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.YY_MOVE_OR_COPY< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.YY_MOVE_OR_COPY< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.YY_MOVE_OR_COPY< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.YY_MOVE_OR_COPY< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.YY_MOVE_OR_COPY< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.YY_MOVE_OR_COPY< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.YY_MOVE_OR_COPY< SysYF::SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.YY_MOVE_OR_COPY< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.YY_MOVE_OR_COPY< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.YY_MOVE_OR_COPY< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + +#if 201103L <= YY_CPLUSPLUS + // that is emptied. + that.state = empty_state; +#endif + } + + SysYFParser::stack_symbol_type::stack_symbol_type (state_type s, YY_MOVE_REF (symbol_type) that) + : super_type (s, YY_MOVE (that.location)) + { + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Block: // Block + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Number: // Number + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SysYF::Ptr > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SysYF::PtrVec > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_BType: // BType + value.move< SysYF::SyntaxTree::Type > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (YY_MOVE (that.value)); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (YY_MOVE (that.value)); + break; + + default: + break; + } + + // that is emptied. + that.kind_ = symbol_kind::S_YYEMPTY; + } + +#if YY_CPLUSPLUS < 201103L + SysYFParser::stack_symbol_type& + SysYFParser::stack_symbol_type::operator= (const stack_symbol_type& that) + { + state = that.state; + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Block: // Block + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_LVal: // LVal + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Number: // Number + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.copy< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.copy< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.copy< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.copy< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.copy< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.copy< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_BType: // BType + value.copy< SysYF::SyntaxTree::Type > (that.value); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.copy< float > (that.value); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.copy< int > (that.value); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.copy< std::string > (that.value); + break; + + default: + break; + } + + location = that.location; + return *this; + } + + SysYFParser::stack_symbol_type& + SysYFParser::stack_symbol_type::operator= (stack_symbol_type& that) + { + state = that.state; + switch (that.kind ()) + { + case symbol_kind::S_CompUnit: // CompUnit + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Block: // Block + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_FuncDef: // FuncDef + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_LVal: // LVal + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Number: // Number + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + value.move< SysYF::Ptr > (that.value); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + value.move< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + value.move< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + value.move< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + value.move< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + value.move< SysYF::PtrVec > (that.value); + break; + + case symbol_kind::S_BType: // BType + value.move< SysYF::SyntaxTree::Type > (that.value); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + value.move< float > (that.value); + break; + + case symbol_kind::S_INTCONST: // INTCONST + value.move< int > (that.value); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + value.move< std::string > (that.value); + break; + + default: + break; + } + + location = that.location; + // that is emptied. + that.state = empty_state; + return *this; + } +#endif + + template + void + SysYFParser::yy_destroy_ (const char* yymsg, basic_symbol& yysym) const + { + if (yymsg) + YY_SYMBOL_PRINT (yymsg, yysym); + } + +#if YYDEBUG + template + void + SysYFParser::yy_print_ (std::ostream& yyo, const basic_symbol& yysym) const + { + std::ostream& yyoutput = yyo; + YY_USE (yyoutput); + if (yysym.empty ()) + yyo << "empty symbol"; + else + { + symbol_kind_type yykind = yysym.kind (); + yyo << (yykind < YYNTOKENS ? "token" : "nterm") + << ' ' << yysym.name () << " (" + << yysym.location << ": "; + YY_USE (yykind); + yyo << ')'; + } + } +#endif + + void + SysYFParser::yypush_ (const char* m, YY_MOVE_REF (stack_symbol_type) sym) + { + if (m) + YY_SYMBOL_PRINT (m, sym); + yystack_.push (YY_MOVE (sym)); + } + + void + SysYFParser::yypush_ (const char* m, state_type s, YY_MOVE_REF (symbol_type) sym) + { +#if 201103L <= YY_CPLUSPLUS + yypush_ (m, stack_symbol_type (s, std::move (sym))); +#else + stack_symbol_type ss (s, sym); + yypush_ (m, ss); +#endif + } + + void + SysYFParser::yypop_ (int n) YY_NOEXCEPT + { + yystack_.pop (n); + } + +#if YYDEBUG + std::ostream& + SysYFParser::debug_stream () const + { + return *yycdebug_; + } + + void + SysYFParser::set_debug_stream (std::ostream& o) + { + yycdebug_ = &o; + } + + + SysYFParser::debug_level_type + SysYFParser::debug_level () const + { + return yydebug_; + } + + void + SysYFParser::set_debug_level (debug_level_type l) + { + yydebug_ = l; + } +#endif // YYDEBUG + + SysYFParser::state_type + SysYFParser::yy_lr_goto_state_ (state_type yystate, int yysym) + { + int yyr = yypgoto_[yysym - YYNTOKENS] + yystate; + if (0 <= yyr && yyr <= yylast_ && yycheck_[yyr] == yystate) + return yytable_[yyr]; + else + return yydefgoto_[yysym - YYNTOKENS]; + } + + bool + SysYFParser::yy_pact_value_is_default_ (int yyvalue) YY_NOEXCEPT + { + return yyvalue == yypact_ninf_; + } + + bool + SysYFParser::yy_table_value_is_error_ (int yyvalue) YY_NOEXCEPT + { + return yyvalue == yytable_ninf_; + } + + int + SysYFParser::operator() () + { + return parse (); + } + + int + SysYFParser::parse () + { + int yyn; + /// Length of the RHS of the rule being reduced. + int yylen = 0; + + // Error handling. + int yynerrs_ = 0; + int yyerrstatus_ = 0; + + /// The lookahead symbol. + symbol_type yyla; + + /// The locations where the error started and ended. + stack_symbol_type yyerror_range[3]; + + /// The return value of parse (). + int yyresult; + +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + YYCDEBUG << "Starting parse\n"; + + + // User initialization code. +#line 24 "../../grammar/SysYFParser.yy" +{ +// Initialize the initial location. +yyla.location.begin.filename = yyla.location.end.filename = &driver.file; +} + +#line 785 "./SysYFParser.cpp" + + + /* Initialize the stack. The initial state will be set in + yynewstate, since the latter expects the semantical and the + location values to have been already stored, initialize these + stacks with a primary value. */ + yystack_.clear (); + yypush_ (YY_NULLPTR, 0, YY_MOVE (yyla)); + + /*-----------------------------------------------. + | yynewstate -- push a new symbol on the stack. | + `-----------------------------------------------*/ + yynewstate: + YYCDEBUG << "Entering state " << int (yystack_[0].state) << '\n'; + YY_STACK_PRINT (); + + // Accept? + if (yystack_[0].state == yyfinal_) + YYACCEPT; + + goto yybackup; + + + /*-----------. + | yybackup. | + `-----------*/ + yybackup: + // Try to take a decision without lookahead. + yyn = yypact_[+yystack_[0].state]; + if (yy_pact_value_is_default_ (yyn)) + goto yydefault; + + // Read a lookahead token. + if (yyla.empty ()) + { + YYCDEBUG << "Reading a token\n"; +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + symbol_type yylookahead (yylex (driver)); + yyla.move (yylookahead); + } +#if YY_EXCEPTIONS + catch (const syntax_error& yyexc) + { + YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; + error (yyexc); + goto yyerrlab1; + } +#endif // YY_EXCEPTIONS + } + YY_SYMBOL_PRINT ("Next token is", yyla); + + if (yyla.kind () == symbol_kind::S_YYerror) + { + // The scanner already issued an error message, process directly + // to error recovery. But do not keep the error token as + // lookahead, it is too special and may lead us to an endless + // loop in error recovery. */ + yyla.kind_ = symbol_kind::S_YYUNDEF; + goto yyerrlab1; + } + + /* If the proper action on seeing token YYLA.TYPE is to reduce or + to detect an error, take that action. */ + yyn += yyla.kind (); + if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yyla.kind ()) + { + goto yydefault; + } + + // Reduce or error. + yyn = yytable_[yyn]; + if (yyn <= 0) + { + if (yy_table_value_is_error_ (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + // Count tokens shifted since error; after three, turn off error status. + if (yyerrstatus_) + --yyerrstatus_; + + // Shift the lookahead token. + yypush_ ("Shifting", state_type (yyn), YY_MOVE (yyla)); + goto yynewstate; + + + /*-----------------------------------------------------------. + | yydefault -- do the default action for the current state. | + `-----------------------------------------------------------*/ + yydefault: + yyn = yydefact_[+yystack_[0].state]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + + /*-----------------------------. + | yyreduce -- do a reduction. | + `-----------------------------*/ + yyreduce: + yylen = yyr2_[yyn]; + { + stack_symbol_type yylhs; + yylhs.state = yy_lr_goto_state_ (yystack_[yylen].state, yyr1_[yyn]); + /* Variants are always initialized to an empty instance of the + correct type. The default '$$ = $1' action is NOT applied + when using variants. */ + switch (yyr1_[yyn]) + { + case symbol_kind::S_CompUnit: // CompUnit + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_Block: // Block + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_OptionRet: // OptionRet + case symbol_kind::S_Exp: // Exp + case symbol_kind::S_RelExp: // RelExp + case symbol_kind::S_EqExp: // EqExp + case symbol_kind::S_LAndExp: // LAndExp + case symbol_kind::S_LOrExp: // LOrExp + case symbol_kind::S_CondExp: // CondExp + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_FuncDef: // FuncDef + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_FuncFParam: // FuncFParam + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_InitVal: // InitVal + case symbol_kind::S_InitValList: // InitValList + case symbol_kind::S_CommaInitValList: // CommaInitValList + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_LVal: // LVal + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_Number: // Number + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_Stmt: // Stmt + case symbol_kind::S_IfStmt: // IfStmt + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_ConstDef: // ConstDef + case symbol_kind::S_VarDef: // VarDef + yylhs.value.emplace< SysYF::Ptr > (); + break; + + case symbol_kind::S_ArrayExpList: // ArrayExpList + case symbol_kind::S_ExpList: // ExpList + case symbol_kind::S_CommaExpList: // CommaExpList + yylhs.value.emplace< SysYF::PtrVec > (); + break; + + case symbol_kind::S_FParamList: // FParamList + case symbol_kind::S_CommaFParamList: // CommaFParamList + yylhs.value.emplace< SysYF::PtrVec > (); + break; + + case symbol_kind::S_GlobalDecl: // GlobalDecl + yylhs.value.emplace< SysYF::PtrVec > (); + break; + + case symbol_kind::S_BlockItemList: // BlockItemList + case symbol_kind::S_BlockItem: // BlockItem + yylhs.value.emplace< SysYF::PtrVec > (); + break; + + case symbol_kind::S_ConstDecl: // ConstDecl + case symbol_kind::S_ConstDefList: // ConstDefList + case symbol_kind::S_VarDecl: // VarDecl + case symbol_kind::S_VarDefList: // VarDefList + yylhs.value.emplace< SysYF::PtrVec > (); + break; + + case symbol_kind::S_BType: // BType + yylhs.value.emplace< SysYF::SyntaxTree::Type > (); + break; + + case symbol_kind::S_FLOATCONST: // FLOATCONST + yylhs.value.emplace< float > (); + break; + + case symbol_kind::S_INTCONST: // INTCONST + yylhs.value.emplace< int > (); + break; + + case symbol_kind::S_IDENTIFIER: // IDENTIFIER + case symbol_kind::S_STRINGCONST: // STRINGCONST + yylhs.value.emplace< std::string > (); + break; + + default: + break; + } + + + // Default location. + { + stack_type::slice range (yystack_, yylen); + YYLLOC_DEFAULT (yylhs.location, range, yylen); + yyerror_range[1].location = yylhs.location; + } + + // Perform the reduction. + YY_REDUCE_PRINT (yyn); +#if YY_EXCEPTIONS + try +#endif // YY_EXCEPTIONS + { + switch (yyn) + { + case 2: // Begin: CompUnit END +#line 106 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::Ptr > ()->loc = yylhs.location; + driver.root = yystack_[1].value.as < SysYF::Ptr > (); + return 0; + } +#line 1021 "./SysYFParser.cpp" + break; + + case 3: // CompUnit: CompUnit GlobalDecl +#line 113 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::Ptr > ()->global_defs.insert(yystack_[1].value.as < SysYF::Ptr > ()->global_defs.end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + yylhs.value.as < SysYF::Ptr > ()=yystack_[1].value.as < SysYF::Ptr > (); + } +#line 1030 "./SysYFParser.cpp" + break; + + case 4: // CompUnit: GlobalDecl +#line 117 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > ()=SysYF::Ptr(new SysYF::SyntaxTree::Assembly()); + yylhs.value.as < SysYF::Ptr > ()->global_defs.insert(yylhs.value.as < SysYF::Ptr > ()->global_defs.end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + } +#line 1039 "./SysYFParser.cpp" + break; + + case 5: // GlobalDecl: ConstDecl +#line 123 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().insert(yylhs.value.as < SysYF::PtrVec > ().end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + } +#line 1048 "./SysYFParser.cpp" + break; + + case 6: // GlobalDecl: VarDecl +#line 127 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().insert(yylhs.value.as < SysYF::PtrVec > ().end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + } +#line 1057 "./SysYFParser.cpp" + break; + + case 7: // GlobalDecl: FuncDef +#line 131 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + } +#line 1066 "./SysYFParser.cpp" + break; + + case 8: // ConstDecl: CONST BType ConstDefList SEMICOLON +#line 137 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=yystack_[1].value.as < SysYF::PtrVec > (); + for (auto &node : yylhs.value.as < SysYF::PtrVec > ()) { + node->btype = yystack_[2].value.as < SysYF::SyntaxTree::Type > (); + } + } +#line 1077 "./SysYFParser.cpp" + break; + + case 9: // ConstDefList: ConstDefList COMMA ConstDef +#line 144 "../../grammar/SysYFParser.yy" + { + yystack_[2].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > ()=yystack_[2].value.as < SysYF::PtrVec > (); + } +#line 1086 "./SysYFParser.cpp" + break; + + case 10: // ConstDefList: ConstDef +#line 148 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + } +#line 1095 "./SysYFParser.cpp" + break; + + case 11: // BType: INT +#line 154 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::SyntaxTree::Type > ()=SysYF::SyntaxTree::Type::INT; + } +#line 1103 "./SysYFParser.cpp" + break; + + case 12: // BType: FLOAT +#line 157 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::SyntaxTree::Type > ()=SysYF::SyntaxTree::Type::FLOAT; + } +#line 1111 "./SysYFParser.cpp" + break; + + case 13: // ConstDef: IDENTIFIER ArrayExpList ASSIGN InitVal +#line 163 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > ()=SysYF::Ptr(new SysYF::SyntaxTree::VarDef()); + yylhs.value.as < SysYF::Ptr > ()->is_constant = true; + yylhs.value.as < SysYF::Ptr > ()->is_inited = true; + yylhs.value.as < SysYF::Ptr > ()->name=yystack_[3].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_length = yystack_[2].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->initializers = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1125 "./SysYFParser.cpp" + break; + + case 14: // VarDecl: BType VarDefList SEMICOLON +#line 174 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=yystack_[1].value.as < SysYF::PtrVec > (); + for (auto &node : yylhs.value.as < SysYF::PtrVec > ()) { + node->btype = yystack_[2].value.as < SysYF::SyntaxTree::Type > (); + } + } +#line 1136 "./SysYFParser.cpp" + break; + + case 15: // VarDefList: VarDefList COMMA VarDef +#line 182 "../../grammar/SysYFParser.yy" + { + yystack_[2].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > ()=yystack_[2].value.as < SysYF::PtrVec > (); + } +#line 1145 "./SysYFParser.cpp" + break; + + case 16: // VarDefList: VarDef +#line 186 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + } +#line 1154 "./SysYFParser.cpp" + break; + + case 17: // VarDef: IDENTIFIER ArrayExpList +#line 192 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > ()=SysYF::Ptr(new SysYF::SyntaxTree::VarDef()); + yylhs.value.as < SysYF::Ptr > ()->name=yystack_[1].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_length = yystack_[0].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->is_inited = false; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1166 "./SysYFParser.cpp" + break; + + case 18: // VarDef: IDENTIFIER ArrayExpList ASSIGN InitVal +#line 199 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::VarDef()); + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[3].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_length = yystack_[2].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->initializers = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > ()->is_inited = true; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1179 "./SysYFParser.cpp" + break; + + case 19: // ArrayExpList: ArrayExpList LBRACKET Exp RBRACKET +#line 209 "../../grammar/SysYFParser.yy" + { + yystack_[3].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > ()=yystack_[3].value.as < SysYF::PtrVec > (); + } +#line 1188 "./SysYFParser.cpp" + break; + + case 20: // ArrayExpList: %empty +#line 213 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > ()=SysYF::PtrVec(); + } +#line 1196 "./SysYFParser.cpp" + break; + + case 21: // InitVal: Exp +#line 218 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::InitVal()); + yylhs.value.as < SysYF::Ptr > ()->isExp = true; + yylhs.value.as < SysYF::Ptr > ()->elementList = SysYF::PtrVec(); + yylhs.value.as < SysYF::Ptr > ()->expr = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1208 "./SysYFParser.cpp" + break; + + case 22: // InitVal: LBRACE InitValList RBRACE +#line 225 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[1].value.as < SysYF::Ptr > (); + } +#line 1216 "./SysYFParser.cpp" + break; + + case 23: // InitValList: CommaInitValList InitVal +#line 230 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::Ptr > ()->elementList.push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::Ptr > () = yystack_[1].value.as < SysYF::Ptr > (); + } +#line 1225 "./SysYFParser.cpp" + break; + + case 24: // InitValList: %empty +#line 234 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::InitVal()); + yylhs.value.as < SysYF::Ptr > ()->isExp = false; + yylhs.value.as < SysYF::Ptr > ()->elementList = SysYF::PtrVec(); + //$$->elementList = std::vector>(); + yylhs.value.as < SysYF::Ptr > ()->expr = nullptr; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1238 "./SysYFParser.cpp" + break; + + case 25: // CommaInitValList: CommaInitValList InitVal COMMA +#line 244 "../../grammar/SysYFParser.yy" + { + yystack_[2].value.as < SysYF::Ptr > ()->elementList.push_back(SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::Ptr > () = yystack_[2].value.as < SysYF::Ptr > (); + } +#line 1247 "./SysYFParser.cpp" + break; + + case 26: // CommaInitValList: %empty +#line 248 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::InitVal()); + yylhs.value.as < SysYF::Ptr > ()->isExp = false; + yylhs.value.as < SysYF::Ptr > ()->elementList = SysYF::PtrVec(); + //$$->elementList = std::vector>(); + yylhs.value.as < SysYF::Ptr > ()->expr = nullptr; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1260 "./SysYFParser.cpp" + break; + + case 27: // ExpList: CommaExpList Exp +#line 258 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > () = yystack_[1].value.as < SysYF::PtrVec > (); + } +#line 1269 "./SysYFParser.cpp" + break; + + case 28: // ExpList: %empty +#line 262 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + } +#line 1277 "./SysYFParser.cpp" + break; + + case 29: // CommaExpList: CommaExpList Exp COMMA +#line 267 "../../grammar/SysYFParser.yy" + { + yystack_[2].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > () = yystack_[2].value.as < SysYF::PtrVec > (); + } +#line 1286 "./SysYFParser.cpp" + break; + + case 30: // CommaExpList: %empty +#line 271 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + } +#line 1294 "./SysYFParser.cpp" + break; + + case 31: // FuncFParam: BType IDENTIFIER ArrayExpList +#line 277 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::FuncParam()); + yylhs.value.as < SysYF::Ptr > ()->param_type = yystack_[2].value.as < SysYF::SyntaxTree::Type > (); + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[1].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_index = yystack_[0].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; +} +#line 1306 "./SysYFParser.cpp" + break; + + case 32: // FuncFParam: BType IDENTIFIER LRBRACKET ArrayExpList +#line 284 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::FuncParam()); + yylhs.value.as < SysYF::Ptr > ()->param_type = yystack_[3].value.as < SysYF::SyntaxTree::Type > (); + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[2].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_index = yystack_[0].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->array_index.insert(yylhs.value.as < SysYF::Ptr > ()->array_index.begin(),nullptr); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; +} +#line 1319 "./SysYFParser.cpp" + break; + + case 33: // FParamList: CommaFParamList FuncFParam +#line 294 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > () = yystack_[1].value.as < SysYF::PtrVec > (); +} +#line 1328 "./SysYFParser.cpp" + break; + + case 34: // FParamList: %empty +#line 298 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); +} +#line 1336 "./SysYFParser.cpp" + break; + + case 35: // CommaFParamList: CommaFParamList FuncFParam COMMA +#line 303 "../../grammar/SysYFParser.yy" + { + yystack_[2].value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ())); + yylhs.value.as < SysYF::PtrVec > () = yystack_[2].value.as < SysYF::PtrVec > (); +} +#line 1345 "./SysYFParser.cpp" + break; + + case 36: // CommaFParamList: %empty +#line 307 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); +} +#line 1353 "./SysYFParser.cpp" + break; + + case 37: // FuncDef: BType IDENTIFIER LPARENTHESE FParamList RPARENTHESE Block +#line 311 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::FuncDef()); + yylhs.value.as < SysYF::Ptr > ()->ret_type = yystack_[5].value.as < SysYF::SyntaxTree::Type > (); + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[4].value.as < std::string > (); + auto tmp = SysYF::Ptr(new SysYF::SyntaxTree::FuncFParamList()); + tmp->params = yystack_[2].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->param_list = SysYF::Ptr(tmp); + yylhs.value.as < SysYF::Ptr > ()->body = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1368 "./SysYFParser.cpp" + break; + + case 38: // FuncDef: VOID IDENTIFIER LPARENTHESE FParamList RPARENTHESE Block +#line 321 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::FuncDef()); + yylhs.value.as < SysYF::Ptr > ()->ret_type = SysYF::SyntaxTree::Type::VOID; + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[4].value.as < std::string > (); + auto tmp = SysYF::Ptr(new SysYF::SyntaxTree::FuncFParamList()); + tmp->params = yystack_[2].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->param_list = SysYF::Ptr(tmp); + yylhs.value.as < SysYF::Ptr > ()->body = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1383 "./SysYFParser.cpp" + break; + + case 39: // Block: LBRACE BlockItemList RBRACE +#line 333 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::BlockStmt()); + yylhs.value.as < SysYF::Ptr > ()->body = yystack_[1].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1393 "./SysYFParser.cpp" + break; + + case 40: // BlockItemList: BlockItemList BlockItem +#line 340 "../../grammar/SysYFParser.yy" + { + yystack_[1].value.as < SysYF::PtrVec > ().insert(yystack_[1].value.as < SysYF::PtrVec > ().end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + yylhs.value.as < SysYF::PtrVec > () = yystack_[1].value.as < SysYF::PtrVec > (); + } +#line 1402 "./SysYFParser.cpp" + break; + + case 41: // BlockItemList: %empty +#line 344 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + } +#line 1410 "./SysYFParser.cpp" + break; + + case 42: // BlockItem: VarDecl +#line 349 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().insert(yylhs.value.as < SysYF::PtrVec > ().end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + } +#line 1419 "./SysYFParser.cpp" + break; + + case 43: // BlockItem: ConstDecl +#line 353 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().insert(yylhs.value.as < SysYF::PtrVec > ().end(), yystack_[0].value.as < SysYF::PtrVec > ().begin(), yystack_[0].value.as < SysYF::PtrVec > ().end()); + } +#line 1428 "./SysYFParser.cpp" + break; + + case 44: // BlockItem: Stmt +#line 357 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::PtrVec > () = SysYF::PtrVec(); + yylhs.value.as < SysYF::PtrVec > ().push_back(SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ())); + } +#line 1437 "./SysYFParser.cpp" + break; + + case 45: // Stmt: LVal ASSIGN Exp SEMICOLON +#line 363 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::AssignStmt()); + temp->target = SysYF::Ptr(yystack_[3].value.as < SysYF::Ptr > ()); + temp->value = SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1449 "./SysYFParser.cpp" + break; + + case 46: // Stmt: Exp SEMICOLON +#line 370 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::ExprStmt()); + temp->exp = SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1460 "./SysYFParser.cpp" + break; + + case 47: // Stmt: RETURN OptionRet SEMICOLON +#line 376 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::ReturnStmt()); + temp->ret = SysYF::Ptr(yystack_[1].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1471 "./SysYFParser.cpp" + break; + + case 48: // Stmt: Block +#line 382 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1479 "./SysYFParser.cpp" + break; + + case 49: // Stmt: WHILE LPARENTHESE CondExp RPARENTHESE Stmt +#line 385 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::WhileStmt()); + temp->cond_exp = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->statement = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1491 "./SysYFParser.cpp" + break; + + case 50: // Stmt: IfStmt +#line 392 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1499 "./SysYFParser.cpp" + break; + + case 51: // Stmt: BREAK SEMICOLON +#line 395 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::BreakStmt()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1508 "./SysYFParser.cpp" + break; + + case 52: // Stmt: CONTINUE SEMICOLON +#line 399 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::ContinueStmt()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1517 "./SysYFParser.cpp" + break; + + case 53: // Stmt: SEMICOLON +#line 403 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::EmptyStmt()); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1526 "./SysYFParser.cpp" + break; + + case 54: // IfStmt: IF LPARENTHESE CondExp RPARENTHESE Stmt +#line 409 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::IfStmt()); + temp->cond_exp = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->if_statement = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + temp->else_statement = nullptr; + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1539 "./SysYFParser.cpp" + break; + + case 55: // IfStmt: IF LPARENTHESE CondExp RPARENTHESE Stmt ELSE Stmt +#line 417 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::IfStmt()); + temp->cond_exp = SysYF::Ptr(yystack_[4].value.as < SysYF::Ptr > ()); + temp->if_statement = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->else_statement = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1552 "./SysYFParser.cpp" + break; + + case 56: // OptionRet: Exp +#line 427 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1560 "./SysYFParser.cpp" + break; + + case 57: // OptionRet: %empty +#line 430 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = nullptr; + } +#line 1568 "./SysYFParser.cpp" + break; + + case 58: // LVal: IDENTIFIER ArrayExpList +#line 435 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::LVal()); + yylhs.value.as < SysYF::Ptr > ()->name = yystack_[1].value.as < std::string > (); + yylhs.value.as < SysYF::Ptr > ()->array_index = yystack_[0].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1579 "./SysYFParser.cpp" + break; + + case 59: // Exp: PLUS Exp +#line 447 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::UnaryExpr()); + temp->op = SysYF::SyntaxTree::UnaryOp::PLUS; + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1591 "./SysYFParser.cpp" + break; + + case 60: // Exp: MINUS Exp +#line 454 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::UnaryExpr()); + temp->op = SysYF::SyntaxTree::UnaryOp::MINUS; + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1603 "./SysYFParser.cpp" + break; + + case 61: // Exp: NOT Exp +#line 461 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::UnaryCondExpr()); + temp->op = SysYF::SyntaxTree::UnaryCondOp::NOT; + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1615 "./SysYFParser.cpp" + break; + + case 62: // Exp: Exp PLUS Exp +#line 468 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryExpr()); + temp->op = SysYF::SyntaxTree::BinOp::PLUS; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1628 "./SysYFParser.cpp" + break; + + case 63: // Exp: Exp MINUS Exp +#line 476 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryExpr()); + temp->op = SysYF::SyntaxTree::BinOp::MINUS; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1641 "./SysYFParser.cpp" + break; + + case 64: // Exp: Exp MULTIPLY Exp +#line 484 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryExpr()); + temp->op = SysYF::SyntaxTree::BinOp::MULTIPLY; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1654 "./SysYFParser.cpp" + break; + + case 65: // Exp: Exp DIVIDE Exp +#line 492 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryExpr()); + temp->op = SysYF::SyntaxTree::BinOp::DIVIDE; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1667 "./SysYFParser.cpp" + break; + + case 66: // Exp: Exp MODULO Exp +#line 500 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryExpr()); + temp->op = SysYF::SyntaxTree::BinOp::MODULO; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1680 "./SysYFParser.cpp" + break; + + case 67: // Exp: LPARENTHESE Exp RPARENTHESE +#line 508 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[1].value.as < SysYF::Ptr > (); + } +#line 1688 "./SysYFParser.cpp" + break; + + case 68: // Exp: IDENTIFIER LPARENTHESE ExpList RPARENTHESE +#line 511 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::FuncCallStmt()); + temp->name = yystack_[3].value.as < std::string > (); + temp->params = yystack_[1].value.as < SysYF::PtrVec > (); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1700 "./SysYFParser.cpp" + break; + + case 69: // Exp: LVal +#line 518 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1708 "./SysYFParser.cpp" + break; + + case 70: // Exp: Number +#line 521 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1716 "./SysYFParser.cpp" + break; + + case 71: // RelExp: RelExp LT Exp +#line 526 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::LT; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1729 "./SysYFParser.cpp" + break; + + case 72: // RelExp: RelExp LTE Exp +#line 534 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::LTE; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1742 "./SysYFParser.cpp" + break; + + case 73: // RelExp: RelExp GT Exp +#line 542 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::GT; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1755 "./SysYFParser.cpp" + break; + + case 74: // RelExp: RelExp GTE Exp +#line 550 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::GTE; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1768 "./SysYFParser.cpp" + break; + + case 75: // RelExp: Exp +#line 558 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1776 "./SysYFParser.cpp" + break; + + case 76: // EqExp: EqExp EQ RelExp +#line 563 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::EQ; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1789 "./SysYFParser.cpp" + break; + + case 77: // EqExp: EqExp NEQ RelExp +#line 571 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::NEQ; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1802 "./SysYFParser.cpp" + break; + + case 78: // EqExp: RelExp +#line 579 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1810 "./SysYFParser.cpp" + break; + + case 79: // LAndExp: LAndExp LOGICAND EqExp +#line 584 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::LAND; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1823 "./SysYFParser.cpp" + break; + + case 80: // LAndExp: EqExp +#line 592 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1831 "./SysYFParser.cpp" + break; + + case 81: // LOrExp: LOrExp LOGICOR LAndExp +#line 597 "../../grammar/SysYFParser.yy" + { + auto temp = SysYF::Ptr(new SysYF::SyntaxTree::BinaryCondExpr()); + temp->op = SysYF::SyntaxTree::BinaryCondOp::LOR; + temp->lhs = SysYF::Ptr(yystack_[2].value.as < SysYF::Ptr > ()); + temp->rhs = SysYF::Ptr(yystack_[0].value.as < SysYF::Ptr > ()); + yylhs.value.as < SysYF::Ptr > () = temp; + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1844 "./SysYFParser.cpp" + break; + + case 82: // LOrExp: LAndExp +#line 605 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1852 "./SysYFParser.cpp" + break; + + case 83: // CondExp: LOrExp +#line 610 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = yystack_[0].value.as < SysYF::Ptr > (); + } +#line 1860 "./SysYFParser.cpp" + break; + + case 84: // Number: INTCONST +#line 615 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::Literal()); + yylhs.value.as < SysYF::Ptr > ()->literal_type = SysYF::SyntaxTree::Type::INT; + yylhs.value.as < SysYF::Ptr > ()->int_const = yystack_[0].value.as < int > (); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1871 "./SysYFParser.cpp" + break; + + case 85: // Number: FLOATCONST +#line 621 "../../grammar/SysYFParser.yy" + { + yylhs.value.as < SysYF::Ptr > () = SysYF::Ptr(new SysYF::SyntaxTree::Literal()); + yylhs.value.as < SysYF::Ptr > ()->literal_type = SysYF::SyntaxTree::Type::FLOAT; + yylhs.value.as < SysYF::Ptr > ()->float_const = yystack_[0].value.as < float > (); + yylhs.value.as < SysYF::Ptr > ()->loc = yylhs.location; + } +#line 1882 "./SysYFParser.cpp" + break; + + +#line 1886 "./SysYFParser.cpp" + + default: + break; + } + } +#if YY_EXCEPTIONS + catch (const syntax_error& yyexc) + { + YYCDEBUG << "Caught exception: " << yyexc.what() << '\n'; + error (yyexc); + YYERROR; + } +#endif // YY_EXCEPTIONS + YY_SYMBOL_PRINT ("-> $$ =", yylhs); + yypop_ (yylen); + yylen = 0; + + // Shift the result of the reduction. + yypush_ (YY_NULLPTR, YY_MOVE (yylhs)); + } + goto yynewstate; + + + /*--------------------------------------. + | yyerrlab -- here on detecting error. | + `--------------------------------------*/ + yyerrlab: + // If not already recovering from an error, report this error. + if (!yyerrstatus_) + { + ++yynerrs_; + context yyctx (*this, yyla); + std::string msg = yysyntax_error_ (yyctx); + error (yyla.location, YY_MOVE (msg)); + } + + + yyerror_range[1].location = yyla.location; + if (yyerrstatus_ == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + // Return failure if at end of input. + if (yyla.kind () == symbol_kind::S_YYEOF) + YYABORT; + else if (!yyla.empty ()) + { + yy_destroy_ ("Error: discarding", yyla); + yyla.clear (); + } + } + + // Else will try to reuse lookahead token after shifting the error token. + goto yyerrlab1; + + + /*---------------------------------------------------. + | yyerrorlab -- error raised explicitly by YYERROR. | + `---------------------------------------------------*/ + yyerrorlab: + /* Pacify compilers when the user code never invokes YYERROR and + the label yyerrorlab therefore never appears in user code. */ + if (false) + YYERROR; + + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + yypop_ (yylen); + yylen = 0; + YY_STACK_PRINT (); + goto yyerrlab1; + + + /*-------------------------------------------------------------. + | yyerrlab1 -- common code for both syntax error and YYERROR. | + `-------------------------------------------------------------*/ + yyerrlab1: + yyerrstatus_ = 3; // Each real token shifted decrements this. + // Pop stack until we find a state that shifts the error token. + for (;;) + { + yyn = yypact_[+yystack_[0].state]; + if (!yy_pact_value_is_default_ (yyn)) + { + yyn += symbol_kind::S_YYerror; + if (0 <= yyn && yyn <= yylast_ + && yycheck_[yyn] == symbol_kind::S_YYerror) + { + yyn = yytable_[yyn]; + if (0 < yyn) + break; + } + } + + // Pop the current state because it cannot handle the error token. + if (yystack_.size () == 1) + YYABORT; + + yyerror_range[1].location = yystack_[0].location; + yy_destroy_ ("Error: popping", yystack_[0]); + yypop_ (); + YY_STACK_PRINT (); + } + { + stack_symbol_type error_token; + + yyerror_range[2].location = yyla.location; + YYLLOC_DEFAULT (error_token.location, yyerror_range, 2); + + // Shift the error token. + error_token.state = state_type (yyn); + yypush_ ("Shifting", YY_MOVE (error_token)); + } + goto yynewstate; + + + /*-------------------------------------. + | yyacceptlab -- YYACCEPT comes here. | + `-------------------------------------*/ + yyacceptlab: + yyresult = 0; + goto yyreturn; + + + /*-----------------------------------. + | yyabortlab -- YYABORT comes here. | + `-----------------------------------*/ + yyabortlab: + yyresult = 1; + goto yyreturn; + + + /*-----------------------------------------------------. + | yyreturn -- parsing is finished, return the result. | + `-----------------------------------------------------*/ + yyreturn: + if (!yyla.empty ()) + yy_destroy_ ("Cleanup: discarding lookahead", yyla); + + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + yypop_ (yylen); + YY_STACK_PRINT (); + while (1 < yystack_.size ()) + { + yy_destroy_ ("Cleanup: popping", yystack_[0]); + yypop_ (); + } + + return yyresult; + } +#if YY_EXCEPTIONS + catch (...) + { + YYCDEBUG << "Exception caught: cleaning lookahead and stack\n"; + // Do not try to display the values of the reclaimed symbols, + // as their printers might throw an exception. + if (!yyla.empty ()) + yy_destroy_ (YY_NULLPTR, yyla); + + while (1 < yystack_.size ()) + { + yy_destroy_ (YY_NULLPTR, yystack_[0]); + yypop_ (); + } + throw; + } +#endif // YY_EXCEPTIONS + } + + void + SysYFParser::error (const syntax_error& yyexc) + { + error (yyexc.location, yyexc.what ()); + } + + /* Return YYSTR after stripping away unnecessary quotes and + backslashes, so that it's suitable for yyerror. The heuristic is + that double-quoting is unnecessary unless the string contains an + apostrophe, a comma, or backslash (other than backslash-backslash). + YYSTR is taken from yytname. */ + std::string + SysYFParser::yytnamerr_ (const char *yystr) + { + if (*yystr == '"') + { + std::string yyr; + char const *yyp = yystr; + + for (;;) + switch (*++yyp) + { + case '\'': + case ',': + goto do_not_strip_quotes; + + case '\\': + if (*++yyp != '\\') + goto do_not_strip_quotes; + else + goto append; + + append: + default: + yyr += *yyp; + break; + + case '"': + return yyr; + } + do_not_strip_quotes: ; + } + + return yystr; + } + + std::string + SysYFParser::symbol_name (symbol_kind_type yysymbol) + { + return yytnamerr_ (yytname_[yysymbol]); + } + + + + // SysYFParser::context. + SysYFParser::context::context (const SysYFParser& yyparser, const symbol_type& yyla) + : yyparser_ (yyparser) + , yyla_ (yyla) + {} + + int + SysYFParser::context::expected_tokens (symbol_kind_type yyarg[], int yyargn) const + { + // Actual number of expected tokens + int yycount = 0; + + const int yyn = yypact_[+yyparser_.yystack_[0].state]; + if (!yy_pact_value_is_default_ (yyn)) + { + /* Start YYX at -YYN if negative to avoid negative indexes in + YYCHECK. In other words, skip the first -YYN actions for + this state because they are default actions. */ + const int yyxbegin = yyn < 0 ? -yyn : 0; + // Stay within bounds of both yycheck and yytname. + const int yychecklim = yylast_ - yyn + 1; + const int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; + for (int yyx = yyxbegin; yyx < yyxend; ++yyx) + if (yycheck_[yyx + yyn] == yyx && yyx != symbol_kind::S_YYerror + && !yy_table_value_is_error_ (yytable_[yyx + yyn])) + { + if (!yyarg) + ++yycount; + else if (yycount == yyargn) + return 0; + else + yyarg[yycount++] = YY_CAST (symbol_kind_type, yyx); + } + } + + if (yyarg && yycount == 0 && 0 < yyargn) + yyarg[0] = symbol_kind::S_YYEMPTY; + return yycount; + } + + + + + + + int + SysYFParser::yy_syntax_error_arguments_ (const context& yyctx, + symbol_kind_type yyarg[], int yyargn) const + { + /* There are many possibilities here to consider: + - If this state is a consistent state with a default action, then + the only way this function was invoked is if the default action + is an error action. In that case, don't check for expected + tokens because there are none. + - The only way there can be no lookahead present (in yyla) is + if this state is a consistent state with a default action. + Thus, detecting the absence of a lookahead is sufficient to + determine that there is no unexpected or expected token to + report. In that case, just report a simple "syntax error". + - Don't assume there isn't a lookahead just because this state is + a consistent state with a default action. There might have + been a previous inconsistent state, consistent state with a + non-default action, or user semantic action that manipulated + yyla. (However, yyla is currently not documented for users.) + - Of course, the expected token list depends on states to have + correct lookahead information, and it depends on the parser not + to perform extra reductions after fetching a lookahead from the + scanner and before detecting a syntax error. Thus, state merging + (from LALR or IELR) and default reductions corrupt the expected + token list. However, the list is correct for canonical LR with + one exception: it will still contain any token that will not be + accepted due to an error action in a later state. + */ + + if (!yyctx.lookahead ().empty ()) + { + if (yyarg) + yyarg[0] = yyctx.token (); + int yyn = yyctx.expected_tokens (yyarg ? yyarg + 1 : yyarg, yyargn - 1); + return yyn + 1; + } + return 0; + } + + // Generate an error message. + std::string + SysYFParser::yysyntax_error_ (const context& yyctx) const + { + // Its maximum. + enum { YYARGS_MAX = 5 }; + // Arguments of yyformat. + symbol_kind_type yyarg[YYARGS_MAX]; + int yycount = yy_syntax_error_arguments_ (yyctx, yyarg, YYARGS_MAX); + + char const* yyformat = YY_NULLPTR; + switch (yycount) + { +#define YYCASE_(N, S) \ + case N: \ + yyformat = S; \ + break + default: // Avoid compiler warnings. + YYCASE_ (0, YY_("syntax error")); + YYCASE_ (1, YY_("syntax error, unexpected %s")); + YYCASE_ (2, YY_("syntax error, unexpected %s, expecting %s")); + YYCASE_ (3, YY_("syntax error, unexpected %s, expecting %s or %s")); + YYCASE_ (4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); + YYCASE_ (5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); +#undef YYCASE_ + } + + std::string yyres; + // Argument number. + std::ptrdiff_t yyi = 0; + for (char const* yyp = yyformat; *yyp; ++yyp) + if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount) + { + yyres += symbol_name (yyarg[yyi++]); + ++yyp; + } + else + yyres += *yyp; + return yyres; + } + + + const signed char SysYFParser::yypact_ninf_ = -116; + + const signed char SysYFParser::yytable_ninf_ = -35; + + const short + SysYFParser::yypact_[] = + { + -8, -116, -25, -18, -116, 9, 20, -116, -116, -3, + -116, -116, -5, 5, -116, -116, -116, 27, 136, -116, + 28, -116, 138, -116, 28, 10, -116, 30, 39, -18, + 29, -116, 5, 46, 116, 119, -116, -116, 52, 48, + 63, 116, -116, 52, 119, 119, 119, 62, 71, -116, + -116, 119, -116, -116, 172, -116, 47, -116, -116, 55, + -116, -116, -116, -116, -116, 155, 85, 116, 95, 96, + -116, 119, 119, 119, 119, 119, -116, 61, -116, 96, + -116, -116, 110, 99, 119, 135, 135, -116, -116, -116, + -116, -116, 111, 119, 127, 154, 156, -116, 30, -116, + -116, -116, -116, -116, 158, 104, 96, -116, -116, 64, + 119, 159, 172, 119, -116, -116, 119, -116, -116, 172, + 4, 122, 126, 137, 163, -116, 165, 160, 119, 119, + 119, 119, 119, 119, 119, 119, 101, 101, -116, 172, + 172, 172, 172, 4, 4, 122, 126, 161, -116, 101, + -116 + }; + + const signed char + SysYFParser::yydefact_[] = + { + 0, 11, 0, 0, 12, 0, 0, 4, 5, 0, + 6, 7, 0, 0, 1, 2, 3, 20, 0, 16, + 36, 20, 0, 10, 36, 17, 14, 0, 0, 0, + 0, 8, 0, 0, 0, 0, 20, 15, 0, 0, + 33, 0, 9, 0, 0, 0, 0, 26, 20, 85, + 84, 0, 18, 69, 21, 70, 0, 41, 38, 20, + 35, 13, 37, 59, 60, 0, 0, 0, 30, 58, + 61, 0, 0, 0, 0, 0, 19, 0, 20, 31, + 67, 22, 23, 0, 0, 62, 63, 64, 65, 66, + 53, 39, 0, 57, 0, 0, 0, 43, 0, 42, + 48, 40, 44, 50, 69, 0, 32, 25, 68, 27, + 0, 0, 56, 0, 51, 52, 0, 46, 29, 75, + 78, 80, 82, 83, 0, 47, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 45, 72, + 73, 74, 71, 76, 77, 79, 81, 54, 49, 0, + 55 + }; + + const short + SysYFParser::yypgoto_[] = + { + -116, -116, -116, 180, 112, -116, -1, 162, 113, -116, + 164, -17, -35, -116, -116, -116, -116, -116, 168, -116, + -116, -19, -116, -116, -115, -116, -116, -74, -34, 25, + 53, 58, -116, 75, -116 + }; + + const signed char + SysYFParser::yydefgoto_[] = + { + 0, 5, 6, 7, 8, 22, 9, 23, 10, 18, + 19, 25, 52, 66, 67, 83, 84, 40, 28, 29, + 11, 100, 77, 101, 102, 103, 111, 53, 119, 120, + 121, 122, 123, 124, 55 + }; + + const short + SysYFParser::yytable_[] = + { + 54, 56, 13, 104, 30, 12, 61, 54, 1, 14, + 63, 64, 65, 20, 128, 129, 130, 70, 1, 58, + 2, 147, 148, 15, 62, 34, 4, 17, 39, 3, + 35, 69, 82, 54, 150, 21, 4, 85, 86, 87, + 88, 89, 79, 105, 41, 24, 1, -34, 2, 35, + 109, 131, 71, 72, 73, 74, 75, 3, 38, 112, + 36, 106, 104, 104, 4, 43, 44, 45, 76, 71, + 72, 73, 74, 75, 57, 104, 98, 90, 59, 46, + 60, 118, 127, 57, 91, -24, 92, 1, 93, 68, + 94, 48, 49, 50, 139, 140, 141, 142, 3, 95, + 96, 51, 105, 105, 78, 4, 44, 45, 81, 71, + 72, 73, 74, 75, -28, 105, 35, 90, 108, 46, + 117, 44, 45, 57, 44, 45, 92, 107, 93, 110, + 94, 48, 49, 50, 46, 132, 133, 46, 47, 95, + 96, 51, 73, 74, 75, 113, 48, 49, 50, 48, + 49, 50, 26, 27, 31, 32, 51, 143, 144, 51, + 71, 72, 73, 74, 75, 71, 72, 73, 74, 75, + 114, 134, 115, 116, 80, 125, 138, 71, 72, 73, + 74, 75, 136, 135, 137, 149, 16, 145, 126, 97, + 99, 37, 33, 146, 42 + }; + + const unsigned char + SysYFParser::yycheck_[] = + { + 34, 35, 3, 77, 21, 30, 41, 41, 26, 0, + 44, 45, 46, 18, 10, 11, 12, 51, 26, 38, + 28, 136, 137, 3, 43, 15, 44, 30, 29, 37, + 20, 48, 67, 67, 149, 30, 44, 71, 72, 73, + 74, 75, 59, 77, 15, 18, 26, 19, 28, 20, + 84, 47, 5, 6, 7, 8, 9, 37, 19, 93, + 30, 78, 136, 137, 44, 19, 5, 6, 21, 5, + 6, 7, 8, 9, 22, 149, 77, 16, 30, 18, + 17, 17, 116, 22, 23, 23, 25, 26, 27, 18, + 29, 30, 31, 32, 128, 129, 130, 131, 37, 38, + 39, 40, 136, 137, 49, 44, 5, 6, 23, 5, + 6, 7, 8, 9, 19, 149, 20, 16, 19, 18, + 16, 5, 6, 22, 5, 6, 25, 17, 27, 18, + 29, 30, 31, 32, 18, 13, 14, 18, 22, 38, + 39, 40, 7, 8, 9, 18, 30, 31, 32, 30, + 31, 32, 16, 17, 16, 17, 40, 132, 133, 40, + 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, + 16, 45, 16, 15, 19, 16, 16, 5, 6, 7, + 8, 9, 19, 46, 19, 24, 6, 134, 113, 77, + 77, 27, 24, 135, 32 + }; + + const signed char + SysYFParser::yystos_[] = + { + 0, 26, 28, 37, 44, 54, 55, 56, 57, 59, + 61, 73, 30, 59, 0, 3, 56, 30, 62, 63, + 18, 30, 58, 60, 18, 64, 16, 17, 71, 72, + 64, 16, 17, 71, 15, 20, 30, 63, 19, 59, + 70, 15, 60, 19, 5, 6, 18, 22, 30, 31, + 32, 40, 65, 80, 81, 87, 81, 22, 74, 30, + 17, 65, 74, 81, 81, 81, 66, 67, 18, 64, + 81, 5, 6, 7, 8, 9, 21, 75, 49, 64, + 19, 23, 65, 68, 69, 81, 81, 81, 81, 81, + 16, 23, 25, 27, 29, 38, 39, 57, 59, 61, + 74, 76, 77, 78, 80, 81, 64, 17, 19, 81, + 18, 79, 81, 18, 16, 16, 15, 16, 17, 81, + 82, 83, 84, 85, 86, 16, 86, 81, 10, 11, + 12, 47, 13, 14, 45, 46, 19, 19, 16, 81, + 81, 81, 81, 82, 82, 83, 84, 77, 77, 24, + 77 + }; + + const signed char + SysYFParser::yyr1_[] = + { + 0, 53, 54, 55, 55, 56, 56, 56, 57, 58, + 58, 59, 59, 60, 61, 62, 62, 63, 63, 64, + 64, 65, 65, 66, 66, 67, 67, 68, 68, 69, + 69, 70, 70, 71, 71, 72, 72, 73, 73, 74, + 75, 75, 76, 76, 76, 77, 77, 77, 77, 77, + 77, 77, 77, 77, 78, 78, 79, 79, 80, 81, + 81, 81, 81, 81, 81, 81, 81, 81, 81, 81, + 81, 82, 82, 82, 82, 82, 83, 83, 83, 84, + 84, 85, 85, 86, 87, 87 + }; + + const signed char + SysYFParser::yyr2_[] = + { + 0, 2, 2, 2, 1, 1, 1, 1, 4, 3, + 1, 1, 1, 4, 3, 3, 1, 2, 4, 4, + 0, 1, 3, 2, 0, 3, 0, 2, 0, 3, + 0, 3, 4, 2, 0, 3, 0, 6, 6, 3, + 2, 0, 1, 1, 1, 4, 2, 3, 1, 5, + 1, 2, 2, 1, 5, 7, 1, 0, 2, 2, + 2, 2, 3, 3, 3, 3, 3, 3, 4, 1, + 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, + 1, 3, 1, 1, 1, 1 + }; + + +#if YYDEBUG || 1 + // YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + // First, the terminals, then, starting at \a YYNTOKENS, nonterminals. + const char* + const SysYFParser::yytname_[] = + { + "\"end of file\"", "error", "\"invalid token\"", "END", "ERROR", "PLUS", + "MINUS", "MULTIPLY", "DIVIDE", "MODULO", "LTE", "GT", "GTE", "EQ", "NEQ", + "ASSIGN", "SEMICOLON", "COMMA", "LPARENTHESE", "RPARENTHESE", "LBRACKET", + "RBRACKET", "LBRACE", "RBRACE", "ELSE", "IF", "INT", "RETURN", "VOID", + "WHILE", "IDENTIFIER", "FLOATCONST", "INTCONST", "LETTER", "EOL", + "COMMENT", "BLANK", "CONST", "BREAK", "CONTINUE", "NOT", "AND", "OR", + "MOD", "FLOAT", "LOGICAND", "LOGICOR", "LT", "STRINGCONST", "LRBRACKET", + "UPLUS", "UMINUS", "UNOT", "$accept", "Begin", "CompUnit", "GlobalDecl", + "ConstDecl", "ConstDefList", "BType", "ConstDef", "VarDecl", + "VarDefList", "VarDef", "ArrayExpList", "InitVal", "InitValList", + "CommaInitValList", "ExpList", "CommaExpList", "FuncFParam", + "FParamList", "CommaFParamList", "FuncDef", "Block", "BlockItemList", + "BlockItem", "Stmt", "IfStmt", "OptionRet", "LVal", "Exp", "RelExp", + "EqExp", "LAndExp", "LOrExp", "CondExp", "Number", YY_NULLPTR + }; +#endif + + +#if YYDEBUG + const short + SysYFParser::yyrline_[] = + { + 0, 106, 106, 113, 117, 123, 127, 131, 137, 144, + 148, 154, 157, 163, 174, 182, 186, 192, 199, 209, + 213, 218, 225, 230, 234, 244, 248, 258, 262, 267, + 271, 277, 284, 294, 298, 303, 307, 311, 321, 333, + 340, 344, 349, 353, 357, 363, 370, 376, 382, 385, + 392, 395, 399, 403, 409, 417, 427, 430, 435, 447, + 454, 461, 468, 476, 484, 492, 500, 508, 511, 518, + 521, 526, 534, 542, 550, 558, 563, 571, 579, 584, + 592, 597, 605, 610, 615, 621 + }; + + void + SysYFParser::yy_stack_print_ () const + { + *yycdebug_ << "Stack now"; + for (stack_type::const_iterator + i = yystack_.begin (), + i_end = yystack_.end (); + i != i_end; ++i) + *yycdebug_ << ' ' << int (i->state); + *yycdebug_ << '\n'; + } + + void + SysYFParser::yy_reduce_print_ (int yyrule) const + { + int yylno = yyrline_[yyrule]; + int yynrhs = yyr2_[yyrule]; + // Print the symbols being reduced, and their result. + *yycdebug_ << "Reducing stack by rule " << yyrule - 1 + << " (line " << yylno << "):\n"; + // The symbols being reduced. + for (int yyi = 0; yyi < yynrhs; yyi++) + YY_SYMBOL_PRINT (" $" << yyi + 1 << " =", + yystack_[(yynrhs) - (yyi + 1)]); + } +#endif // YYDEBUG + + +} // yy +#line 2470 "./SysYFParser.cpp" + +#line 629 "../../grammar/SysYFParser.yy" + + +// Register errors to the driver: +void yy::SysYFParser::error (const location_type& l, + const std::string& m) +{ + driver.error(l, m); +} diff --git a/src/Frontend/SysYFScanner.cpp b/src/Frontend/SysYFScanner.cpp new file mode 100644 index 0000000..9a3018d --- /dev/null +++ b/src/Frontend/SysYFScanner.cpp @@ -0,0 +1,2339 @@ +#line 2 "./SysYFScanner.cpp" + +#line 4 "./SysYFScanner.cpp" + +#define YY_INT_ALIGNED short int + +/* A lexical scanner generated by flex */ + +/* %not-for-header */ +/* %if-c-only */ +/* %if-not-reentrant */ +/* %endif */ +/* %endif */ +/* %ok-for-header */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 4 +#if YY_FLEX_SUBMINOR_VERSION > 0 +#define FLEX_BETA +#endif + +/* %if-c++-only */ + /* The c++ scanner is a mess. The FlexLexer.h header file relies on the + * following macro. This is required in order to pass the c++-multiple-scanners + * test in the regression suite. We get reports that it breaks inheritance. + * We will address this in a future release of flex, or omit the C++ scanner + * altogether. + */ + #define yyFlexLexer yyFlexLexer +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* First, we deal with platform-specific or compiler-specific issues. */ + +/* begin standard C headers. */ +/* %if-c-only */ +/* %endif */ + +/* %if-tables-serialization */ +/* %endif */ +/* end standard C headers. */ + +/* %if-c-or-c++ */ +/* flex integer type definitions */ + +#ifndef FLEXINT_H +#define FLEXINT_H + +/* C99 systems have . Non-C99 systems may or may not. */ + +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + +/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, + * if you want the limit (max/min) macros for int types. + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS 1 +#endif + +#include +typedef int8_t flex_int8_t; +typedef uint8_t flex_uint8_t; +typedef int16_t flex_int16_t; +typedef uint16_t flex_uint16_t; +typedef int32_t flex_int32_t; +typedef uint32_t flex_uint32_t; +#else +typedef signed char flex_int8_t; +typedef short int flex_int16_t; +typedef int flex_int32_t; +typedef unsigned char flex_uint8_t; +typedef unsigned short int flex_uint16_t; +typedef unsigned int flex_uint32_t; + +/* Limits of integral types. */ +#ifndef INT8_MIN +#define INT8_MIN (-128) +#endif +#ifndef INT16_MIN +#define INT16_MIN (-32767-1) +#endif +#ifndef INT32_MIN +#define INT32_MIN (-2147483647-1) +#endif +#ifndef INT8_MAX +#define INT8_MAX (127) +#endif +#ifndef INT16_MAX +#define INT16_MAX (32767) +#endif +#ifndef INT32_MAX +#define INT32_MAX (2147483647) +#endif +#ifndef UINT8_MAX +#define UINT8_MAX (255U) +#endif +#ifndef UINT16_MAX +#define UINT16_MAX (65535U) +#endif +#ifndef UINT32_MAX +#define UINT32_MAX (4294967295U) +#endif + +#ifndef SIZE_MAX +#define SIZE_MAX (~(size_t)0) +#endif + +#endif /* ! C99 */ + +#endif /* ! FLEXINT_H */ + +/* %endif */ + +/* begin standard C++ headers. */ +/* %if-c++-only */ +#include +#include +#include +#include +#include +/* end standard C++ headers. */ +/* %endif */ + +/* TODO: this is always defined, so inline it */ +#define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) +#else +#define yynoreturn +#endif + +/* %not-for-header */ +/* Returned upon end-of-file. */ +#define YY_NULL 0 +/* %ok-for-header */ + +/* %not-for-header */ +/* Promotes a possibly negative, possibly signed char to an + * integer in range [0..255] for use as an array index. + */ +#define YY_SC_TO_UI(c) ((YY_CHAR) (c)) +/* %ok-for-header */ + +/* %if-reentrant */ +/* %endif */ + +/* %if-not-reentrant */ + +/* %endif */ + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN (yy_start) = 1 + 2 * +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START (((yy_start) - 1) / 2) +#define YYSTATE YY_START +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE yyrestart( yyin ) +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else +#define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ +#endif + +/* The state buf must be large enough to hold one state per character in the main buffer. + */ +#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) + +#ifndef YY_TYPEDEF_YY_BUFFER_STATE +#define YY_TYPEDEF_YY_BUFFER_STATE +typedef struct yy_buffer_state *YY_BUFFER_STATE; +#endif + +#ifndef YY_TYPEDEF_YY_SIZE_T +#define YY_TYPEDEF_YY_SIZE_T +typedef size_t yy_size_t; +#endif + +/* %if-not-reentrant */ +extern int yyleng; +/* %endif */ + +/* %if-c-only */ +/* %if-not-reentrant */ +/* %endif */ +/* %endif */ + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) + +/* Return all but the first "n" matched characters back to the input stream. */ +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + *yy_cp = (yy_hold_char); \ + YY_RESTORE_YY_MORE_OFFSET \ + (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) +#define unput(c) yyunput( c, (yytext_ptr) ) + +#ifndef YY_STRUCT_YY_BUFFER_STATE +#define YY_STRUCT_YY_BUFFER_STATE +struct yy_buffer_state + { +/* %if-c-only */ +/* %endif */ + +/* %if-c++-only */ + std::streambuf* yy_input_file; +/* %endif */ + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + int yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + int yy_bs_lineno; /**< The line count. */ + int yy_bs_column; /**< The column count. */ + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; + +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + + }; +#endif /* !YY_STRUCT_YY_BUFFER_STATE */ + +/* %if-c-only Standard (non-C++) definition */ +/* %not-for-header */ +/* %if-not-reentrant */ +/* %endif */ +/* %ok-for-header */ + +/* %endif */ + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + * + * Returns the top of the stack, or NULL. + */ +#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ + ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ + : NULL) +/* Same as previous macro, but useful when we know that the buffer stack is not + * NULL or when we need an lvalue. For internal use only. + */ +#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] + +/* %if-c-only Standard (non-C++) definition */ +/* %if-not-reentrant */ +/* %not-for-header */ +/* %ok-for-header */ + +/* %endif */ +/* %endif */ + +void *yyalloc ( yy_size_t ); +void *yyrealloc ( void *, yy_size_t ); +void yyfree ( void * ); + +#define yy_new_buffer yy_create_buffer +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! YY_CURRENT_BUFFER ){ \ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ + } +#define yy_set_bol(at_bol) \ + { \ + if ( ! YY_CURRENT_BUFFER ){\ + yyensure_buffer_stack (); \ + YY_CURRENT_BUFFER_LVALUE = \ + yy_create_buffer( yyin, YY_BUF_SIZE ); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ + } +#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) + +/* %% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here */ +/* Begin user sect3 */ +#define YY_SKIP_YYWRAP + +#define FLEX_DEBUG +typedef flex_uint8_t YY_CHAR; + +#define yytext_ptr yytext + +#include + +int yyFlexLexer::yywrap() { return 1; } + +/* %% [1.5] DFA */ + +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + (yytext_ptr) = yy_bp; \ +/* %% [2.0] code to fiddle yytext and yyleng for yymore() goes here \ */\ + yyleng = (int) (yy_cp - yy_bp); \ + (yy_hold_char) = *yy_cp; \ + *yy_cp = '\0'; \ +/* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\ + (yy_c_buf_p) = yy_cp; +/* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */ +#define YY_NUM_RULES 45 +#define YY_END_OF_BUFFER 46 +/* This struct is not used in this scanner, + but its presence is necessary. */ +struct yy_trans_info + { + flex_int32_t yy_verify; + flex_int32_t yy_nxt; + }; +static const flex_int16_t yy_accept[113] = + { 0, + 0, 0, 46, 44, 35, 36, 17, 24, 44, 28, + 29, 22, 20, 27, 21, 44, 23, 41, 39, 26, + 11, 25, 13, 42, 30, 31, 42, 42, 42, 42, + 42, 42, 42, 42, 32, 44, 33, 35, 36, 16, + 18, 43, 0, 0, 43, 41, 0, 0, 0, 39, + 12, 15, 14, 42, 0, 0, 34, 42, 42, 42, + 42, 9, 42, 42, 42, 42, 19, 0, 0, 0, + 0, 0, 38, 0, 43, 40, 0, 0, 42, 42, + 42, 42, 2, 42, 42, 42, 0, 43, 37, 0, + 0, 0, 0, 42, 42, 42, 10, 42, 42, 4, + + 42, 6, 5, 42, 1, 42, 8, 42, 3, 42, + 7, 0 + } ; + +static const YY_CHAR yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 5, 1, 1, 1, 6, 7, 1, 8, + 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, + 17, 17, 17, 17, 17, 18, 18, 1, 19, 20, + 21, 22, 1, 1, 23, 23, 23, 23, 24, 23, + 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, + 25, 25, 25, 25, 25, 25, 25, 26, 25, 25, + 27, 1, 28, 1, 25, 1, 29, 30, 31, 32, + + 33, 34, 25, 35, 36, 25, 37, 38, 25, 39, + 40, 25, 25, 41, 42, 43, 44, 45, 46, 26, + 25, 25, 47, 48, 49, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static const YY_CHAR yy_meta[50] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, + 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 1, 1, 1 + } ; + +static const flex_int16_t yy_base[121] = + { 0, + 0, 0, 222, 223, 48, 218, 199, 223, 212, 223, + 223, 223, 223, 223, 223, 37, 41, 43, 48, 223, + 197, 196, 195, 0, 71, 223, 174, 174, 175, 174, + 24, 178, 170, 174, 223, 160, 223, 66, 204, 223, + 223, 61, 72, 80, 72, 84, 95, 105, 0, 113, + 223, 223, 223, 0, 130, 82, 223, 173, 166, 162, + 163, 0, 159, 158, 164, 163, 223, 125, 100, 110, + 125, 100, 223, 131, 134, 0, 129, 103, 169, 111, + 164, 167, 0, 151, 162, 155, 139, 143, 223, 152, + 153, 154, 162, 155, 148, 154, 0, 83, 83, 0, + + 81, 0, 0, 56, 0, 54, 0, 47, 0, 47, + 0, 223, 168, 171, 174, 69, 177, 180, 183, 186 + } ; + +static const flex_int16_t yy_def[121] = + { 0, + 112, 1, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 113, 112, 112, 113, 113, 113, 113, + 113, 113, 113, 113, 112, 112, 112, 112, 112, 112, + 112, 112, 114, 115, 112, 112, 112, 112, 116, 112, + 112, 112, 112, 113, 112, 112, 112, 113, 113, 113, + 113, 113, 113, 113, 113, 113, 112, 112, 114, 117, + 114, 115, 112, 112, 112, 116, 118, 119, 113, 113, + 113, 113, 113, 113, 113, 113, 112, 112, 112, 118, + 120, 118, 119, 113, 113, 113, 113, 113, 113, 113, + + 113, 113, 113, 113, 113, 113, 113, 113, 113, 113, + 113, 0, 112, 112, 112, 112, 112, 112, 112, 112 + } ; + +static const flex_int16_t yy_nxt[273] = + { 0, + 4, 5, 6, 5, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, + 22, 23, 24, 24, 24, 24, 25, 26, 24, 27, + 28, 24, 29, 30, 24, 31, 24, 24, 24, 24, + 32, 24, 24, 24, 33, 34, 35, 36, 37, 38, + 43, 38, 42, 42, 42, 44, 45, 62, 46, 46, + 47, 45, 63, 50, 50, 50, 48, 38, 49, 38, + 76, 48, 55, 55, 55, 48, 42, 42, 42, 111, + 48, 70, 73, 73, 68, 56, 71, 42, 42, 42, + 110, 77, 109, 68, 108, 68, 78, 45, 57, 46, + + 46, 47, 73, 73, 68, 55, 55, 48, 45, 70, + 47, 47, 47, 107, 71, 74, 48, 74, 48, 70, + 75, 75, 75, 106, 89, 105, 45, 48, 50, 50, + 50, 55, 55, 55, 70, 87, 48, 87, 91, 71, + 88, 88, 88, 92, 56, 48, 75, 75, 75, 75, + 75, 75, 95, 96, 88, 88, 88, 57, 88, 88, + 88, 91, 91, 91, 55, 55, 92, 55, 92, 54, + 54, 69, 69, 69, 72, 72, 72, 71, 71, 71, + 90, 90, 90, 93, 93, 93, 92, 92, 92, 104, + 103, 102, 101, 100, 99, 98, 97, 94, 86, 85, + + 84, 83, 82, 81, 80, 79, 39, 67, 66, 65, + 64, 61, 60, 59, 58, 53, 52, 51, 41, 40, + 39, 112, 3, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112 + } ; + +static const flex_int16_t yy_chk[273] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, + 17, 5, 16, 16, 16, 17, 18, 31, 18, 18, + 18, 19, 31, 19, 19, 19, 18, 38, 18, 38, + 116, 19, 25, 25, 25, 18, 42, 42, 42, 110, + 19, 43, 44, 44, 42, 25, 43, 45, 45, 45, + 108, 56, 106, 42, 104, 45, 56, 46, 25, 46, + + 46, 46, 72, 72, 45, 78, 78, 46, 47, 69, + 47, 47, 47, 101, 69, 48, 46, 48, 47, 70, + 48, 48, 48, 99, 70, 98, 50, 47, 50, 50, + 50, 55, 55, 55, 71, 68, 50, 68, 77, 71, + 68, 68, 68, 77, 55, 50, 74, 74, 74, 75, + 75, 75, 80, 80, 87, 87, 87, 55, 88, 88, + 88, 90, 91, 92, 93, 93, 90, 91, 92, 113, + 113, 114, 114, 114, 115, 115, 115, 117, 117, 117, + 118, 118, 118, 119, 119, 119, 120, 120, 120, 96, + 95, 94, 86, 85, 84, 82, 81, 79, 66, 65, + + 64, 63, 61, 60, 59, 58, 39, 36, 34, 33, + 32, 30, 29, 28, 27, 23, 22, 21, 9, 7, + 6, 3, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, + 112, 112 + } ; + +static const flex_int16_t yy_rule_linenum[45] = + { 0, + 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, + 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, + 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, + 163, 164, 165, 168, 169, 170, 171, 174, 175, 183, + 191, 199, 200, 202 + } ; + +/* The intent behind this definition is that it'll catch + * any uses of REJECT which flex missed. + */ +#define REJECT reject_used_but_not_detected +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +#line 1 "../../grammar/SysYFScanner.ll" +#line 2 "../../grammar/SysYFScanner.ll" +# include +# include +# include +# include // strerror +# include +# include +# include +# include +std::map ch2int = { + {'0',0}, + {'1',1}, + {'2',2}, + {'3',3}, + {'4',4}, + {'5',5}, + {'6',6}, + {'7',7}, + {'8',8}, + {'9',9}, + {'a',10}, + {'b',11}, + {'c',12}, + {'d',13}, + {'e',14}, + {'f',15}, + {'A',10}, + {'B',11}, + {'C',12}, + {'D',13}, + {'E',14}, + {'F',15} +}; +# include "SysYFDriver.h" +# include "SysYFParser.h" +# define RET_NOTYPE_TOKEN(name) \ + auto mytoken = yy::SysYFParser::make_##name(loc);\ + loc.step();\ + return mytoken; + +# define RET_TYPE_TOKEN(name, value) \ + auto mytoken = yy::SysYFParser::make_##name(value, loc);\ + loc.step();\ + return mytoken; +#line 620 "./SysYFScanner.cpp" +#line 48 "../../grammar/SysYFScanner.ll" +#if defined __clang__ +# define CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#endif + +// Clang and ICC like to pretend they are GCC. +#if defined __GNUC__ && !defined __clang__ && !defined __ICC +# define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#endif + +// Pacify warnings in yy_init_buffer (observed with Flex 2.6.4) +// and GCC 6.4.0, 7.3.0 with -O3. +#if defined GCC_VERSION && 600 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wnull-dereference" +#endif + +// This code uses Flex's C backend, yet compiles it as C++. +// So expect warnings about C style casts and NULL. +#if defined CLANG_VERSION && 500 <= CLANG_VERSION +# pragma clang diagnostic ignored "-Wold-style-cast" +# pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#elif defined GCC_VERSION && 407 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wold-style-cast" +# pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" +#endif + +#define FLEX_VERSION (YY_FLEX_MAJOR_VERSION * 100 + YY_FLEX_MINOR_VERSION) + +// Old versions of Flex (2.5.35) generate an incomplete documentation comment. +// +// In file included from src/scan-code-c.c:3: +// src/scan-code.c:2198:21: error: empty paragraph passed to '@param' command +// [-Werror,-Wdocumentation] +// * @param line_number +// ~~~~~~~~~~~~~~~~~^ +// 1 error generated. +#if FLEX_VERSION < 206 && defined CLANG_VERSION +# pragma clang diagnostic ignored "-Wdocumentation" +#endif + +// Old versions of Flex (2.5.35) use 'register'. Warnings introduced in +// GCC 7 and Clang 6. +#if FLEX_VERSION < 206 +# if defined CLANG_VERSION && 600 <= CLANG_VERSION +# pragma clang diagnostic ignored "-Wdeprecated-register" +# elif defined GCC_VERSION && 700 <= GCC_VERSION +# pragma GCC diagnostic ignored "-Wregister" +# endif +#endif + +#if FLEX_VERSION < 206 +# if defined CLANG_VERSION +# pragma clang diagnostic ignored "-Wconversion" +# pragma clang diagnostic ignored "-Wdocumentation" +# pragma clang diagnostic ignored "-Wshorten-64-to-32" +# pragma clang diagnostic ignored "-Wsign-conversion" +# elif defined GCC_VERSION +# pragma GCC diagnostic ignored "-Wconversion" +# pragma GCC diagnostic ignored "-Wsign-conversion" +# endif +#endif +#line 682 "./SysYFScanner.cpp" +#define YY_NO_INPUT 1 +#line 113 "../../grammar/SysYFScanner.ll" + // Code run each time a pattern is matched. + # define YY_USER_ACTION loc.columns(yyleng); +#line 687 "./SysYFScanner.cpp" +/* Regex abbreviations: */ +#line 689 "./SysYFScanner.cpp" + +#define INITIAL 0 + +#ifndef YY_NO_UNISTD_H +/* Special case for "unistd.h", since it is non-ANSI. We include it way + * down here because we want the user's section 1 to have been scanned first. + * The user has a chance to override it with an option. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +#include +/* %endif */ +#endif + +#ifndef YY_EXTRA_TYPE +#define YY_EXTRA_TYPE void * +#endif + +/* %if-c-only Reentrant structure and macros (non-C++). */ +/* %if-reentrant */ +/* %if-c-only */ +/* %endif */ +/* %if-reentrant */ +/* %endif */ +/* %endif End reentrant structures and macros. */ +/* %if-bison-bridge */ +/* %endif */ +/* %not-for-header */ +/* %ok-for-header */ + +/* %endif */ + +#ifndef yytext_ptr +static void yy_flex_strncpy ( char *, const char *, int ); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen ( const char * ); +#endif + +#ifndef YY_NO_INPUT +/* %if-c-only Standard (non-C++) definition */ +/* %not-for-header */ +/* %ok-for-header */ + +/* %endif */ +#endif + +/* %if-c-only */ +/* %endif */ + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else +#define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ +#endif + +/* Copy whatever the last rule matched to the standard output. */ +#ifndef ECHO +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ +/* %if-c++-only C++ definition */ +#define ECHO LexerOutput( yytext, yyleng ) +/* %endif */ +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ +/* %% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \ */\ +\ +/* %if-c++-only C++ definition \ */\ + if ( (int)(result = LexerInput( (char *) buf, max_size )) < 0 ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); +/* %endif */ + +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +#define YY_FATAL_ERROR(msg) LexerError( msg ) +/* %endif */ +#endif + +/* %if-tables-serialization structures and prototypes */ +/* %not-for-header */ +/* %ok-for-header */ + +/* %not-for-header */ +/* %tables-yydmap generated elements */ +/* %endif */ +/* end tables serialization structures and prototypes */ + +/* %ok-for-header */ + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL_IS_OURS 1 +/* %if-c-only Standard (non-C++) definition */ +/* %endif */ +/* %if-c++-only C++ definition */ +#define YY_DECL int yyFlexLexer::yylex() +/* %endif */ +#endif /* !YY_DECL */ + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK /*LINTED*/break; +#endif + +/* %% [6.0] YY_RULE_SETUP definition goes here */ +#define YY_RULE_SETUP \ + YY_USER_ACTION + +/* %not-for-header */ +/** The main scanner function which does all the work. + */ +YY_DECL +{ + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; + + if ( !(yy_init) ) + { + (yy_init) = 1; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! (yy_start) ) + (yy_start) = 1; /* first start state */ + + if ( ! yyin ) +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyin.rdbuf(std::cin.rdbuf()); +/* %endif */ + + if ( ! yyout ) +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyout.rdbuf(std::cout.rdbuf()); +/* %endif */ + + if ( ! YY_CURRENT_BUFFER ) { + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_load_buffer_state( ); + } + + { +/* %% [7.0] user's declarations go here */ +#line 129 "../../grammar/SysYFScanner.ll" + +#line 131 "../../grammar/SysYFScanner.ll" + /* keyword */ +#line 885 "./SysYFScanner.cpp" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ + { +/* %% [8.0] yymore()-related code goes here */ + yy_cp = (yy_c_buf_p); + + /* Support of yytext. */ + *yy_cp = (yy_hold_char); + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + +/* %% [9.0] code to set up and find next match goes here */ + yy_current_state = (yy_start); +yy_match: + do + { + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + ++yy_cp; + } + while ( yy_current_state != 112 ); + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + +yy_find_action: +/* %% [10.0] code to find the action number goes here */ + yy_act = yy_accept[yy_current_state]; + + YY_DO_BEFORE_ACTION; + +/* %% [11.0] code for yylineno update goes here */ + +do_action: /* This label is used only to access EOF actions. */ + +/* %% [12.0] debug code goes here */ + if ( yy_flex_debug ) + { + if ( yy_act == 0 ) + std::cerr << "--scanner backing up\n"; + else if ( yy_act < 45 ) + std::cerr << "--accepting rule at line " << yy_rule_linenum[yy_act] << + "(\"" << yytext << "\")\n"; + else if ( yy_act == 45 ) + std::cerr << "--accepting default rule (\"" << yytext << "\")\n"; + else if ( yy_act == 46 ) + std::cerr << "--(end of buffer or a NUL)\n"; + else + std::cerr << "--EOF (start condition " << YY_START << ")\n"; + } + + switch ( yy_act ) + { /* beginning of action switch */ +/* %% [13.0] actions go here */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = (yy_hold_char); + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + goto yy_find_action; + +case 1: +YY_RULE_SETUP +#line 132 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(FLOAT);} + YY_BREAK +case 2: +YY_RULE_SETUP +#line 133 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(INT);} + YY_BREAK +case 3: +YY_RULE_SETUP +#line 134 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(RETURN);} + YY_BREAK +case 4: +YY_RULE_SETUP +#line 135 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(VOID);} + YY_BREAK +case 5: +YY_RULE_SETUP +#line 136 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(CONST);} + YY_BREAK +case 6: +YY_RULE_SETUP +#line 137 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(BREAK);} + YY_BREAK +case 7: +YY_RULE_SETUP +#line 138 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(CONTINUE);} + YY_BREAK +case 8: +YY_RULE_SETUP +#line 139 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(WHILE);} + YY_BREAK +case 9: +YY_RULE_SETUP +#line 140 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(IF);} + YY_BREAK +case 10: +YY_RULE_SETUP +#line 141 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(ELSE);} + YY_BREAK +case 11: +YY_RULE_SETUP +#line 143 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LT);} + YY_BREAK +case 12: +YY_RULE_SETUP +#line 144 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LTE);} + YY_BREAK +case 13: +YY_RULE_SETUP +#line 145 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(GT);} + YY_BREAK +case 14: +YY_RULE_SETUP +#line 146 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(GTE);} + YY_BREAK +case 15: +YY_RULE_SETUP +#line 147 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(EQ);} + YY_BREAK +case 16: +YY_RULE_SETUP +#line 148 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(NEQ);} + YY_BREAK +case 17: +YY_RULE_SETUP +#line 149 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(NOT);} + YY_BREAK +case 18: +YY_RULE_SETUP +#line 150 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LOGICAND);} + YY_BREAK +case 19: +YY_RULE_SETUP +#line 151 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LOGICOR);} + YY_BREAK +case 20: +YY_RULE_SETUP +#line 152 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(PLUS);} + YY_BREAK +case 21: +YY_RULE_SETUP +#line 153 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(MINUS);} + YY_BREAK +case 22: +YY_RULE_SETUP +#line 154 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(MULTIPLY);} + YY_BREAK +case 23: +YY_RULE_SETUP +#line 155 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(DIVIDE);} + YY_BREAK +case 24: +YY_RULE_SETUP +#line 156 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(MODULO);} + YY_BREAK +case 25: +YY_RULE_SETUP +#line 157 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(ASSIGN);} + YY_BREAK +case 26: +YY_RULE_SETUP +#line 158 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(SEMICOLON);} + YY_BREAK +case 27: +YY_RULE_SETUP +#line 159 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(COMMA);} + YY_BREAK +case 28: +YY_RULE_SETUP +#line 160 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LPARENTHESE);} + YY_BREAK +case 29: +YY_RULE_SETUP +#line 161 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(RPARENTHESE);} + YY_BREAK +case 30: +YY_RULE_SETUP +#line 162 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LBRACKET);} + YY_BREAK +case 31: +YY_RULE_SETUP +#line 163 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(RBRACKET);} + YY_BREAK +case 32: +YY_RULE_SETUP +#line 164 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LBRACE);} + YY_BREAK +case 33: +YY_RULE_SETUP +#line 165 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(RBRACE);} + YY_BREAK +case 34: +/* rule 34 can match eol */ +YY_RULE_SETUP +#line 168 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(LRBRACKET);} + YY_BREAK +case 35: +YY_RULE_SETUP +#line 169 "../../grammar/SysYFScanner.ll" +{loc.step();} + YY_BREAK +case 36: +/* rule 36 can match eol */ +YY_RULE_SETUP +#line 170 "../../grammar/SysYFScanner.ll" +{loc.lines(yyleng); loc.step();} + YY_BREAK +case 37: +/* rule 37 can match eol */ +YY_RULE_SETUP +#line 171 "../../grammar/SysYFScanner.ll" +{std::string s = yytext; + size_t n = std::count(s.begin(), s.end(), '\n'); + for (size_t i = 0; i < n; i++) loc.lines(1);} + YY_BREAK +case 38: +/* rule 38 can match eol */ +YY_RULE_SETUP +#line 174 "../../grammar/SysYFScanner.ll" +{loc.lines(1);loc.step();} + YY_BREAK +case 39: +YY_RULE_SETUP +#line 175 "../../grammar/SysYFScanner.ll" +{std::string dec = yytext; + unsigned sum = 0; + int len = dec.size(); + for(int i = 0;i < len;i++){ + auto a = dec[i]; + sum = sum * 10 + a - 48; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 40: +YY_RULE_SETUP +#line 183 "../../grammar/SysYFScanner.ll" +{std::string hex = yytext; + unsigned sum = 0; + int len = hex.size(); + for(int i = 2;i < len;i++){ + auto a = hex[i]; + sum = sum * 16 + ch2int[a]; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 41: +YY_RULE_SETUP +#line 191 "../../grammar/SysYFScanner.ll" +{std::string oct = yytext; + unsigned sum = 0; + int len = oct.size(); + for(int i = 1;i < len;i++){ + auto a = oct[i]; + sum = sum * 8 + ch2int[a]; + } + RET_TYPE_TOKEN(INTCONST, int(sum));} + YY_BREAK +case 42: +YY_RULE_SETUP +#line 199 "../../grammar/SysYFScanner.ll" +{RET_TYPE_TOKEN(IDENTIFIER, yytext);} + YY_BREAK +case 43: +YY_RULE_SETUP +#line 200 "../../grammar/SysYFScanner.ll" +{RET_TYPE_TOKEN(FLOATCONST, std::stod(yytext));} + YY_BREAK +case YY_STATE_EOF(INITIAL): +#line 201 "../../grammar/SysYFScanner.ll" +{RET_NOTYPE_TOKEN(END);} + YY_BREAK +case 44: +YY_RULE_SETUP +#line 202 "../../grammar/SysYFScanner.ll" +{std::cout << "Error in scanner!" << '\n'; exit(1);} + YY_BREAK +case 45: +YY_RULE_SETUP +#line 203 "../../grammar/SysYFScanner.ll" +ECHO; + YY_BREAK +#line 1216 "./SysYFScanner.cpp" + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = (yy_hold_char); + YY_RESTORE_YY_MORE_OFFSET + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between YY_CURRENT_BUFFER and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin.rdbuf(); +/* %endif */ + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state ); + + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++(yy_c_buf_p); + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { +/* %% [14.0] code to do back-up for compressed tables and set up yy_cp goes here */ + yy_cp = (yy_last_accepting_cpos); + yy_current_state = (yy_last_accepting_state); + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_END_OF_FILE: + { + (yy_did_buffer_switch_on_eof) = 0; + + if ( yywrap( ) ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = + (yytext_ptr) + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + (yy_c_buf_p) = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; + + yy_current_state = yy_get_previous_state( ); + + yy_cp = (yy_c_buf_p); + yy_bp = (yytext_ptr) + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of user's declarations */ +} /* end of yylex */ +/* %ok-for-header */ + +/* %if-c++-only */ +/* %not-for-header */ +/* The contents of this function are C++ specific, so the () macro is not used. + * This constructor simply maintains backward compatibility. + * DEPRECATED + */ +yyFlexLexer::yyFlexLexer( std::istream* arg_yyin, std::ostream* arg_yyout ): + yyin(arg_yyin ? arg_yyin->rdbuf() : std::cin.rdbuf()), + yyout(arg_yyout ? arg_yyout->rdbuf() : std::cout.rdbuf()) +{ + ctor_common(); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +yyFlexLexer::yyFlexLexer( std::istream& arg_yyin, std::ostream& arg_yyout ): + yyin(arg_yyin.rdbuf()), + yyout(arg_yyout.rdbuf()) +{ + ctor_common(); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::ctor_common() +{ + yy_c_buf_p = 0; + yy_init = 0; + yy_start = 0; + yy_flex_debug = 0; + yylineno = 1; // this will only get updated if %option yylineno + + yy_did_buffer_switch_on_eof = 0; + + yy_looking_for_trail_begin = 0; + yy_more_flag = 0; + yy_more_len = 0; + yy_more_offset = yy_prev_more_offset = 0; + + yy_start_stack_ptr = yy_start_stack_depth = 0; + yy_start_stack = NULL; + + yy_buffer_stack = NULL; + yy_buffer_stack_top = 0; + yy_buffer_stack_max = 0; + + yy_state_buf = 0; + +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +yyFlexLexer::~yyFlexLexer() +{ + delete [] yy_state_buf; + yyfree( yy_start_stack ); + yy_delete_buffer( YY_CURRENT_BUFFER ); + yyfree( yy_buffer_stack ); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::switch_streams( std::istream& new_in, std::ostream& new_out ) +{ + // was if( new_in ) + yy_delete_buffer( YY_CURRENT_BUFFER ); + yy_switch_to_buffer( yy_create_buffer( new_in, YY_BUF_SIZE ) ); + + // was if( new_out ) + yyout.rdbuf(new_out.rdbuf()); +} + +/* The contents of this function are C++ specific, so the () macro is not used. + */ +void yyFlexLexer::switch_streams( std::istream* new_in, std::ostream* new_out ) +{ + if( ! new_in ) { + new_in = &yyin; + } + + if ( ! new_out ) { + new_out = &yyout; + } + + switch_streams(*new_in, *new_out); +} + +#ifdef YY_INTERACTIVE +int yyFlexLexer::LexerInput( char* buf, int /* max_size */ ) +#else +int yyFlexLexer::LexerInput( char* buf, int max_size ) +#endif +{ + if ( yyin.eof() || yyin.fail() ) + return 0; + +#ifdef YY_INTERACTIVE + yyin.get( buf[0] ); + + if ( yyin.eof() ) + return 0; + + if ( yyin.bad() ) + return -1; + + return 1; + +#else + (void) yyin.read( buf, max_size ); + + if ( yyin.bad() ) + return -1; + else + return yyin.gcount(); +#endif +} + +void yyFlexLexer::LexerOutput( const char* buf, int size ) +{ + (void) yyout.write( buf, size ); +} +/* %ok-for-header */ + +/* %endif */ + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +int yyFlexLexer::yy_get_next_buffer() +/* %endif */ +{ + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = (yytext_ptr); + int number_to_move, i; + int ret_val; + + if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr) - 1); + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; + + else + { + int num_to_read = + YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; + + int yy_c_buf_p_offset = + (int) ((yy_c_buf_p) - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + int new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yyrealloc( (void *) b->yy_ch_buf, + (yy_size_t) (b->yy_buf_size + 2) ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = NULL; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - + number_to_move - 1; + + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), + (yy_n_chars), num_to_read ); + + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + if ( (yy_n_chars) == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart( yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + if (((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + /* Extend the array by 50%, plus the number we really need. */ + int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc( + (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size ); + if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + /* "- 2" to take care of EOB's */ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2); + } + + (yy_n_chars) += number_to_move; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; + + (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; + + return ret_val; +} + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + +/* %if-c-only */ +/* %not-for-header */ +/* %endif */ +/* %if-c++-only */ + yy_state_type yyFlexLexer::yy_get_previous_state() +/* %endif */ +{ + yy_state_type yy_current_state; + char *yy_cp; + +/* %% [15.0] code to get the start state into yy_current_state goes here */ + yy_current_state = (yy_start); + + for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) + { +/* %% [16.0] code to find the next state goes here */ + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + } + + return yy_current_state; +} + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yy_state_type yyFlexLexer::yy_try_NUL_trans( yy_state_type yy_current_state ) +/* %endif */ +{ + int yy_is_jam; + /* %% [17.0] code to find the next state, and perhaps do backing up, goes here */ + char *yy_cp = (yy_c_buf_p); + + YY_CHAR yy_c = 1; + if ( yy_accept[yy_current_state] ) + { + (yy_last_accepting_state) = yy_current_state; + (yy_last_accepting_cpos) = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 113 ) + yy_c = yy_meta[yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c]; + yy_is_jam = (yy_current_state == 112); + + return yy_is_jam ? 0 : yy_current_state; +} + +#ifndef YY_NO_UNPUT +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yyunput( int c, char* yy_bp) +/* %endif */ +{ + char *yy_cp; + + yy_cp = (yy_c_buf_p); + + /* undo effects of setting up yytext */ + *yy_cp = (yy_hold_char); + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + int number_to_move = (yy_n_chars) + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; + char *source = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; + + while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = + (yy_n_chars) = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + +/* %% [18.0] update yylineno here */ + + (yytext_ptr) = yy_bp; + (yy_hold_char) = *yy_cp; + (yy_c_buf_p) = yy_cp; +} +/* %if-c-only */ +/* %endif */ +#endif + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + int yyFlexLexer::yyinput() +/* %endif */ +{ + int c; + + *(yy_c_buf_p) = (yy_hold_char); + + if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) + /* This was really a NUL. */ + *(yy_c_buf_p) = '\0'; + + else + { /* need more input */ + int offset = (int) ((yy_c_buf_p) - (yytext_ptr)); + ++(yy_c_buf_p); + + switch ( yy_get_next_buffer( ) ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart( yyin ); + + /*FALLTHROUGH*/ + + case EOB_ACT_END_OF_FILE: + { + if ( yywrap( ) ) + return 0; + + if ( ! (yy_did_buffer_switch_on_eof) ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr) + offset; + break; + } + } + } + + c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ + *(yy_c_buf_p) = '\0'; /* preserve yytext */ + (yy_hold_char) = *++(yy_c_buf_p); + +/* %% [19.0] update BOL and yylineno */ + + return c; +} +/* %if-c-only */ +/* %endif */ + +/** Immediately switch to a different input stream. + * @param input_file A readable stream. + * + * @note This function does not reset the start condition to @c INITIAL . + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yyrestart( std::istream& input_file ) +/* %endif */ +{ + + if ( ! YY_CURRENT_BUFFER ){ + yyensure_buffer_stack (); + YY_CURRENT_BUFFER_LVALUE = + yy_create_buffer( yyin, YY_BUF_SIZE ); + } + + yy_init_buffer( YY_CURRENT_BUFFER, input_file ); + yy_load_buffer_state( ); +} + +/* %if-c++-only */ +/** Delegate to the new version that takes an istream reference. + * @param input_file A readable stream. + * + * @note This function does not reset the start condition to @c INITIAL . + */ +void yyFlexLexer::yyrestart( std::istream* input_file ) +{ + if( ! input_file ) { + input_file = &yyin; + } + yyrestart( *input_file ); +} +/* %endif */ + +/** Switch to a different input buffer. + * @param new_buffer The new input buffer. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +/* %endif */ +{ + + /* TODO. We should be able to replace this entire function body + * with + * yypop_buffer_state(); + * yypush_buffer_state(new_buffer); + */ + yyensure_buffer_stack (); + if ( YY_CURRENT_BUFFER == new_buffer ) + return; + + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + YY_CURRENT_BUFFER_LVALUE = new_buffer; + yy_load_buffer_state( ); + + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + (yy_did_buffer_switch_on_eof) = 1; +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_load_buffer_state() +/* %endif */ +{ + (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + yyin.rdbuf(YY_CURRENT_BUFFER_LVALUE->yy_input_file); +/* %endif */ + (yy_hold_char) = *(yy_c_buf_p); +} + +/** Allocate and initialize an input buffer state. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * + * @return the allocated buffer state. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream& file, int size ) +/* %endif */ +{ + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_buf_size = size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + yy_init_buffer( b, file ); + + return b; +} + +/* %if-c++-only */ +/** Delegate creation of buffers to the new version that takes an istream reference. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * + * @return the allocated buffer state. + */ + YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream* file, int size ) +{ + return yy_create_buffer( *file, size ); +} +/* %endif */ + +/** Destroy the buffer. + * @param b a buffer created with yy_create_buffer() + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_delete_buffer( YY_BUFFER_STATE b ) +/* %endif */ +{ + + if ( ! b ) + return; + + if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ + YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + yyfree( (void *) b->yy_ch_buf ); + + yyfree( (void *) b ); +} + +/* Initializes or reinitializes a buffer. + * This function is sometimes called more than once on the same buffer, + * such as during a yyrestart() or at EOF. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_init_buffer( YY_BUFFER_STATE b, std::istream& file ) +/* %endif */ + +{ + int oerrno = errno; + + yy_flush_buffer( b ); + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + b->yy_input_file = file.rdbuf(); +/* %endif */ + b->yy_fill_buffer = 1; + + /* If b is the current buffer, then yy_init_buffer was _probably_ + * called from yyrestart() or through yy_get_next_buffer. + * In that case, we don't want to reset the lineno or column. + */ + if (b != YY_CURRENT_BUFFER){ + b->yy_bs_lineno = 1; + b->yy_bs_column = 0; + } + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + b->yy_is_interactive = 0; +/* %endif */ + errno = oerrno; +} + +/** Discard all buffered characters. On the next scan, YY_INPUT will be called. + * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_flush_buffer( YY_BUFFER_STATE b ) +/* %endif */ +{ + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == YY_CURRENT_BUFFER ) + yy_load_buffer_state( ); +} + +/* %if-c-or-c++ */ +/** Pushes the new state onto the stack. The new state becomes + * the current state. This function will allocate the stack + * if necessary. + * @param new_buffer The new state. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yypush_buffer_state (YY_BUFFER_STATE new_buffer) +/* %endif */ +{ + if (new_buffer == NULL) + return; + + yyensure_buffer_stack(); + + /* This block is copied from yy_switch_to_buffer. */ + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *(yy_c_buf_p) = (yy_hold_char); + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); + } + + /* Only push if top exists. Otherwise, replace top. */ + if (YY_CURRENT_BUFFER) + (yy_buffer_stack_top)++; + YY_CURRENT_BUFFER_LVALUE = new_buffer; + + /* copied from yy_switch_to_buffer. */ + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; +} +/* %endif */ + +/* %if-c-or-c++ */ +/** Removes and deletes the top of the stack, if present. + * The next element becomes the new top. + * + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yypop_buffer_state (void) +/* %endif */ +{ + if (!YY_CURRENT_BUFFER) + return; + + yy_delete_buffer(YY_CURRENT_BUFFER ); + YY_CURRENT_BUFFER_LVALUE = NULL; + if ((yy_buffer_stack_top) > 0) + --(yy_buffer_stack_top); + + if (YY_CURRENT_BUFFER) { + yy_load_buffer_state( ); + (yy_did_buffer_switch_on_eof) = 1; + } +} +/* %endif */ + +/* %if-c-or-c++ */ +/* Allocates the stack if it does not exist. + * Guarantees space for at least one push. + */ +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::yyensure_buffer_stack(void) +/* %endif */ +{ + yy_size_t num_to_alloc; + + if (!(yy_buffer_stack)) { + + /* First allocation is just for 2 elements, since we don't know if this + * scanner will even need a stack. We use 2 instead of 1 to avoid an + * immediate realloc on the next call. + */ + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ + (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc + (num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); + + (yy_buffer_stack_max) = num_to_alloc; + (yy_buffer_stack_top) = 0; + return; + } + + if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ + + /* Increase the buffer to prepare for a possible push. */ + yy_size_t grow_size = 8 /* arbitrary grow size */; + + num_to_alloc = (yy_buffer_stack_max) + grow_size; + (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc + ((yy_buffer_stack), + num_to_alloc * sizeof(struct yy_buffer_state*) + ); + if ( ! (yy_buffer_stack) ) + YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); + + /* zero only the new slots.*/ + memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); + (yy_buffer_stack_max) = num_to_alloc; + } +} +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_push_state( int _new_state ) +/* %endif */ +{ + if ( (yy_start_stack_ptr) >= (yy_start_stack_depth) ) + { + yy_size_t new_size; + + (yy_start_stack_depth) += YY_START_STACK_INCR; + new_size = (yy_size_t) (yy_start_stack_depth) * sizeof( int ); + + if ( ! (yy_start_stack) ) + (yy_start_stack) = (int *) yyalloc( new_size ); + + else + (yy_start_stack) = (int *) yyrealloc( + (void *) (yy_start_stack), new_size ); + + if ( ! (yy_start_stack) ) + YY_FATAL_ERROR( "out of memory expanding start-condition stack" ); + } + + (yy_start_stack)[(yy_start_stack_ptr)++] = YY_START; + + BEGIN(_new_state); +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + void yyFlexLexer::yy_pop_state() +/* %endif */ +{ + if ( --(yy_start_stack_ptr) < 0 ) + YY_FATAL_ERROR( "start-condition stack underflow" ); + + BEGIN((yy_start_stack)[(yy_start_stack_ptr)]); +} + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ + int yyFlexLexer::yy_top_state() +/* %endif */ +{ + return (yy_start_stack)[(yy_start_stack_ptr) - 1]; +} + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +/* %if-c-only */ +/* %endif */ +/* %if-c++-only */ +void yyFlexLexer::LexerError( const char* msg ) +{ + std::cerr << msg << std::endl; + exit( YY_EXIT_FAILURE ); +} +/* %endif */ + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + yytext[yyleng] = (yy_hold_char); \ + (yy_c_buf_p) = yytext + yyless_macro_arg; \ + (yy_hold_char) = *(yy_c_buf_p); \ + *(yy_c_buf_p) = '\0'; \ + yyleng = yyless_macro_arg; \ + } \ + while ( 0 ) + +/* Accessor methods (get/set functions) to struct members. */ + +/* %if-c-only */ +/* %if-reentrant */ +/* %endif */ +/* %if-reentrant */ +/* %endif */ +/* %endif */ + +/* %if-reentrant */ +/* %if-bison-bridge */ +/* %endif */ +/* %endif if-c-only */ + +/* %if-c-only */ +/* %endif */ + +/* %if-c-only SNIP! this currently causes conflicts with the c++ scanner */ +/* %if-reentrant */ +/* %endif */ +/* %endif */ + +/* + * Internal utility routines. + */ + +#ifndef yytext_ptr +static void yy_flex_strncpy (char* s1, const char * s2, int n ) +{ + + int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; +} +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (const char * s ) +{ + int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; +} +#endif + +void *yyalloc (yy_size_t size ) +{ + return malloc(size); +} + +void *yyrealloc (void * ptr, yy_size_t size ) +{ + + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return realloc(ptr, size); +} + +void yyfree (void * ptr ) +{ + free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ +} + +/* %if-tables-serialization definitions */ +/* %define-yytables The name for this specific scanner's tables. */ +#define YYTABLES_NAME "yytables" +/* %endif */ + +/* %ok-for-header */ + +#line 203 "../../grammar/SysYFScanner.ll" + + +int yyFlexLexer::yylex() { + std::cerr << "'int yyFlexLexer::yylex()' should never be called." << std::endl; + exit(1); +} + diff --git a/src/SysYFIR/BasicBlock.cpp b/src/SysYFIR/BasicBlock.cpp new file mode 100644 index 0000000..bb04f3c --- /dev/null +++ b/src/SysYFIR/BasicBlock.cpp @@ -0,0 +1,122 @@ +#include "Module.h" +#include "BasicBlock.h" +#include "Function.h" +#include "IRPrinter.h" +#ifdef DEBUG +#include +#endif +#include + +namespace SysYF +{ +namespace IR +{ +BasicBlock::BasicBlock(Ptr m, const std::string &name = "", + Ptr parent = nullptr) + : Value(Type::get_label_type(m), name), parent_(parent) +{ +#ifdef DEBUG + assert(parent && "currently parent should not be nullptr"); +#endif + // parent_->add_basic_block(dynamic_pointer_cast(shared_from_this())); +} + +void BasicBlock::init(Ptr m, const std::string &name = "", + Ptr parent = nullptr) +{ + parent_->add_basic_block(dynamic_pointer_cast(shared_from_this())); +} + +Ptr BasicBlock::get_module() +{ + return get_parent()->get_parent(); +} + +void BasicBlock::add_instruction(Ptr instr) +{ + instr_list_.push_back(instr); +} + +void BasicBlock::add_instruction(PtrList::iterator instr_pos, Ptr instr) +{ + instr_list_.insert(instr_pos, instr); +} + +void BasicBlock::add_instr_begin(Ptr instr) +{ + instr_list_.push_front(instr); +} + +PtrList::iterator BasicBlock::find_instruction(Ptr instr) +{ + return std::find(instr_list_.begin(), instr_list_.end(), instr); +} + +void BasicBlock::delete_instr( Ptr instr ) +{ + instr_list_.remove(instr); + instr->remove_use_of_ops(); +} + +const Ptr BasicBlock::get_terminator() const +{ + if (instr_list_.empty()){ + return nullptr; + } + switch (instr_list_.back()->get_instr_type()) + { + case Instruction::ret: + return instr_list_.back(); + break; + + case Instruction::br: + return instr_list_.back(); + break; + + default: + return nullptr; + break; + } +} + +void BasicBlock::erase_from_parent() +{ + this->get_parent()->remove(dynamic_pointer_cast(shared_from_this())); +} + +std::string BasicBlock::print() +{ + std::string bb_ir; + bb_ir += this->get_name(); + bb_ir += ":"; + // print prebb + if(!this->get_pre_basic_blocks().empty()) + { + bb_ir += " ; preds = "; + } + for (auto bb : this->get_pre_basic_blocks() ) + { + if( bb != *this->get_pre_basic_blocks().begin() ) + bb_ir += ", "; + bb_ir += print_as_op(bb, false); + } + + // print prebb + if ( !this->get_parent() ) + { + bb_ir += "\n"; + bb_ir += "; Error: Block without parent!"; + } + bb_ir += "\n"; + for ( auto instr : this->get_instructions() ) + { + bb_ir += " "; + bb_ir += instr->print(); + bb_ir += "\n"; + } + + return bb_ir; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/CMakeLists.txt b/src/SysYFIR/CMakeLists.txt new file mode 100644 index 0000000..240f22f --- /dev/null +++ b/src/SysYFIR/CMakeLists.txt @@ -0,0 +1,13 @@ +add_library( + IRLib STATIC + Type.cpp + User.cpp + Value.cpp + BasicBlock.cpp + Constant.cpp + Function.cpp + GlobalVariable.cpp + Instruction.cpp + Module.cpp + IRPrinter.cpp +) diff --git a/src/SysYFIR/Constant.cpp b/src/SysYFIR/Constant.cpp new file mode 100644 index 0000000..af830d1 --- /dev/null +++ b/src/SysYFIR/Constant.cpp @@ -0,0 +1,122 @@ +#include "Constant.h" +#include "Module.h" +#include "internal_macros.h" +#include +#include +#include + +namespace SysYF +{ +namespace IR +{ +void ConstantInt::init(Ptr ty, int val) +{ + Constant::init(ty, "", 0); +} + +Ptr ConstantInt::create(int val, Ptr m) +{ + RET_AFTER_INIT(ConstantInt, Type::get_int32_type(m), val); +} + +Ptr ConstantInt::create(bool val, Ptr m) +{ + RET_AFTER_INIT(ConstantInt, Type::get_int1_type(m), val?1:0); +} + +std::string ConstantInt::print() +{ + std::string const_ir; + Ptr ty = this->get_type(); + if ( ty->is_integer_type() && static_pointer_cast(ty)->get_num_bits() == 1 ) + { + //int1 + const_ir += (this->get_value() == 0) ? "false" : "true"; + } + else + { + //int32 + const_ir += std::to_string(this->get_value()); + } + return const_ir; +} + +void ConstantFloat::init(Ptr ty, float val) +{ + Constant::init(ty, "", 0); +} + +Ptr ConstantFloat::create(float val, Ptr m) +{ + RET_AFTER_INIT(ConstantFloat, Type::get_float_type(m), val); +} + +std::string ConstantFloat::print() +{ + std::stringstream fp_ir_ss; + std::string fp_ir; + double val = this->get_value(); + uint64_t hex_val = 0; + memcpy(&hex_val, &val, sizeof(double)); + fp_ir_ss << "0x"<< std::hex << hex_val << std::endl; + fp_ir_ss >> fp_ir; + return fp_ir; +} + +ConstantArray::ConstantArray(Ptr ty, const PtrVec &val) + : Constant(ty, "", val.size()) +{ + +} + +void ConstantArray::init(Ptr ty, const PtrVec &val) +{ + Constant::init(ty, "", val.size()); + for (unsigned int i = 0; i < val.size(); i++) + set_operand(i, val[i]); + this->const_array.assign(val.begin(),val.end()); +} + +Ptr ConstantArray::get_element_value(int index) { + return this->const_array[index]; +} + +Ptr ConstantArray::create(Ptr ty, const PtrVec &val) +{ + RET_AFTER_INIT(ConstantArray, ty, val); +} + +std::string ConstantArray::print() +{ + std::string const_ir; + const_ir += "["; + const_ir += this->get_type()->get_array_element_type()->print(); + const_ir += " "; + const_ir += get_element_value(0)->print(); + for (unsigned int i = 1; i < this->get_size_of_array(); i++) { + const_ir += ", "; + const_ir += this->get_type()->get_array_element_type()->print(); + const_ir += " "; + const_ir += get_element_value(i)->print(); + } + const_ir += "]"; + return const_ir; +} + +void ConstantZero::init(Ptr ty) +{ + Constant::init(ty, "", 0); +} + +Ptr ConstantZero::create(Ptr ty, Ptr m) +{ + RET_AFTER_INIT(ConstantZero, ty); +} + +std::string ConstantZero::print() +{ + return "zeroinitializer"; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/Function.cpp b/src/SysYFIR/Function.cpp new file mode 100644 index 0000000..17f2fd8 --- /dev/null +++ b/src/SysYFIR/Function.cpp @@ -0,0 +1,192 @@ +#include "Module.h" +#include "Function.h" +#include "IRPrinter.h" +#include "internal_macros.h" + +namespace SysYF +{ +namespace IR +{ +Function::Function(Ptr ty, const std::string &name, Ptr parent) + : Value(ty, name), parent_(parent), seq_cnt_(0) +{ + +} + +void Function::init(Ptr ty, const std::string &name, Ptr parent) { + parent_->add_function(dynamic_pointer_cast(shared_from_this())); + build_args(); +} + +Ptr Function::create(Ptr ty, const std::string &name, Ptr parent) +{ + RET_AFTER_INIT(Function, ty, name, parent); +} + +Ptr Function::get_function_type() const +{ + return static_pointer_cast(get_type()); +} + +Ptr Function::get_return_type() const +{ + return get_function_type()->get_return_type(); +} + +unsigned Function::get_num_of_args() const +{ + return get_function_type()->get_num_of_args(); +} + +unsigned Function::get_num_basic_blocks() const +{ + return basic_blocks_.size(); +} + +Ptr Function::get_parent() const +{ + return parent_; +} + +void Function::remove(Ptr bb) +{ + basic_blocks_.remove(bb); + for (auto pre : bb->get_pre_basic_blocks()) + { + pre->remove_succ_basic_block(bb); + } + for (auto succ : bb->get_succ_basic_blocks()) + { + succ->remove_pre_basic_block(bb); + } +} + +void Function::build_args() +{ + auto func_ty = get_function_type(); + unsigned int num_args = get_num_of_args(); + for (unsigned int i = 0; i < num_args; i++) { + arguments_.push_back(Argument::create(func_ty->get_param_type(i), "", dynamic_pointer_cast(shared_from_this()), i)); + } +} + +void Function::add_basic_block(Ptr bb) +{ + basic_blocks_.push_back(bb); +} + +void Function::set_instr_name() +{ + std::map , int> seq; + for (auto arg : this->get_args()) + { + if ( seq.find(arg) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( arg->set_name("arg"+std::to_string(seq_num) )) + { + seq.insert( {arg, seq_num} ); + } + } + } + for (auto bb : basic_blocks_) + { + if ( seq.find(bb) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( bb->set_name("label"+std::to_string(seq_num) )) + { + seq.insert( {bb, seq_num} ); + } + } + for (auto instr : bb->get_instructions()) + { + if ( !instr->is_void() && seq.find(instr) == seq.end()) + { + auto seq_num = seq.size() + seq_cnt_; + if ( instr->set_name("op"+std::to_string(seq_num) )) + { + seq.insert( {instr, seq_num} ); + } + } + } + } + seq_cnt_ += seq.size(); +} + +std::string Function::print() +{ + set_instr_name(); + std::string func_ir; + if ( this->is_declaration() ) + { + func_ir += "declare "; + } + else + { + func_ir += "define "; + } + + func_ir += this->get_return_type()->print(); + func_ir += " "; + func_ir += print_as_op(shared_from_this(), false); + func_ir += "("; + + //print arg + if ( this->is_declaration() ) + { + for (unsigned int i = 0; i < this->get_num_of_args(); i++) + { + if(i) + func_ir += ", "; + func_ir += static_pointer_cast(this->get_type())->get_param_type(i)->print(); + } + } + else + { + for ( auto arg = this->arg_begin(); arg != arg_end() ; arg++ ) + { + if( arg != this->arg_begin() ) + { + func_ir += ", "; + } + func_ir += static_pointer_cast(*arg)->print(); + } + } + func_ir += ")"; + + //print bb + if( this->is_declaration() ) { + func_ir += "\n"; + } + else + { + func_ir += " {"; + func_ir += "\n"; + for ( auto bb : this->get_basic_blocks() ) + { + func_ir += bb->print(); + } + func_ir += "}"; + } + + return func_ir; +} + +Ptr Argument::create(Ptr ty, const std::string &name, Ptr f, + unsigned arg_no) +{ + return Ptr(new Argument(ty, name, f, arg_no)); +} + +std::string Argument::print() +{ + std::string arg_ir; + arg_ir += this->get_type()->print(); + arg_ir += " %"; + arg_ir += this->get_name(); + return arg_ir; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/GlobalVariable.cpp b/src/SysYFIR/GlobalVariable.cpp new file mode 100644 index 0000000..7b5a74f --- /dev/null +++ b/src/SysYFIR/GlobalVariable.cpp @@ -0,0 +1,41 @@ +#include "GlobalVariable.h" +#include "IRPrinter.h" + +namespace SysYF +{ +namespace IR +{ +GlobalVariable::GlobalVariable(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val) + : User(ty, name, init_val != nullptr), is_const_(is_const), init_val_(init_val) +{ + +} + +void GlobalVariable::init(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val) +{ + m->add_global_variable(dynamic_pointer_cast(shared_from_this())); + if (init_val) { + this->set_operand(0, init_val); + } +}//global操作数为initval + +Ptr GlobalVariable::create(std::string name, Ptr m, Ptr ty, bool is_const, Ptr init_val) +{ + + RET_AFTER_INIT(GlobalVariable, name, m, PointerType::get(ty), is_const, init_val) +} + +std::string GlobalVariable::print() +{ + std::string global_val_ir; + global_val_ir += print_as_op(shared_from_this(), false); + global_val_ir += " = "; + global_val_ir += (this->is_const() ? "constant " : "global "); + global_val_ir += this->get_type()->get_pointer_element_type()->print(); + global_val_ir += " "; + global_val_ir += this->get_init()->print(); + return global_val_ir; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/IRPrinter.cpp b/src/SysYFIR/IRPrinter.cpp new file mode 100644 index 0000000..d796eec --- /dev/null +++ b/src/SysYFIR/IRPrinter.cpp @@ -0,0 +1,93 @@ +#include "IRPrinter.h" + +namespace SysYF +{ +namespace IR +{ +std::string print_as_op( Ptr v, bool print_ty ) +{ + std::string op_ir; + if( print_ty ) + { + op_ir += v->get_type()->print(); + op_ir += " "; + } + + if (dynamic_pointer_cast(v)) + { + op_ir += "@"+v->get_name(); + } + else if (dynamic_pointer_cast(v) ) + { + op_ir += "@"+v->get_name(); + } + else if (dynamic_pointer_cast(v)) + { + op_ir += v->print(); + } + else + { + op_ir += "%"+v->get_name(); + } + + return op_ir; +} + +std::string print_cmp_type( CmpInst::CmpOp op ) +{ + switch (op) + { + case CmpInst::GE: + return "sge"; + break; + case CmpInst::GT: + return "sgt"; + break; + case CmpInst::LE: + return "sle"; + break; + case CmpInst::LT: + return "slt"; + break; + case CmpInst::EQ: + return "eq"; + break; + case CmpInst::NE: + return "ne"; + break; + default: + break; + } + return "wrong cmpop"; +} + +std::string print_fcmp_type( FCmpInst::CmpOp op ) +{ + switch (op) + { + case FCmpInst::GE: + return "uge"; + break; + case FCmpInst::GT: + return "ugt"; + break; + case FCmpInst::LE: + return "ule"; + break; + case FCmpInst::LT: + return "ult"; + break; + case FCmpInst::EQ: + return "ueq"; + break; + case FCmpInst::NE: + return "une"; + break; + default: + break; + } + return "wrong fcmpop"; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/Instruction.cpp b/src/SysYFIR/Instruction.cpp new file mode 100644 index 0000000..daa65eb --- /dev/null +++ b/src/SysYFIR/Instruction.cpp @@ -0,0 +1,792 @@ +#include "Type.h" +#include "Module.h" +#include "Function.h" +#include "BasicBlock.h" +#include "Instruction.h" +#include "IRPrinter.h" +#include "internal_macros.h" + +#ifdef DEBUG +#include +#endif +#include +#include + +namespace SysYF +{ +namespace IR +{ +Instruction::Instruction(Ptr ty, OpID id, unsigned num_ops, Ptr parent) + : User(ty, "", num_ops), op_id_(id), num_ops_(num_ops), parent_(parent) +{ + +} + +void Instruction::insert_to_bb() +{ + parent_ -> add_instruction(dynamic_pointer_cast(shared_from_this())); +} + +void Instruction::init(Ptr ty, OpID id, unsigned num_ops, Ptr parent) +{ + insert_to_bb(); +} + +Ptr Instruction::get_function() +{ + return parent_->get_parent(); +} + +Ptr Instruction::get_module() +{ + return parent_->get_module(); +} + +BinaryInst::BinaryInst(Ptr ty, OpID id, Ptr v1, Ptr v2, Ptr bb) + : Instruction(ty, id, 2, bb) +{ + +} + +void BinaryInst::init(Ptr ty, OpID id, Ptr v1, Ptr v2, Ptr bb) +{ + Instruction::init(ty, id, 2, bb); + set_operand(0, v1); + set_operand(1, v2); +} + +Ptr BinaryInst::create_add(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, v1->get_type()->is_pointer_type() ? v1->get_type() : v2->get_type(), Instruction::add, v1, v2, bb); +} + +Ptr BinaryInst::create_sub(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_int32_type(m), Instruction::sub, v1, v2, bb); +} + +Ptr BinaryInst::create_mul(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_int32_type(m), Instruction::mul, v1, v2, bb); +} + +Ptr BinaryInst::create_sdiv(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_int32_type(m), Instruction::sdiv, v1, v2, bb); +} + +Ptr BinaryInst::create_srem(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_int32_type(m), Instruction::srem, v1, v2, bb); +} + +Ptr BinaryInst::create_fadd(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_float_type(m), Instruction::fadd, v1, v2, bb); +} + +Ptr BinaryInst::create_fsub(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_float_type(m), Instruction::fsub, v1, v2, bb); +} + +Ptr BinaryInst::create_fmul(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_float_type(m), Instruction::fmul, v1, v2, bb); +} + +Ptr BinaryInst::create_fdiv(Ptr v1, Ptr v2, Ptr bb, Ptr m) +{ + RET_AFTER_INIT(BinaryInst, Type::get_float_type(m), Instruction::fdiv, v1, v2, bb); +} + +std::string BinaryInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +CmpInst::CmpInst(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb) + : Instruction(ty, Instruction::cmp, 2, bb), cmp_op_(op) +{ + +} + +void CmpInst::init(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, Ptr bb) +{ + Instruction::init(ty, Instruction::cmp, 2, bb); + set_operand(0, lhs); + set_operand(1, rhs); +} + +Ptr CmpInst::create_cmp(CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb, Ptr m) +{ + RET_AFTER_INIT(CmpInst, m->get_int1_type(), op, lhs, rhs, bb); +} + +std::string CmpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_cmp_type(this->cmp_op_); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +FCmpInst::FCmpInst(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb) + : Instruction(ty, Instruction::fcmp, 2, bb), cmp_op_(op) +{ + +} + +void FCmpInst::init(Ptr ty, CmpOp op, Ptr lhs, Ptr rhs, Ptr bb) +{ + Instruction::init(ty, Instruction::fcmp, 2, bb); + set_operand(0, lhs); + set_operand(1, rhs); +} + +Ptr FCmpInst::create_fcmp(CmpOp op, Ptr lhs, Ptr rhs, + Ptr bb, Ptr m) +{ + RET_AFTER_INIT(FCmpInst, m->get_int1_type(), op, lhs, rhs, bb); +} + +std::string FCmpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_fcmp_type(this->cmp_op_); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + if (Type::is_eq_type(this->get_operand(0)->get_type(), this->get_operand(1)->get_type())) + { + instr_ir += print_as_op(this->get_operand(1), false); + } + else + { + instr_ir += print_as_op(this->get_operand(1), true); + } + return instr_ir; +} + +CallInst::CallInst(Ptr func, PtrVec args, Ptr bb) + : Instruction(func->get_return_type(), Instruction::call, args.size() + 1, bb) +{ +#ifdef DEBUG + assert(func->get_num_of_args() == args.size()); +#endif +} + +void CallInst::init(Ptr func, PtrVec args, Ptr bb) +{ + Instruction::init(func->get_return_type(), Instruction::call, args.size() + 1, bb); + int num_ops = args.size() + 1; + set_operand(0, func); + for (int i = 1; i < num_ops; i++) { + set_operand(i, args[i-1]); + } +} + +CallInst::CallInst(Ptr ret_ty, PtrVec args, Ptr bb) + : Instruction(ret_ty, Instruction::call, args.size() + 1, bb) +{ + +} + +void CallInst::init(Ptr ret_ty, PtrVec args, Ptr bb) +{ + Instruction::init(ret_ty, Instruction::call, args.size() + 1, bb); + int num_ops = args.size() + 1; + for (int i = 1; i < num_ops; i++) { + set_operand(i, args[i-1]); + } +} + +Ptr CallInst::create(Ptr func, PtrVec args, Ptr bb) +{ + RET_AFTER_INIT(CallInst, func, args, bb); +} + +Ptr CallInst::get_function_type() const +{ + return static_pointer_cast(get_operand(0)->get_type()); +} + +std::string CallInst::print() +{ + std::string instr_ir; + if( !this->is_void() ) + { + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + } + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_function_type()->get_return_type()->print(); + + instr_ir += " "; +#ifdef DEBUG + assert(dynamic_pointer_cast(this->get_operand(0)) && "Wrong call operand function"); +#endif + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += "("; + for (unsigned int i = 1; i < this->get_num_operand(); i++) + { + if( i > 1 ) + instr_ir += ", "; + instr_ir += this->get_operand(i)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(i), false); + } + instr_ir += ")"; + return instr_ir; +} + +BranchInst::BranchInst(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb) + : Instruction(Type::get_void_type(if_true->get_module()), Instruction::br, 3, bb) +{ + +} + +void BranchInst::init(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb) +{ + Instruction::init(Type::get_void_type(if_true->get_module()), Instruction::br, 3, bb); + set_operand(0, cond); + set_operand(1, if_true); + set_operand(2, if_false); +} + +BranchInst::BranchInst(Ptr cond, Ptr bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::br, 3, bb) +{ + +} + +void BranchInst::init(Ptr cond, Ptr bb) +{ + Instruction::init(Type::get_void_type(bb->get_module()), Instruction::br, 3, bb); + set_operand(0, cond); +} + +BranchInst::BranchInst(Ptr if_true, Ptr bb) + : Instruction(Type::get_void_type(if_true->get_module()), Instruction::br, 1, bb) +{ + +} + +void BranchInst::init(Ptr if_true, Ptr bb) +{ + Instruction::init(Type::get_void_type(if_true->get_module()), Instruction::br, 1, bb); + set_operand(0, if_true); +} + +BranchInst::BranchInst(Ptr bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::br, 1, bb) +{ + +} + +void BranchInst::init(Ptr bb) +{ + Instruction::init(Type::get_void_type(bb->get_module()), Instruction::br, 1, bb); +} + +Ptr BranchInst::create_cond_br(Ptr cond, Ptr if_true, Ptr if_false, + Ptr bb) +{ + if_true->add_pre_basic_block(bb); + if_false->add_pre_basic_block(bb); + bb->add_succ_basic_block(if_false); + bb->add_succ_basic_block(if_true); + + RET_AFTER_INIT(BranchInst, cond, if_true, if_false, bb); +} + +Ptr BranchInst::create_br(Ptr if_true, Ptr bb) +{ + if_true->add_pre_basic_block(bb); + bb->add_succ_basic_block(if_true); + + RET_AFTER_INIT(BranchInst, if_true, bb); +} + +bool BranchInst::is_cond_br() const +{ + return get_num_operand() == 3; +} + +std::string BranchInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), true); + if( is_cond_br() ) + { + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(1), true); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(2), true); + } + return instr_ir; +} + +ReturnInst::ReturnInst(Ptr val, Ptr bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::ret, 1, bb) +{ + +} + +void ReturnInst::init(Ptr val, Ptr bb) +{ + Instruction::init(Type::get_void_type(bb->get_module()), Instruction::ret, 1, bb); + set_operand(0, val); +} + +ReturnInst::ReturnInst(Ptr bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::ret, 0, bb) +{ + +} + +void ReturnInst::init(Ptr bb) +{ + Instruction::init(Type::get_void_type(bb->get_module()), Instruction::ret, 0, bb); +} + +Ptr ReturnInst::create_ret(Ptr val, Ptr bb) +{ + RET_AFTER_INIT(ReturnInst, val, bb); +} + +Ptr ReturnInst::create_void_ret(Ptr bb) +{ + RET_AFTER_INIT(ReturnInst, bb); +} + +bool ReturnInst::is_void_ret() const +{ + return get_num_operand() == 0; +} + +std::string ReturnInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + if ( !is_void_ret() ) + { + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + } + else + { + instr_ir += "void"; + } + + return instr_ir; +} + +GetElementPtrInst::GetElementPtrInst(Ptr ptr, PtrVec idxs, Ptr bb) + : Instruction(PointerType::get(get_element_type(ptr, idxs)), Instruction::getelementptr, + 1 + idxs.size(), bb) +{ + +} + +void GetElementPtrInst::init(Ptr ptr, PtrVec idxs, Ptr bb) +{ + Instruction::init(PointerType::get(get_element_type(ptr, idxs)), Instruction::getelementptr, + 1 + idxs.size(), bb); + set_operand(0, ptr); + for (unsigned int i = 0; i < idxs.size(); i++) { + set_operand(i + 1, idxs[i]); + } + element_ty_ = get_element_type(ptr, idxs); +} + +Ptr GetElementPtrInst::get_element_type(Ptr ptr, PtrVec idxs) +{ + + Ptr ty = ptr->get_type()->get_pointer_element_type(); + if (ty->is_array_type()) + { + Ptr arr_ty = static_pointer_cast(ty); + for (unsigned int i = 1; i < idxs.size(); i++) { + ty = arr_ty->get_element_type(); + if (i < idxs.size() - 1) { +#ifdef DEBUG + assert(ty->is_array_type() && "Index error!"); +#endif + } + if (ty->is_array_type()) { + arr_ty = static_pointer_cast(ty); + } + } + } + return ty; +} + +Ptr GetElementPtrInst::get_element_type() const +{ + return element_ty_; +} + +Ptr GetElementPtrInst::create_gep(Ptr ptr, PtrVec idxs, Ptr bb) +{ + RET_AFTER_INIT(GetElementPtrInst, ptr, idxs, bb); +} + +std::string GetElementPtrInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; +#ifdef DEBUG + assert(this->get_operand(0)->get_type()->is_pointer_type()); +#endif + instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print(); + instr_ir += ", "; + for (unsigned int i = 0; i < this->get_num_operand(); i++) + { + if( i > 0 ) + instr_ir += ", "; + instr_ir += this->get_operand(i)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(i), false); + } + return instr_ir; +} + +StoreInst::StoreInst(Ptr val, Ptr ptr, Ptr bb) + : Instruction(Type::get_void_type(bb->get_module()), Instruction::store, 2, bb) +{ + +} + +void StoreInst::init(Ptr val, Ptr ptr, Ptr bb) +{ + Instruction::init(Type::get_void_type(bb->get_module()), Instruction::store, 2, bb); + set_operand(0, val); + set_operand(1, ptr); +} + +Ptr StoreInst::create_store(Ptr val, Ptr ptr, Ptr bb) +{ + RET_AFTER_INIT(StoreInst, val, ptr, bb); +} + +std::string StoreInst::print() +{ + std::string instr_ir; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(1), true); + return instr_ir; +} + +LoadInst::LoadInst(Ptr ty, Ptr ptr, Ptr bb) + : Instruction(ty, Instruction::load, 1, bb) +{ +#ifdef DEBUG + assert(ptr->get_type()->is_pointer_type()); + assert(ty == static_pointer_cast(ptr->get_type())->get_element_type()); +#endif +} + +void LoadInst::init(Ptr ty, Ptr ptr, Ptr bb) +{ + Instruction::init(ty, Instruction::load, 1, bb); + set_operand(0, ptr); +} + +Ptr LoadInst::create_load(Ptr ty, Ptr ptr, Ptr bb) +{ + RET_AFTER_INIT(LoadInst, ty, ptr, bb); +} + +Ptr LoadInst::get_load_type() const +{ + return static_pointer_cast(get_operand(0)->get_type())->get_element_type(); +} + +std::string LoadInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; +#ifdef DEBUG + assert(this->get_operand(0)->get_type()->is_pointer_type()); +#endif + instr_ir += this->get_operand(0)->get_type()->get_pointer_element_type()->print(); + instr_ir += ","; + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), true); + return instr_ir; +} + +AllocaInst::AllocaInst(Ptr ty, Ptr bb) + : Instruction(PointerType::get(ty), Instruction::alloca, 0, bb), alloca_ty_(ty) +{ + +} + +void AllocaInst::init(Ptr ty, Ptr bb) +{ + Instruction::init(PointerType::get(ty), Instruction::alloca, 0, bb); +} + +Ptr AllocaInst::create_alloca(Ptr ty, Ptr bb) +{ + RET_AFTER_INIT(AllocaInst, ty, bb); +} + +Ptr AllocaInst::get_alloca_type() const +{ + return alloca_ty_; +} + +std::string AllocaInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += get_alloca_type()->print(); + return instr_ir; +} + +ZextInst::ZextInst(OpID op, Ptr val, Ptr ty, Ptr bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + +} + +void ZextInst::init(OpID op, Ptr val, Ptr ty, Ptr bb) +{ + Instruction::init(ty, op, 1, bb); + set_operand(0, val); +} + +Ptr ZextInst::create_zext(Ptr val, Ptr ty, Ptr bb) +{ + RET_AFTER_INIT(ZextInst, Instruction::zext, val, ty, bb); +} + +Ptr ZextInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string ZextInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +FpToSiInst::FpToSiInst(OpID op, Ptr val, Ptr ty, Ptr bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + +} + +void FpToSiInst::init(OpID op, Ptr val, Ptr ty, Ptr bb) +{ + Instruction::init(ty, op, 1, bb); + set_operand(0, val); +} + +Ptr FpToSiInst::create_fptosi(Ptr val, Ptr ty, Ptr bb) +{ + RET_AFTER_INIT(FpToSiInst, Instruction::fptosi, val, ty, bb); +} + +Ptr FpToSiInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string FpToSiInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +SiToFpInst::SiToFpInst(OpID op, Ptr val, Ptr ty, Ptr bb) + : Instruction(ty, op, 1, bb), dest_ty_(ty) +{ + +} + +void SiToFpInst::init(OpID op, Ptr val, Ptr ty, Ptr bb) +{ + Instruction::init(ty, op, 1, bb); + set_operand(0, val); +} + +Ptr SiToFpInst::create_sitofp(Ptr val, Ptr ty, Ptr bb) +{ + RET_AFTER_INIT(SiToFpInst, Instruction::sitofp, val, ty, bb); +} + +Ptr SiToFpInst::get_dest_type() const +{ + return dest_ty_; +} + +std::string SiToFpInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + instr_ir += print_as_op(this->get_operand(0), false); + instr_ir += " to "; + instr_ir += this->get_dest_type()->print(); + return instr_ir; +} + +PhiInst::PhiInst(OpID op, PtrVec vals, PtrVec val_bbs, Ptr ty, Ptr bb) + : Instruction(ty, op, 2*vals.size()) +{ + +} + +void PhiInst::init(OpID op, PtrVec vals, PtrVec val_bbs, Ptr ty, Ptr bb) +{ + Instruction::init(ty, op, 2*vals.size()); + for (unsigned int i = 0; i < vals.size(); i++) + { + set_operand(2*i, vals[i]); + set_operand(2*i+1, val_bbs[i]); + } + this->set_parent(bb); +} + +Ptr PhiInst::create_phi( Ptr ty, Ptr bb) +{ + PtrVec vals; + PtrVec val_bbs; + RET_AFTER_INIT(PhiInst, Instruction::phi, vals, val_bbs, ty, bb); +} + +std::string PhiInst::print() +{ + std::string instr_ir; + instr_ir += "%"; + instr_ir += this->get_name(); + instr_ir += " = "; + instr_ir += this->get_module()->get_instr_op_name( this->get_instr_type() ); + instr_ir += " "; + instr_ir += this->get_operand(0)->get_type()->print(); + instr_ir += " "; + for (unsigned int i = 0; i < this->get_num_operand()/2; i++) + { + if( i > 0 ) + instr_ir += ", "; + instr_ir += "[ "; + instr_ir += print_as_op(this->get_operand(2*i), false); + instr_ir += ", "; + instr_ir += print_as_op(this->get_operand(2*i+1), false); + instr_ir += " ]"; + } + if ( this->get_num_operand()/2 < this->get_parent()->get_pre_basic_blocks().size() ) + { + for ( auto pre_bb : this->get_parent()->get_pre_basic_blocks() ) + { + if (std::find(this->get_operands().begin(), this->get_operands().end(), static_pointer_cast(pre_bb)) == this->get_operands().end()) + { + // find a pre_bb is not in phi + instr_ir += ", [ undef, " +print_as_op(pre_bb, false)+" ]"; + } + } + } + return instr_ir; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/Module.cpp b/src/SysYFIR/Module.cpp new file mode 100644 index 0000000..5ddfcc3 --- /dev/null +++ b/src/SysYFIR/Module.cpp @@ -0,0 +1,144 @@ +#include "Module.h" + +namespace SysYF +{ +namespace IR +{ +Module::Module(std::string name) + : module_name_(name) +{ + // init instr_id2string + instr_id2string_.insert({ Instruction::ret, "ret" }); + instr_id2string_.insert({ Instruction::br, "br" }); + + instr_id2string_.insert({ Instruction::add, "add" }); + instr_id2string_.insert({ Instruction::sub, "sub" }); + instr_id2string_.insert({ Instruction::mul, "mul" }); + instr_id2string_.insert({ Instruction::sdiv, "sdiv" }); + instr_id2string_.insert({ Instruction::srem, "srem" }); + + instr_id2string_.insert({ Instruction::fadd, "fadd" }); + instr_id2string_.insert({ Instruction::fsub, "fsub" }); + instr_id2string_.insert({ Instruction::fmul, "fmul" }); + instr_id2string_.insert({ Instruction::fdiv, "fdiv" }); + + instr_id2string_.insert({ Instruction::alloca, "alloca" }); + instr_id2string_.insert({ Instruction::load, "load" }); + instr_id2string_.insert({ Instruction::store, "store" }); + instr_id2string_.insert({ Instruction::cmp, "icmp" }); + instr_id2string_.insert({ Instruction::fcmp, "fcmp" }); + instr_id2string_.insert({ Instruction::phi, "phi" }); + instr_id2string_.insert({ Instruction::call, "call" }); + instr_id2string_.insert({ Instruction::getelementptr, "getelementptr" }); + instr_id2string_.insert({ Instruction::zext, "zext" }); + instr_id2string_.insert({ Instruction::fptosi, "fptosi" }); + instr_id2string_.insert({ Instruction::sitofp, "sitofp" }); +} + +void Module::init(std::string name) { + void_ty_ = Type::create(Type::VoidTyID, shared_from_this()); + label_ty_ = Type::create(Type::LabelTyID, shared_from_this()); + int1_ty_ = IntegerType::create(1, shared_from_this()); + int32_ty_ = IntegerType::create(32, shared_from_this()); + float32_ty_ = FloatType::create(shared_from_this()); +} + +Ptr Module::create(std::string name) { + RET_AFTER_INIT(Module, name); +} + +Ptr Module::get_void_type() +{ + return void_ty_; +} + +Ptr Module::get_label_type() +{ + return label_ty_; +} + +Ptr Module::get_int1_type() +{ + return int1_ty_; +} + +Ptr Module::get_int32_type() +{ + return int32_ty_; +} + +Ptr Module::get_float_type() +{ + return float32_ty_; +} + +Ptr Module::get_pointer_type(Ptr contained) +{ + if( pointer_map_.find(contained) == pointer_map_.end() ) + { + pointer_map_[contained] = PointerType::create(contained); + } + return pointer_map_[contained]; +} + +Ptr Module::get_array_type(Ptr contained, unsigned num_elements) +{ + if( array_map_.find({contained, num_elements}) == array_map_.end() ) + { + array_map_[{contained, num_elements}] = ArrayType::create(contained, num_elements); + } + return array_map_[{contained, num_elements}]; +} + +Ptr Module::get_int32_ptr_type() +{ + return get_pointer_type(int32_ty_); +} + +Ptr Module::get_float_ptr_type() +{ + return get_pointer_type(float32_ty_); +} + +void Module::add_function(Ptr f) +{ + function_list_.push_back(f); +} +PtrList &Module::get_functions(){ + return function_list_; +} +void Module::add_global_variable(Ptr g) +{ + global_list_.push_back(g); +} +PtrList &Module::get_global_variable(){ + return global_list_; +} + +void Module::set_print_name() +{ + for (auto func : this->get_functions()) + { + func->set_instr_name(); + } + return ; +} + +std::string Module::print() +{ + std::string module_ir; + for ( auto global_val : this->global_list_) + { + module_ir += global_val->print(); + module_ir += "\n"; + } + for ( auto func : this->function_list_) + { + module_ir += func->print(); + module_ir += "\n"; + } + return module_ir; +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/Type.cpp b/src/SysYFIR/Type.cpp new file mode 100644 index 0000000..bc003ae --- /dev/null +++ b/src/SysYFIR/Type.cpp @@ -0,0 +1,284 @@ +#include "Type.h" +#include "Module.h" + +#ifdef DEBUG +#include +#endif + +namespace SysYF +{ +namespace IR +{ +Type::Type(TypeID tid, Ptr m) +{ + tid_ = tid; + m_ = m; +} + +Ptr Type::create(TypeID tid, Ptr m) +{ + RET_AFTER_INIT(Type, tid, m); +} + +Ptr Type::get_module() +{ + return m_; +} + +bool Type::is_eq_type(Ptr ty1, Ptr ty2) +{ + return ty1 == ty2; +} + +Ptr Type::get_void_type(Ptr m) +{ + return m->get_void_type(); +} + +Ptr Type::get_label_type(Ptr m) +{ + return m->get_label_type(); +} + +Ptr Type::get_int1_type(Ptr m) +{ + return m->get_int1_type(); +} + +Ptr Type::get_int32_type(Ptr m) +{ + return m->get_int32_type(); +} + +Ptr Type::get_float_type(Ptr m) +{ + return m->get_float_type(); +} + +Ptr Type::get_pointer_type(Ptr contained) +{ + return PointerType::get(contained); +} + +Ptr Type::get_array_type(Ptr contained, unsigned num_elements) +{ + return ArrayType::get(contained, num_elements); +} + +Ptr Type::get_int32_ptr_type(Ptr m) +{ + return m->get_int32_ptr_type(); +} + +Ptr Type::get_float_ptr_type(Ptr m) +{ + return m->get_float_ptr_type(); +} + +Ptr Type::get_pointer_element_type(){ + if( this->is_pointer_type() ) + return static_pointer_cast(shared_from_this())->get_element_type(); + else + return nullptr; +} + +Ptr Type::get_array_element_type(){ + if( this->is_array_type() ) + return static_pointer_cast(shared_from_this())->get_element_type(); + else + return nullptr; +} + +int Type::get_size() +{ + if (this->is_integer_type()) + { + auto bits = static_pointer_cast(shared_from_this())->get_num_bits() / 8; + return bits > 0 ? bits : 1; + } + if (this->is_float_type()) + { + return 4; + } + if (this->is_array_type()) + { + auto element_size = static_pointer_cast(shared_from_this())->get_element_type()->get_size(); + auto num_elements = static_pointer_cast(shared_from_this())->get_num_of_elements(); + return element_size * num_elements; + } + if (this->is_pointer_type()) + { + if (this->get_pointer_element_type()->is_array_type()) + { + return this->get_pointer_element_type()->get_size(); + } + else + { + return 4; + } + } + return 0; +} + +std::string Type::print(){ + std::string type_ir; + switch (this->get_type_id()) + { + case VoidTyID: + type_ir += "void"; + break; + case LabelTyID: + type_ir += "label"; + break; + case IntegerTyID: + type_ir += "i"; + type_ir += std::to_string( static_pointer_cast(shared_from_this())->get_num_bits()); + break; + case FloatTyID: + type_ir += "float"; + break; + case FunctionTyID: + type_ir += static_pointer_cast(shared_from_this())->get_return_type()->print(); + type_ir += " ("; + for(unsigned int i = 0 ; i < static_pointer_cast(shared_from_this())->get_num_of_args() ; i++) + { + if(i) + type_ir += ", "; + type_ir += static_pointer_cast(shared_from_this())->get_param_type(i)->print(); + } + type_ir += ")"; + break; + case PointerTyID: + type_ir += this->get_pointer_element_type()->print(); + type_ir += "*"; + break; + case ArrayTyID: + type_ir += "["; + type_ir += std::to_string( static_pointer_cast(shared_from_this())->get_num_of_elements()); + type_ir += " x "; + type_ir += static_pointer_cast(shared_from_this())->get_element_type()->print(); + type_ir += "]"; + break; + default: + break; + } + return type_ir; +} + +IntegerType::IntegerType(unsigned num_bits , Ptr m) + : Type(Type::IntegerTyID, m), num_bits_(num_bits) +{ + +} + + +Ptr IntegerType::create(unsigned num_bits, Ptr m ) +{ + RET_AFTER_INIT(IntegerType, num_bits, m); +} + +unsigned IntegerType::get_num_bits() +{ + return num_bits_; +} + +FloatType::FloatType(Ptr m) + : Type(Type::FloatTyID, m) +{ + +} + +Ptr FloatType::create(Ptr m ) +{ + RET_AFTER_INIT(FloatType, m); +} + +FunctionType::FunctionType(Ptr result, PtrVec params) + : Type(Type::FunctionTyID, nullptr) +{ +#ifdef DEBUG + assert(is_valid_return_type(result) && "Invalid return type for function!"); +#endif + result_ = result; + + for (auto p : params) { +#ifdef DEBUG + assert(is_valid_argument_type(p) && + "Not a valid type for function argument!"); +#endif + args_.push_back(p); + } +} + +Ptr FunctionType::create(Ptr result, PtrVec params) +{ + RET_AFTER_INIT(FunctionType, result, params); +} + +bool FunctionType::is_valid_return_type(Ptr ty) +{ + return ty->is_integer_type() || ty->is_void_type(); +} + +bool FunctionType::is_valid_argument_type(Ptr ty) +{ + return ty->is_integer_type() || ty->is_pointer_type(); +} + +unsigned FunctionType::get_num_of_args() const +{ + return args_.size(); +} + +Ptr FunctionType::get_param_type(unsigned i) const +{ + return args_[i]; +} + +Ptr FunctionType::get_return_type() const +{ + return result_; +} + +ArrayType::ArrayType(Ptr contained, unsigned num_elements) + : Type(Type::ArrayTyID, contained->get_module()), num_elements_(num_elements) +{ +#ifdef DEBUG + assert(is_valid_element_type(contained) && "Not a valid type for array element!"); +#endif + contained_ = contained; +} + +bool ArrayType::is_valid_element_type(Ptr ty) +{ + return ty->is_integer_type()||ty->is_array_type()||ty->is_float_type(); +} + +Ptr ArrayType::get(Ptr contained, unsigned num_elements) +{ + return contained->get_module()->get_array_type(contained, num_elements); +} + +Ptr ArrayType::create(Ptr contained, unsigned num_elements) +{ + RET_AFTER_INIT(ArrayType, contained, num_elements); +} + +PointerType::PointerType(Ptr contained) + : Type(Type::PointerTyID, contained->get_module()), contained_(contained) +{ + +} + +Ptr PointerType::get(Ptr contained) +{ + return contained->get_module()->get_pointer_type(contained); +} + +Ptr PointerType::create(Ptr contained) +{ + RET_AFTER_INIT(PointerType, contained); +} + +} +} \ No newline at end of file diff --git a/src/SysYFIR/User.cpp b/src/SysYFIR/User.cpp new file mode 100644 index 0000000..1fdacb8 --- /dev/null +++ b/src/SysYFIR/User.cpp @@ -0,0 +1,67 @@ +#include "User.h" +#ifdef DEBUG +#include +#endif + +namespace SysYF +{ +namespace IR +{ +User::User(Ptr ty, const std::string &name , unsigned num_ops) + : Value(ty, name), num_ops_(num_ops) +{ + // if (num_ops_ > 0) + // operands_.reset(new std::list >()); + operands_.resize(num_ops_, nullptr); +} + +PtrVec& User::get_operands() +{ + return operands_; +} + +Ptr User::get_operand(unsigned i) const +{ + return operands_[i]; +} + +void User::set_operand(unsigned i, Ptr v) +{ +#ifdef DEBUG + assert(i < num_ops_ && "set_operand out of index"); +#endif + // assert(operands_[i] == nullptr && "ith operand is not null"); + operands_[i] = v; + v->add_use(shared_from_this(), i); +} + +void User::add_operand(Ptr v) +{ + operands_.push_back(v); + v->add_use(shared_from_this(), num_ops_); + num_ops_++; +} + +unsigned User::get_num_operand() const +{ + return num_ops_; +} + +void User::remove_use_of_ops() +{ + for (auto op : operands_) { + op->remove_use(shared_from_this()); + } +} + +void User::remove_operands(int index1,int index2){ + for(int i=index1;i<=index2;i++){ + operands_[i]->remove_use(shared_from_this()); + } + operands_.erase(operands_.begin()+index1,operands_.begin()+index2+1); + // std::cout< +#endif + +namespace SysYF +{ +namespace IR +{ +Value::Value(Ptr ty, const std::string &name) + : type_(ty), name_(name) +{ + +} + +void Value::add_use(Ptr val, unsigned arg_no) +{ + use_list_.push_back(Use(val, arg_no)); +} + +std::string Value::get_name() const +{ + return name_; +} + +void Value::replace_all_use_with(Ptr new_val) +{ + for (auto use : use_list_) { + auto val = dynamic_pointer_cast(use.val_); +#ifdef DEBUG + assert(val && "new_val is not a user"); +#endif + val->set_operand(use.arg_no_, new_val); + } +} + +void Value::remove_use(Ptr val) +{ + auto is_val = [val] (const Use &use) { return use.val_ == val; }; + use_list_.remove_if(is_val); +} + +} +} \ No newline at end of file diff --git a/src/SysYFIRBuilder/CMakeLists.txt b/src/SysYFIRBuilder/CMakeLists.txt new file mode 100644 index 0000000..59aec00 --- /dev/null +++ b/src/SysYFIRBuilder/CMakeLists.txt @@ -0,0 +1,4 @@ +add_library( + SysYFIRBuilder STATIC + IRBuilder.cpp +) diff --git a/src/SysYFIRBuilder/IRBuilder.cpp b/src/SysYFIRBuilder/IRBuilder.cpp new file mode 100644 index 0000000..951bd45 --- /dev/null +++ b/src/SysYFIRBuilder/IRBuilder.cpp @@ -0,0 +1,81 @@ +#include "IRBuilder.h" + +namespace SysYF +{ +namespace IR +{ +#define CONST_INT(num) ConstantInt::create(num, module) +#define CONST_FLOAT(num) ConstantFloat::create(num, module) + +// You can define global variables here +// to store state + +// store temporary value +Ptr tmp_val = nullptr; + +// types +Ptr VOID_T; +Ptr INT1_T; +Ptr INT32_T; +Ptr FLOAT_T; +Ptr INT32PTR_T; +Ptr FLOATPTR_T; + +void IRBuilder::visit(SyntaxTree::Assembly &node) { + VOID_T = Type::get_void_type(module); + INT1_T = Type::get_int1_type(module); + INT32_T = Type::get_int32_type(module); + FLOAT_T = Type::get_float_type(module); + INT32PTR_T = Type::get_int32_ptr_type(module); + FLOATPTR_T = Type::get_float_ptr_type(module); + for (const auto &def : node.global_defs) { + def->accept(*this); + } +} + +// You need to fill them + +void IRBuilder::visit(SyntaxTree::InitVal &node) {} + +void IRBuilder::visit(SyntaxTree::FuncDef &node) {} + +void IRBuilder::visit(SyntaxTree::FuncFParamList &node) {} + +void IRBuilder::visit(SyntaxTree::FuncParam &node) {} + +void IRBuilder::visit(SyntaxTree::VarDef &node) {} + +void IRBuilder::visit(SyntaxTree::LVal &node) {} + +void IRBuilder::visit(SyntaxTree::AssignStmt &node) {} + +void IRBuilder::visit(SyntaxTree::Literal &node) {} + +void IRBuilder::visit(SyntaxTree::ReturnStmt &node) {} + +void IRBuilder::visit(SyntaxTree::BlockStmt &node) {} + +void IRBuilder::visit(SyntaxTree::EmptyStmt &node) {} + +void IRBuilder::visit(SyntaxTree::ExprStmt &node) {} + +void IRBuilder::visit(SyntaxTree::UnaryCondExpr &node) {} + +void IRBuilder::visit(SyntaxTree::BinaryCondExpr &node) {} + +void IRBuilder::visit(SyntaxTree::BinaryExpr &node) {} + +void IRBuilder::visit(SyntaxTree::UnaryExpr &node) {} + +void IRBuilder::visit(SyntaxTree::FuncCallStmt &node) {} + +void IRBuilder::visit(SyntaxTree::IfStmt &node) {} + +void IRBuilder::visit(SyntaxTree::WhileStmt &node) {} + +void IRBuilder::visit(SyntaxTree::BreakStmt &node) {} + +void IRBuilder::visit(SyntaxTree::ContinueStmt &node) {} + +} +} \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100755 index 0000000..cae2b75 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,61 @@ +#include +#include "IRBuilder.h" +#include "SysYFDriver.h" +#include "SyntaxTreePrinter.h" +#include "ErrorReporter.h" + + +void print_help(const std::string& exe_name) { + std::cout << "Usage: " << exe_name + << " [ -h | --help ] [ -p | --trace_parsing ] [ -s | --trace_scanning ] [ -emit-ast ] [ -emit-ir ] [ -o ]" + << " " + << std::endl; +} + +int main(int argc, char *argv[]) +{ + SysYFDriver driver; + SysYF::SyntaxTree::SyntaxTreePrinter printer; + auto builder = SysYF::IR::IRBuilder::create(); + + bool print_ast = false; + bool print_ir = false; + + std::string filename = "testcase.sy"; + std::string output_llvm_file = "testcase.ll"; + for (int i = 1; i < argc; ++i) { + if (argv[i] == std::string("-h") || argv[i] == std::string("--help")) { + print_help(argv[0]); + return 0; + } + else if (argv[i] == std::string("-p") || argv[i] == std::string("--trace_parsing")) + driver.trace_parsing = true; + else if (argv[i] == std::string("-s") || argv[i] == std::string("--trace_scanning")) + driver.trace_scanning = true; + else if (argv[i] == std::string("-emit-ast")) + print_ast = true; + else if (argv[i] == std::string("-emit-ir")) + print_ir = true; + else if (argv[i] == std::string("-o")){ + output_llvm_file = argv[++i]; + } + else { + filename = argv[i]; + } + } + auto root = driver.parse(filename); + if (print_ast) + root->accept(printer); + if (print_ir) { + root->accept(*builder); + auto m = builder->getModule(); + m->set_file_name(filename); + m->set_print_name(); + auto IR = m->print(); + std::ofstream output_stream; + output_stream.open(output_llvm_file, std::ios::out); + output_stream << IR; + output_stream.close(); + } + return 0; +}