Home | History | Annotate | Download | only in tutorial
      1 ==================================================
      2 Kaleidoscope: Extending the Language: Control Flow
      3 ==================================================
      4 
      5 .. contents::
      6    :local:
      7 
      8 Chapter 5 Introduction
      9 ======================
     10 
     11 Welcome to Chapter 5 of the "`Implementing a language with
     12 LLVM <index.html>`_" tutorial. Parts 1-4 described the implementation of
     13 the simple Kaleidoscope language and included support for generating
     14 LLVM IR, followed by optimizations and a JIT compiler. Unfortunately, as
     15 presented, Kaleidoscope is mostly useless: it has no control flow other
     16 than call and return. This means that you can't have conditional
     17 branches in the code, significantly limiting its power. In this episode
     18 of "build that compiler", we'll extend Kaleidoscope to have an
     19 if/then/else expression plus a simple 'for' loop.
     20 
     21 If/Then/Else
     22 ============
     23 
     24 Extending Kaleidoscope to support if/then/else is quite straightforward.
     25 It basically requires adding support for this "new" concept to the
     26 lexer, parser, AST, and LLVM code emitter. This example is nice, because
     27 it shows how easy it is to "grow" a language over time, incrementally
     28 extending it as new ideas are discovered.
     29 
     30 Before we get going on "how" we add this extension, lets talk about
     31 "what" we want. The basic idea is that we want to be able to write this
     32 sort of thing:
     33 
     34 ::
     35 
     36     def fib(x)
     37       if x < 3 then
     38         1
     39       else
     40         fib(x-1)+fib(x-2);
     41 
     42 In Kaleidoscope, every construct is an expression: there are no
     43 statements. As such, the if/then/else expression needs to return a value
     44 like any other. Since we're using a mostly functional form, we'll have
     45 it evaluate its conditional, then return the 'then' or 'else' value
     46 based on how the condition was resolved. This is very similar to the C
     47 "?:" expression.
     48 
     49 The semantics of the if/then/else expression is that it evaluates the
     50 condition to a boolean equality value: 0.0 is considered to be false and
     51 everything else is considered to be true. If the condition is true, the
     52 first subexpression is evaluated and returned, if the condition is
     53 false, the second subexpression is evaluated and returned. Since
     54 Kaleidoscope allows side-effects, this behavior is important to nail
     55 down.
     56 
     57 Now that we know what we "want", lets break this down into its
     58 constituent pieces.
     59 
     60 Lexer Extensions for If/Then/Else
     61 ---------------------------------
     62 
     63 The lexer extensions are straightforward. First we add new enum values
     64 for the relevant tokens:
     65 
     66 .. code-block:: c++
     67 
     68       // control
     69       tok_if = -6,
     70       tok_then = -7,
     71       tok_else = -8,
     72 
     73 Once we have that, we recognize the new keywords in the lexer. This is
     74 pretty simple stuff:
     75 
     76 .. code-block:: c++
     77 
     78         ...
     79         if (IdentifierStr == "def")
     80           return tok_def;
     81         if (IdentifierStr == "extern")
     82           return tok_extern;
     83         if (IdentifierStr == "if")
     84           return tok_if;
     85         if (IdentifierStr == "then")
     86           return tok_then;
     87         if (IdentifierStr == "else")
     88           return tok_else;
     89         return tok_identifier;
     90 
     91 AST Extensions for If/Then/Else
     92 -------------------------------
     93 
     94 To represent the new expression we add a new AST node for it:
     95 
     96 .. code-block:: c++
     97 
     98     /// IfExprAST - Expression class for if/then/else.
     99     class IfExprAST : public ExprAST {
    100       std::unique_ptr<ExprAST> Cond, Then, Else;
    101 
    102     public:
    103       IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
    104                 std::unique_ptr<ExprAST> Else)
    105         : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
    106       virtual Value *codegen();
    107     };
    108 
    109 The AST node just has pointers to the various subexpressions.
    110 
    111 Parser Extensions for If/Then/Else
    112 ----------------------------------
    113 
    114 Now that we have the relevant tokens coming from the lexer and we have
    115 the AST node to build, our parsing logic is relatively straightforward.
    116 First we define a new parsing function:
    117 
    118 .. code-block:: c++
    119 
    120     /// ifexpr ::= 'if' expression 'then' expression 'else' expression
    121     static std::unique_ptr<ExprAST> ParseIfExpr() {
    122       getNextToken();  // eat the if.
    123 
    124       // condition.
    125       auto Cond = ParseExpression();
    126       if (!Cond)
    127         return nullptr;
    128 
    129       if (CurTok != tok_then)
    130         return Error("expected then");
    131       getNextToken();  // eat the then
    132 
    133       auto Then = ParseExpression();
    134       if (!Then)
    135         return nullptr;
    136 
    137       if (CurTok != tok_else)
    138         return Error("expected else");
    139 
    140       getNextToken();
    141 
    142       auto Else = ParseExpression();
    143       if (!Else)
    144         return nullptr;
    145 
    146       return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
    147                                           std::move(Else));
    148     }
    149 
    150 Next we hook it up as a primary expression:
    151 
    152 .. code-block:: c++
    153 
    154     static std::unique_ptr<ExprAST> ParsePrimary() {
    155       switch (CurTok) {
    156       default:
    157         return Error("unknown token when expecting an expression");
    158       case tok_identifier:
    159         return ParseIdentifierExpr();
    160       case tok_number:
    161         return ParseNumberExpr();
    162       case '(':
    163         return ParseParenExpr();
    164       case tok_if:
    165         return ParseIfExpr();
    166       }
    167     }
    168 
    169 LLVM IR for If/Then/Else
    170 ------------------------
    171 
    172 Now that we have it parsing and building the AST, the final piece is
    173 adding LLVM code generation support. This is the most interesting part
    174 of the if/then/else example, because this is where it starts to
    175 introduce new concepts. All of the code above has been thoroughly
    176 described in previous chapters.
    177 
    178 To motivate the code we want to produce, lets take a look at a simple
    179 example. Consider:
    180 
    181 ::
    182 
    183     extern foo();
    184     extern bar();
    185     def baz(x) if x then foo() else bar();
    186 
    187 If you disable optimizations, the code you'll (soon) get from
    188 Kaleidoscope looks like this:
    189 
    190 .. code-block:: llvm
    191 
    192     declare double @foo()
    193 
    194     declare double @bar()
    195 
    196     define double @baz(double %x) {
    197     entry:
    198       %ifcond = fcmp one double %x, 0.000000e+00
    199       br i1 %ifcond, label %then, label %else
    200 
    201     then:       ; preds = %entry
    202       %calltmp = call double @foo()
    203       br label %ifcont
    204 
    205     else:       ; preds = %entry
    206       %calltmp1 = call double @bar()
    207       br label %ifcont
    208 
    209     ifcont:     ; preds = %else, %then
    210       %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
    211       ret double %iftmp
    212     }
    213 
    214 To visualize the control flow graph, you can use a nifty feature of the
    215 LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
    216 IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
    217 window will pop up <../ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ and you'll
    218 see this graph:
    219 
    220 .. figure:: LangImpl5-cfg.png
    221    :align: center
    222    :alt: Example CFG
    223 
    224    Example CFG
    225 
    226 Another way to get this is to call "``F->viewCFG()``" or
    227 "``F->viewCFGOnly()``" (where F is a "``Function*``") either by
    228 inserting actual calls into the code and recompiling or by calling these
    229 in the debugger. LLVM has many nice features for visualizing various
    230 graphs.
    231 
    232 Getting back to the generated code, it is fairly simple: the entry block
    233 evaluates the conditional expression ("x" in our case here) and compares
    234 the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
    235 and Not Equal"). Based on the result of this expression, the code jumps
    236 to either the "then" or "else" blocks, which contain the expressions for
    237 the true/false cases.
    238 
    239 Once the then/else blocks are finished executing, they both branch back
    240 to the 'ifcont' block to execute the code that happens after the
    241 if/then/else. In this case the only thing left to do is to return to the
    242 caller of the function. The question then becomes: how does the code
    243 know which expression to return?
    244 
    245 The answer to this question involves an important SSA operation: the
    246 `Phi
    247 operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
    248 If you're not familiar with SSA, `the wikipedia
    249 article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
    250 is a good introduction and there are various other introductions to it
    251 available on your favorite search engine. The short version is that
    252 "execution" of the Phi operation requires "remembering" which block
    253 control came from. The Phi operation takes on the value corresponding to
    254 the input control block. In this case, if control comes in from the
    255 "then" block, it gets the value of "calltmp". If control comes from the
    256 "else" block, it gets the value of "calltmp1".
    257 
    258 At this point, you are probably starting to think "Oh no! This means my
    259 simple and elegant front-end will have to start generating SSA form in
    260 order to use LLVM!". Fortunately, this is not the case, and we strongly
    261 advise *not* implementing an SSA construction algorithm in your
    262 front-end unless there is an amazingly good reason to do so. In
    263 practice, there are two sorts of values that float around in code
    264 written for your average imperative programming language that might need
    265 Phi nodes:
    266 
    267 #. Code that involves user variables: ``x = 1; x = x + 1;``
    268 #. Values that are implicit in the structure of your AST, such as the
    269    Phi node in this case.
    270 
    271 In `Chapter 7 <LangImpl7.html>`_ of this tutorial ("mutable variables"),
    272 we'll talk about #1 in depth. For now, just believe me that you don't
    273 need SSA construction to handle this case. For #2, you have the choice
    274 of using the techniques that we will describe for #1, or you can insert
    275 Phi nodes directly, if convenient. In this case, it is really
    276 easy to generate the Phi node, so we choose to do it directly.
    277 
    278 Okay, enough of the motivation and overview, lets generate code!
    279 
    280 Code Generation for If/Then/Else
    281 --------------------------------
    282 
    283 In order to generate code for this, we implement the ``codegen`` method
    284 for ``IfExprAST``:
    285 
    286 .. code-block:: c++
    287 
    288     Value *IfExprAST::codegen() {
    289       Value *CondV = Cond->codegen();
    290       if (!CondV)
    291         return nullptr;
    292 
    293       // Convert condition to a bool by comparing equal to 0.0.
    294       CondV = Builder.CreateFCmpONE(
    295           CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
    296 
    297 This code is straightforward and similar to what we saw before. We emit
    298 the expression for the condition, then compare that value to zero to get
    299 a truth value as a 1-bit (bool) value.
    300 
    301 .. code-block:: c++
    302 
    303       Function *TheFunction = Builder.GetInsertBlock()->getParent();
    304 
    305       // Create blocks for the then and else cases.  Insert the 'then' block at the
    306       // end of the function.
    307       BasicBlock *ThenBB =
    308           BasicBlock::Create(getGlobalContext(), "then", TheFunction);
    309       BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
    310       BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
    311 
    312       Builder.CreateCondBr(CondV, ThenBB, ElseBB);
    313 
    314 This code creates the basic blocks that are related to the if/then/else
    315 statement, and correspond directly to the blocks in the example above.
    316 The first line gets the current Function object that is being built. It
    317 gets this by asking the builder for the current BasicBlock, and asking
    318 that block for its "parent" (the function it is currently embedded
    319 into).
    320 
    321 Once it has that, it creates three blocks. Note that it passes
    322 "TheFunction" into the constructor for the "then" block. This causes the
    323 constructor to automatically insert the new block into the end of the
    324 specified function. The other two blocks are created, but aren't yet
    325 inserted into the function.
    326 
    327 Once the blocks are created, we can emit the conditional branch that
    328 chooses between them. Note that creating new blocks does not implicitly
    329 affect the IRBuilder, so it is still inserting into the block that the
    330 condition went into. Also note that it is creating a branch to the
    331 "then" block and the "else" block, even though the "else" block isn't
    332 inserted into the function yet. This is all ok: it is the standard way
    333 that LLVM supports forward references.
    334 
    335 .. code-block:: c++
    336 
    337       // Emit then value.
    338       Builder.SetInsertPoint(ThenBB);
    339 
    340       Value *ThenV = Then->codegen();
    341       if (!ThenV)
    342         return nullptr;
    343 
    344       Builder.CreateBr(MergeBB);
    345       // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
    346       ThenBB = Builder.GetInsertBlock();
    347 
    348 After the conditional branch is inserted, we move the builder to start
    349 inserting into the "then" block. Strictly speaking, this call moves the
    350 insertion point to be at the end of the specified block. However, since
    351 the "then" block is empty, it also starts out by inserting at the
    352 beginning of the block. :)
    353 
    354 Once the insertion point is set, we recursively codegen the "then"
    355 expression from the AST. To finish off the "then" block, we create an
    356 unconditional branch to the merge block. One interesting (and very
    357 important) aspect of the LLVM IR is that it `requires all basic blocks
    358 to be "terminated" <../LangRef.html#functionstructure>`_ with a `control
    359 flow instruction <../LangRef.html#terminators>`_ such as return or
    360 branch. This means that all control flow, *including fall throughs* must
    361 be made explicit in the LLVM IR. If you violate this rule, the verifier
    362 will emit an error.
    363 
    364 The final line here is quite subtle, but is very important. The basic
    365 issue is that when we create the Phi node in the merge block, we need to
    366 set up the block/value pairs that indicate how the Phi will work.
    367 Importantly, the Phi node expects to have an entry for each predecessor
    368 of the block in the CFG. Why then, are we getting the current block when
    369 we just set it to ThenBB 5 lines above? The problem is that the "Then"
    370 expression may actually itself change the block that the Builder is
    371 emitting into if, for example, it contains a nested "if/then/else"
    372 expression. Because calling ``codegen()`` recursively could arbitrarily change
    373 the notion of the current block, we are required to get an up-to-date
    374 value for code that will set up the Phi node.
    375 
    376 .. code-block:: c++
    377 
    378       // Emit else block.
    379       TheFunction->getBasicBlockList().push_back(ElseBB);
    380       Builder.SetInsertPoint(ElseBB);
    381 
    382       Value *ElseV = Else->codegen();
    383       if (!ElseV)
    384         return nullptr;
    385 
    386       Builder.CreateBr(MergeBB);
    387       // codegen of 'Else' can change the current block, update ElseBB for the PHI.
    388       ElseBB = Builder.GetInsertBlock();
    389 
    390 Code generation for the 'else' block is basically identical to codegen
    391 for the 'then' block. The only significant difference is the first line,
    392 which adds the 'else' block to the function. Recall previously that the
    393 'else' block was created, but not added to the function. Now that the
    394 'then' and 'else' blocks are emitted, we can finish up with the merge
    395 code:
    396 
    397 .. code-block:: c++
    398 
    399       // Emit merge block.
    400       TheFunction->getBasicBlockList().push_back(MergeBB);
    401       Builder.SetInsertPoint(MergeBB);
    402       PHINode *PN =
    403         Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
    404 
    405       PN->addIncoming(ThenV, ThenBB);
    406       PN->addIncoming(ElseV, ElseBB);
    407       return PN;
    408     }
    409 
    410 The first two lines here are now familiar: the first adds the "merge"
    411 block to the Function object (it was previously floating, like the else
    412 block above). The second changes the insertion point so that newly
    413 created code will go into the "merge" block. Once that is done, we need
    414 to create the PHI node and set up the block/value pairs for the PHI.
    415 
    416 Finally, the CodeGen function returns the phi node as the value computed
    417 by the if/then/else expression. In our example above, this returned
    418 value will feed into the code for the top-level function, which will
    419 create the return instruction.
    420 
    421 Overall, we now have the ability to execute conditional code in
    422 Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
    423 language that can calculate a wide variety of numeric functions. Next up
    424 we'll add another useful expression that is familiar from non-functional
    425 languages...
    426 
    427 'for' Loop Expression
    428 =====================
    429 
    430 Now that we know how to add basic control flow constructs to the
    431 language, we have the tools to add more powerful things. Lets add
    432 something more aggressive, a 'for' expression:
    433 
    434 ::
    435 
    436      extern putchard(char)
    437      def printstar(n)
    438        for i = 1, i < n, 1.0 in
    439          putchard(42);  # ascii 42 = '*'
    440 
    441      # print 100 '*' characters
    442      printstar(100);
    443 
    444 This expression defines a new variable ("i" in this case) which iterates
    445 from a starting value, while the condition ("i < n" in this case) is
    446 true, incrementing by an optional step value ("1.0" in this case). If
    447 the step value is omitted, it defaults to 1.0. While the loop is true,
    448 it executes its body expression. Because we don't have anything better
    449 to return, we'll just define the loop as always returning 0.0. In the
    450 future when we have mutable variables, it will get more useful.
    451 
    452 As before, lets talk about the changes that we need to Kaleidoscope to
    453 support this.
    454 
    455 Lexer Extensions for the 'for' Loop
    456 -----------------------------------
    457 
    458 The lexer extensions are the same sort of thing as for if/then/else:
    459 
    460 .. code-block:: c++
    461 
    462       ... in enum Token ...
    463       // control
    464       tok_if = -6, tok_then = -7, tok_else = -8,
    465       tok_for = -9, tok_in = -10
    466 
    467       ... in gettok ...
    468       if (IdentifierStr == "def")
    469         return tok_def;
    470       if (IdentifierStr == "extern")
    471         return tok_extern;
    472       if (IdentifierStr == "if")
    473         return tok_if;
    474       if (IdentifierStr == "then")
    475         return tok_then;
    476       if (IdentifierStr == "else")
    477         return tok_else;
    478       if (IdentifierStr == "for")
    479         return tok_for;
    480       if (IdentifierStr == "in")
    481         return tok_in;
    482       return tok_identifier;
    483 
    484 AST Extensions for the 'for' Loop
    485 ---------------------------------
    486 
    487 The AST node is just as simple. It basically boils down to capturing the
    488 variable name and the constituent expressions in the node.
    489 
    490 .. code-block:: c++
    491 
    492     /// ForExprAST - Expression class for for/in.
    493     class ForExprAST : public ExprAST {
    494       std::string VarName;
    495       std::unique_ptr<ExprAST> Start, End, Step, Body;
    496 
    497     public:
    498       ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
    499                  std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
    500                  std::unique_ptr<ExprAST> Body)
    501         : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
    502           Step(std::move(Step)), Body(std::move(Body)) {}
    503       virtual Value *codegen();
    504     };
    505 
    506 Parser Extensions for the 'for' Loop
    507 ------------------------------------
    508 
    509 The parser code is also fairly standard. The only interesting thing here
    510 is handling of the optional step value. The parser code handles it by
    511 checking to see if the second comma is present. If not, it sets the step
    512 value to null in the AST node:
    513 
    514 .. code-block:: c++
    515 
    516     /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
    517     static std::unique_ptr<ExprAST> ParseForExpr() {
    518       getNextToken();  // eat the for.
    519 
    520       if (CurTok != tok_identifier)
    521         return Error("expected identifier after for");
    522 
    523       std::string IdName = IdentifierStr;
    524       getNextToken();  // eat identifier.
    525 
    526       if (CurTok != '=')
    527         return Error("expected '=' after for");
    528       getNextToken();  // eat '='.
    529 
    530 
    531       auto Start = ParseExpression();
    532       if (!Start)
    533         return nullptr;
    534       if (CurTok != ',')
    535         return Error("expected ',' after for start value");
    536       getNextToken();
    537 
    538       auto End = ParseExpression();
    539       if (!End)
    540         return nullptr;
    541 
    542       // The step value is optional.
    543       std::unique_ptr<ExprAST> Step;
    544       if (CurTok == ',') {
    545         getNextToken();
    546         Step = ParseExpression();
    547         if (!Step)
    548           return nullptr;
    549       }
    550 
    551       if (CurTok != tok_in)
    552         return Error("expected 'in' after for");
    553       getNextToken();  // eat 'in'.
    554 
    555       auto Body = ParseExpression();
    556       if (!Body)
    557         return nullptr;
    558 
    559       return llvm::make_unique<ForExprAST>(IdName, std::move(Start),
    560                                            std::move(End), std::move(Step),
    561                                            std::move(Body));
    562     }
    563 
    564 LLVM IR for the 'for' Loop
    565 --------------------------
    566 
    567 Now we get to the good part: the LLVM IR we want to generate for this
    568 thing. With the simple example above, we get this LLVM IR (note that
    569 this dump is generated with optimizations disabled for clarity):
    570 
    571 .. code-block:: llvm
    572 
    573     declare double @putchard(double)
    574 
    575     define double @printstar(double %n) {
    576     entry:
    577       ; initial value = 1.0 (inlined into phi)
    578       br label %loop
    579 
    580     loop:       ; preds = %loop, %entry
    581       %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
    582       ; body
    583       %calltmp = call double @putchard(double 4.200000e+01)
    584       ; increment
    585       %nextvar = fadd double %i, 1.000000e+00
    586 
    587       ; termination test
    588       %cmptmp = fcmp ult double %i, %n
    589       %booltmp = uitofp i1 %cmptmp to double
    590       %loopcond = fcmp one double %booltmp, 0.000000e+00
    591       br i1 %loopcond, label %loop, label %afterloop
    592 
    593     afterloop:      ; preds = %loop
    594       ; loop always returns 0.0
    595       ret double 0.000000e+00
    596     }
    597 
    598 This loop contains all the same constructs we saw before: a phi node,
    599 several expressions, and some basic blocks. Lets see how this fits
    600 together.
    601 
    602 Code Generation for the 'for' Loop
    603 ----------------------------------
    604 
    605 The first part of codegen is very simple: we just output the start
    606 expression for the loop value:
    607 
    608 .. code-block:: c++
    609 
    610     Value *ForExprAST::codegen() {
    611       // Emit the start code first, without 'variable' in scope.
    612       Value *StartVal = Start->codegen();
    613       if (StartVal == 0) return 0;
    614 
    615 With this out of the way, the next step is to set up the LLVM basic
    616 block for the start of the loop body. In the case above, the whole loop
    617 body is one block, but remember that the body code itself could consist
    618 of multiple blocks (e.g. if it contains an if/then/else or a for/in
    619 expression).
    620 
    621 .. code-block:: c++
    622 
    623       // Make the new basic block for the loop header, inserting after current
    624       // block.
    625       Function *TheFunction = Builder.GetInsertBlock()->getParent();
    626       BasicBlock *PreheaderBB = Builder.GetInsertBlock();
    627       BasicBlock *LoopBB =
    628           BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
    629 
    630       // Insert an explicit fall through from the current block to the LoopBB.
    631       Builder.CreateBr(LoopBB);
    632 
    633 This code is similar to what we saw for if/then/else. Because we will
    634 need it to create the Phi node, we remember the block that falls through
    635 into the loop. Once we have that, we create the actual block that starts
    636 the loop and create an unconditional branch for the fall-through between
    637 the two blocks.
    638 
    639 .. code-block:: c++
    640 
    641       // Start insertion in LoopBB.
    642       Builder.SetInsertPoint(LoopBB);
    643 
    644       // Start the PHI node with an entry for Start.
    645       PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
    646                                             2, VarName.c_str());
    647       Variable->addIncoming(StartVal, PreheaderBB);
    648 
    649 Now that the "preheader" for the loop is set up, we switch to emitting
    650 code for the loop body. To begin with, we move the insertion point and
    651 create the PHI node for the loop induction variable. Since we already
    652 know the incoming value for the starting value, we add it to the Phi
    653 node. Note that the Phi will eventually get a second value for the
    654 backedge, but we can't set it up yet (because it doesn't exist!).
    655 
    656 .. code-block:: c++
    657 
    658       // Within the loop, the variable is defined equal to the PHI node.  If it
    659       // shadows an existing variable, we have to restore it, so save it now.
    660       Value *OldVal = NamedValues[VarName];
    661       NamedValues[VarName] = Variable;
    662 
    663       // Emit the body of the loop.  This, like any other expr, can change the
    664       // current BB.  Note that we ignore the value computed by the body, but don't
    665       // allow an error.
    666       if (!Body->codegen())
    667         return nullptr;
    668 
    669 Now the code starts to get more interesting. Our 'for' loop introduces a
    670 new variable to the symbol table. This means that our symbol table can
    671 now contain either function arguments or loop variables. To handle this,
    672 before we codegen the body of the loop, we add the loop variable as the
    673 current value for its name. Note that it is possible that there is a
    674 variable of the same name in the outer scope. It would be easy to make
    675 this an error (emit an error and return null if there is already an
    676 entry for VarName) but we choose to allow shadowing of variables. In
    677 order to handle this correctly, we remember the Value that we are
    678 potentially shadowing in ``OldVal`` (which will be null if there is no
    679 shadowed variable).
    680 
    681 Once the loop variable is set into the symbol table, the code
    682 recursively codegen's the body. This allows the body to use the loop
    683 variable: any references to it will naturally find it in the symbol
    684 table.
    685 
    686 .. code-block:: c++
    687 
    688       // Emit the step value.
    689       Value *StepVal = nullptr;
    690       if (Step) {
    691         StepVal = Step->codegen();
    692         if (!StepVal)
    693           return nullptr;
    694       } else {
    695         // If not specified, use 1.0.
    696         StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
    697       }
    698 
    699       Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
    700 
    701 Now that the body is emitted, we compute the next value of the iteration
    702 variable by adding the step value, or 1.0 if it isn't present.
    703 '``NextVar``' will be the value of the loop variable on the next
    704 iteration of the loop.
    705 
    706 .. code-block:: c++
    707 
    708       // Compute the end condition.
    709       Value *EndCond = End->codegen();
    710       if (!EndCond)
    711         return nullptr;
    712 
    713       // Convert condition to a bool by comparing equal to 0.0.
    714       EndCond = Builder.CreateFCmpONE(
    715           EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
    716 
    717 Finally, we evaluate the exit value of the loop, to determine whether
    718 the loop should exit. This mirrors the condition evaluation for the
    719 if/then/else statement.
    720 
    721 .. code-block:: c++
    722 
    723       // Create the "after loop" block and insert it.
    724       BasicBlock *LoopEndBB = Builder.GetInsertBlock();
    725       BasicBlock *AfterBB =
    726           BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
    727 
    728       // Insert the conditional branch into the end of LoopEndBB.
    729       Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
    730 
    731       // Any new code will be inserted in AfterBB.
    732       Builder.SetInsertPoint(AfterBB);
    733 
    734 With the code for the body of the loop complete, we just need to finish
    735 up the control flow for it. This code remembers the end block (for the
    736 phi node), then creates the block for the loop exit ("afterloop"). Based
    737 on the value of the exit condition, it creates a conditional branch that
    738 chooses between executing the loop again and exiting the loop. Any
    739 future code is emitted in the "afterloop" block, so it sets the
    740 insertion position to it.
    741 
    742 .. code-block:: c++
    743 
    744       // Add a new entry to the PHI node for the backedge.
    745       Variable->addIncoming(NextVar, LoopEndBB);
    746 
    747       // Restore the unshadowed variable.
    748       if (OldVal)
    749         NamedValues[VarName] = OldVal;
    750       else
    751         NamedValues.erase(VarName);
    752 
    753       // for expr always returns 0.0.
    754       return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
    755     }
    756 
    757 The final code handles various cleanups: now that we have the "NextVar"
    758 value, we can add the incoming value to the loop PHI node. After that,
    759 we remove the loop variable from the symbol table, so that it isn't in
    760 scope after the for loop. Finally, code generation of the for loop
    761 always returns 0.0, so that is what we return from
    762 ``ForExprAST::codegen()``.
    763 
    764 With this, we conclude the "adding control flow to Kaleidoscope" chapter
    765 of the tutorial. In this chapter we added two control flow constructs,
    766 and used them to motivate a couple of aspects of the LLVM IR that are
    767 important for front-end implementors to know. In the next chapter of our
    768 saga, we will get a bit crazier and add `user-defined
    769 operators <LangImpl6.html>`_ to our poor innocent language.
    770 
    771 Full Code Listing
    772 =================
    773 
    774 Here is the complete code listing for our running example, enhanced with
    775 the if/then/else and for expressions.. To build this example, use:
    776 
    777 .. code-block:: bash
    778 
    779     # Compile
    780     clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core mcjit native` -O3 -o toy
    781     # Run
    782     ./toy
    783 
    784 Here is the code:
    785 
    786 .. literalinclude:: ../../examples/Kaleidoscope/Chapter5/toy.cpp
    787    :language: c++
    788 
    789 `Next: Extending the language: user-defined operators <LangImpl6.html>`_
    790 
    791