如何在中间代码上执行恒定折叠和恒定传播?

时间:2019-04-21 16:25:53

标签: c compiler-construction constantfolding intermediate-code

因此,我的编译器为if else和while(这些构造在C中,即编译器是接受while和if-else的C编译器)生成中间代码,并将其存储在文件中。

我知道恒定折叠和恒定传播如何工作的理论方面。但是,当我读取带有中间代码的文件时,实际上该如何编码和实现它。

如果有人也可以给我一个基本的算法/伪代码,那太好了,因为我发现仅阅读文本文件就很难实现它。

1 个答案:

答案 0 :(得分:0)

使用IR读取文本文件时,编译器不起作用。它应该为IR提供方便的数据结构并能够对其进行转换。关于恒定折叠或恒定传播的算法,您最好在适当的书中阅读它们。例如S.S. Muchnick的Advanced Compiler Design and Implementation

简而言之,恒定折叠如下:

const_fold(instr):
  if is_bin_exp(instr.oper):
    if is_const(instr.arg1) && is_const(instr.arg2):
      return = perform_bin(instr.oper, instr.arg1, instr.arg2)
  if is_un_exp(instr.oper):
    if is_const(instr.arg1):
      return = perform_un(instr.oper, instr.arg1)
  return Null