Generating IR code for expressions

In this recipe, you will see how IR code gets generated for an expression using the compiler frontend.

How to do it…

To implement LLVM IR code generation for our TOY language, proceed with the following code flow:

  1. Open the toy.cpp file as follows:
    $ vi toy.cpp
  2. The function to generate code for numeric values can be defined as follows:
    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.

  3. The function for generating code for variable expressions can be defined as follows:
    Value *VariableAST::Codegen() {
      Value *V = Named_Values[Var_Name];
      return V ? V : 0;
    }
  4. The 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.

See also

  • The next recipe shows how to generate IR code for function; we will learn how the code generation actually works.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.255.140