In this recipe, you will see how IR code gets generated for an expression using the compiler frontend.
To implement LLVM IR code generation for our TOY language, proceed with the following code flow:
toy.cpp
file as follows:$ vi toy.cpp
Value *NumericAST::Codegen() { return ConstantInt::get(Type::getInt32Ty(getGlobalContext()), numeric_val); }
In LLVM IR, integer constants are represented by the ConstantInt
class whose numeric value is held by the APInt
class.
Value *VariableAST::Codegen() { Value *V = Named_Values[Var_Name]; return V ? V : 0; }
Codegen()
function for binary expression can be defined as follows:Value *BinaryAST::Codegen() { Value *L = LHS->Codegen(); Value *R = RHS->Codegen(); if(L == 0 || R == 0) return 0; switch(atoi(Bin_Operator.c_str())) { case '+' : return Builder.CreateAdd(L, R, "addtmp"); case '-' : return Builder.CreateSub(L, R, "subtmp"); case '*' : return Builder.CreateMul(L, R, "multmp"); case '/' : return Builder.CreateUDiv(L, R, "divtmp"); default : return 0; } }
If the code above emits multiple addtmp
variables, LLVM will automatically provide each one with an increasing, unique numeric suffix.
3.135.216.75