How llvm do constantfolding?

Hi, I have been learning llvm recently, I have searched a lot of materials but I cannot find how llvm does constant folding. Is there any talk or slides about this? pseudocode is highly appreciated!

Constant folding as an IR optimization is what the literature refers to as a “peephole optimization”: taking an instruction with certain operands, and replacing it with a simpler equivalent. Once you understand peephole optimizations in general, there’s not much to say about constant folding specifically, so people don’t tend to talk about it much.

See https://github.com/llvm/llvm-project/blob/181e8065ed56a3c3c3686c091e901e3481321840/llvm/lib/IR/ConstantFold.cpp#L920 for code that constant-folds “add” operations.

I found a file named ConstantFolding.h. So could you please tell me what is the difference between ConstantFolding.h and ConstantFold.h? thank you!

The complexity there involves the datalayout. Certain forms of constant folding require knowing details about the sizes of types, so constant folding is split into two parts: the part that requires the datalayout, and the part that doesn’t. If you’re interested in the history of it, make DataLayout a mandatory part of Module should give you some idea why it works this way.

1 Like