1 ==================================================
2 Kaleidoscope: Extending the Language: Control Flow
3 ==================================================
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.
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.
30 Before we get going on "how" we add this extension, let's talk about
31 "what" we want. The basic idea is that we want to be able to write this
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
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
57 Now that we know what we "want", let's break this down into its
60 Lexer Extensions for If/Then/Else
61 ---------------------------------
63 The lexer extensions are straightforward. First we add new enum values
64 for the relevant tokens:
73 Once we have that, we recognize the new keywords in the lexer. This is
79 if (IdentifierStr == "def")
81 if (IdentifierStr == "extern")
83 if (IdentifierStr == "if")
85 if (IdentifierStr == "then")
87 if (IdentifierStr == "else")
89 return tok_identifier;
91 AST Extensions for If/Then/Else
92 -------------------------------
94 To represent the new expression we add a new AST node for it:
98 /// IfExprAST - Expression class for if/then/else.
99 class IfExprAST : public ExprAST {
100 std::unique_ptr<ExprAST> Cond, Then, Else;
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)) {}
107 Value *codegen() override;
110 The AST node just has pointers to the various subexpressions.
112 Parser Extensions for If/Then/Else
113 ----------------------------------
115 Now that we have the relevant tokens coming from the lexer and we have
116 the AST node to build, our parsing logic is relatively straightforward.
117 First we define a new parsing function:
121 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
122 static std::unique_ptr<ExprAST> ParseIfExpr() {
123 getNextToken(); // eat the if.
126 auto Cond = ParseExpression();
130 if (CurTok != tok_then)
131 return LogError("expected then");
132 getNextToken(); // eat the then
134 auto Then = ParseExpression();
138 if (CurTok != tok_else)
139 return LogError("expected else");
143 auto Else = ParseExpression();
147 return std::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
151 Next we hook it up as a primary expression:
155 static std::unique_ptr<ExprAST> ParsePrimary() {
158 return LogError("unknown token when expecting an expression");
160 return ParseIdentifierExpr();
162 return ParseNumberExpr();
164 return ParseParenExpr();
166 return ParseIfExpr();
170 LLVM IR for If/Then/Else
171 ------------------------
173 Now that we have it parsing and building the AST, the final piece is
174 adding LLVM code generation support. This is the most interesting part
175 of the if/then/else example, because this is where it starts to
176 introduce new concepts. All of the code above has been thoroughly
177 described in previous chapters.
179 To motivate the code we want to produce, let's take a look at a simple
186 def baz(x) if x then foo() else bar();
188 If you disable optimizations, the code you'll (soon) get from
189 Kaleidoscope looks like this:
193 declare double @foo()
195 declare double @bar()
197 define double @baz(double %x) {
199 %ifcond = fcmp one double %x, 0.000000e+00
200 br i1 %ifcond, label %then, label %else
202 then: ; preds = %entry
203 %calltmp = call double @foo()
206 else: ; preds = %entry
207 %calltmp1 = call double @bar()
210 ifcont: ; preds = %else, %then
211 %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
215 To visualize the control flow graph, you can use a nifty feature of the
216 LLVM '`opt <https://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
217 IR into "t.ll" and run "``llvm-as < t.ll | opt -passes=view-cfg``", `a
218 window will pop up <../../ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ and you'll
221 .. figure:: LangImpl05-cfg.png
227 Another way to get this is to call "``F->viewCFG()``" or
228 "``F->viewCFGOnly()``" (where F is a "``Function*``") either by
229 inserting actual calls into the code and recompiling or by calling these
230 in the debugger. LLVM has many nice features for visualizing various
233 Getting back to the generated code, it is fairly simple: the entry block
234 evaluates the conditional expression ("x" in our case here) and compares
235 the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
236 and Not Equal"). Based on the result of this expression, the code jumps
237 to either the "then" or "else" blocks, which contain the expressions for
238 the true/false cases.
240 Once the then/else blocks are finished executing, they both branch back
241 to the 'ifcont' block to execute the code that happens after the
242 if/then/else. In this case the only thing left to do is to return to the
243 caller of the function. The question then becomes: how does the code
244 know which expression to return?
246 The answer to this question involves an important SSA operation: the
248 operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
249 If you're not familiar with SSA, `the wikipedia
250 article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
251 is a good introduction and there are various other introductions to it
252 available on your favorite search engine. The short version is that
253 "execution" of the Phi operation requires "remembering" which block
254 control came from. The Phi operation takes on the value corresponding to
255 the input control block. In this case, if control comes in from the
256 "then" block, it gets the value of "calltmp". If control comes from the
257 "else" block, it gets the value of "calltmp1".
259 At this point, you are probably starting to think "Oh no! This means my
260 simple and elegant front-end will have to start generating SSA form in
261 order to use LLVM!". Fortunately, this is not the case, and we strongly
262 advise *not* implementing an SSA construction algorithm in your
263 front-end unless there is an amazingly good reason to do so. In
264 practice, there are two sorts of values that float around in code
265 written for your average imperative programming language that might need
268 #. Code that involves user variables: ``x = 1; x = x + 1;``
269 #. Values that are implicit in the structure of your AST, such as the
270 Phi node in this case.
272 In `Chapter 7 <LangImpl07.html>`_ of this tutorial ("mutable variables"),
273 we'll talk about #1 in depth. For now, just believe me that you don't
274 need SSA construction to handle this case. For #2, you have the choice
275 of using the techniques that we will describe for #1, or you can insert
276 Phi nodes directly, if convenient. In this case, it is really
277 easy to generate the Phi node, so we choose to do it directly.
279 Okay, enough of the motivation and overview, let's generate code!
281 Code Generation for If/Then/Else
282 --------------------------------
284 In order to generate code for this, we implement the ``codegen`` method
289 Value *IfExprAST::codegen() {
290 Value *CondV = Cond->codegen();
294 // Convert condition to a bool by comparing non-equal to 0.0.
295 CondV = Builder->CreateFCmpONE(
296 CondV, ConstantFP::get(*TheContext, APFloat(0.0)), "ifcond");
298 This code is straightforward and similar to what we saw before. We emit
299 the expression for the condition, then compare that value to zero to get
300 a truth value as a 1-bit (bool) value.
304 Function *TheFunction = Builder->GetInsertBlock()->getParent();
306 // Create blocks for the then and else cases. Insert the 'then' block at the
307 // end of the function.
309 BasicBlock::Create(*TheContext, "then", TheFunction);
310 BasicBlock *ElseBB = BasicBlock::Create(*TheContext, "else");
311 BasicBlock *MergeBB = BasicBlock::Create(*TheContext, "ifcont");
313 Builder->CreateCondBr(CondV, ThenBB, ElseBB);
315 This code creates the basic blocks that are related to the if/then/else
316 statement, and correspond directly to the blocks in the example above.
317 The first line gets the current Function object that is being built. It
318 gets this by asking the builder for the current BasicBlock, and asking
319 that block for its "parent" (the function it is currently embedded
322 Once it has that, it creates three blocks. Note that it passes
323 "TheFunction" into the constructor for the "then" block. This causes the
324 constructor to automatically insert the new block into the end of the
325 specified function. The other two blocks are created, but aren't yet
326 inserted into the function.
328 Once the blocks are created, we can emit the conditional branch that
329 chooses between them. Note that creating new blocks does not implicitly
330 affect the IRBuilder, so it is still inserting into the block that the
331 condition went into. Also note that it is creating a branch to the
332 "then" block and the "else" block, even though the "else" block isn't
333 inserted into the function yet. This is all ok: it is the standard way
334 that LLVM supports forward references.
339 Builder->SetInsertPoint(ThenBB);
341 Value *ThenV = Then->codegen();
345 Builder->CreateBr(MergeBB);
346 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
347 ThenBB = Builder->GetInsertBlock();
349 After the conditional branch is inserted, we move the builder to start
350 inserting into the "then" block. Strictly speaking, this call moves the
351 insertion point to be at the end of the specified block. However, since
352 the "then" block is empty, it also starts out by inserting at the
353 beginning of the block. :)
355 Once the insertion point is set, we recursively codegen the "then"
356 expression from the AST. To finish off the "then" block, we create an
357 unconditional branch to the merge block. One interesting (and very
358 important) aspect of the LLVM IR is that it :ref:`requires all basic
359 blocks to be "terminated" <functionstructure>` with a :ref:`control
360 flow instruction <terminators>` such as return or branch. This means
361 that all control flow, *including fall throughs* must be made explicit
362 in the LLVM IR. If you violate this rule, the verifier will emit an
365 The final line here is quite subtle, but is very important. The basic
366 issue is that when we create the Phi node in the merge block, we need to
367 set up the block/value pairs that indicate how the Phi will work.
368 Importantly, the Phi node expects to have an entry for each predecessor
369 of the block in the CFG. Why then, are we getting the current block when
370 we just set it to ThenBB 5 lines above? The problem is that the "Then"
371 expression may actually itself change the block that the Builder is
372 emitting into if, for example, it contains a nested "if/then/else"
373 expression. Because calling ``codegen()`` recursively could arbitrarily change
374 the notion of the current block, we are required to get an up-to-date
375 value for code that will set up the Phi node.
380 TheFunction->insert(TheFunction->end(), ElseBB);
381 Builder->SetInsertPoint(ElseBB);
383 Value *ElseV = Else->codegen();
387 Builder->CreateBr(MergeBB);
388 // codegen of 'Else' can change the current block, update ElseBB for the PHI.
389 ElseBB = Builder->GetInsertBlock();
391 Code generation for the 'else' block is basically identical to codegen
392 for the 'then' block. The only significant difference is the first line,
393 which adds the 'else' block to the function. Recall previously that the
394 'else' block was created, but not added to the function. Now that the
395 'then' and 'else' blocks are emitted, we can finish up with the merge
401 TheFunction->insert(TheFunction->end(), MergeBB);
402 Builder->SetInsertPoint(MergeBB);
404 Builder->CreatePHI(Type::getDoubleTy(*TheContext), 2, "iftmp");
406 PN->addIncoming(ThenV, ThenBB);
407 PN->addIncoming(ElseV, ElseBB);
411 The first two lines here are now familiar: the first adds the "merge"
412 block to the Function object (it was previously floating, like the else
413 block above). The second changes the insertion point so that newly
414 created code will go into the "merge" block. Once that is done, we need
415 to create the PHI node and set up the block/value pairs for the PHI.
417 Finally, the CodeGen function returns the phi node as the value computed
418 by the if/then/else expression. In our example above, this returned
419 value will feed into the code for the top-level function, which will
420 create the return instruction.
422 Overall, we now have the ability to execute conditional code in
423 Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
424 language that can calculate a wide variety of numeric functions. Next up
425 we'll add another useful expression that is familiar from non-functional
428 'for' Loop Expression
429 =====================
431 Now that we know how to add basic control flow constructs to the
432 language, we have the tools to add more powerful things. Let's add
433 something more aggressive, a 'for' expression:
437 extern putchard(char);
439 for i = 1, i < n, 1.0 in
440 putchard(42); # ascii 42 = '*'
442 # print 100 '*' characters
445 This expression defines a new variable ("i" in this case) which iterates
446 from a starting value, while the condition ("i < n" in this case) is
447 true, incrementing by an optional step value ("1.0" in this case). If
448 the step value is omitted, it defaults to 1.0. While the loop is true,
449 it executes its body expression. Because we don't have anything better
450 to return, we'll just define the loop as always returning 0.0. In the
451 future when we have mutable variables, it will get more useful.
453 As before, let's talk about the changes that we need to Kaleidoscope to
456 Lexer Extensions for the 'for' Loop
457 -----------------------------------
459 The lexer extensions are the same sort of thing as for if/then/else:
463 ... in enum Token ...
465 tok_if = -6, tok_then = -7, tok_else = -8,
466 tok_for = -9, tok_in = -10
469 if (IdentifierStr == "def")
471 if (IdentifierStr == "extern")
473 if (IdentifierStr == "if")
475 if (IdentifierStr == "then")
477 if (IdentifierStr == "else")
479 if (IdentifierStr == "for")
481 if (IdentifierStr == "in")
483 return tok_identifier;
485 AST Extensions for the 'for' Loop
486 ---------------------------------
488 The AST node is just as simple. It basically boils down to capturing the
489 variable name and the constituent expressions in the node.
493 /// ForExprAST - Expression class for for/in.
494 class ForExprAST : public ExprAST {
496 std::unique_ptr<ExprAST> Start, End, Step, Body;
499 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
500 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
501 std::unique_ptr<ExprAST> Body)
502 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
503 Step(std::move(Step)), Body(std::move(Body)) {}
505 Value *codegen() override;
508 Parser Extensions for the 'for' Loop
509 ------------------------------------
511 The parser code is also fairly standard. The only interesting thing here
512 is handling of the optional step value. The parser code handles it by
513 checking to see if the second comma is present. If not, it sets the step
514 value to null in the AST node:
518 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
519 static std::unique_ptr<ExprAST> ParseForExpr() {
520 getNextToken(); // eat the for.
522 if (CurTok != tok_identifier)
523 return LogError("expected identifier after for");
525 std::string IdName = IdentifierStr;
526 getNextToken(); // eat identifier.
529 return LogError("expected '=' after for");
530 getNextToken(); // eat '='.
533 auto Start = ParseExpression();
537 return LogError("expected ',' after for start value");
540 auto End = ParseExpression();
544 // The step value is optional.
545 std::unique_ptr<ExprAST> Step;
548 Step = ParseExpression();
553 if (CurTok != tok_in)
554 return LogError("expected 'in' after for");
555 getNextToken(); // eat 'in'.
557 auto Body = ParseExpression();
561 return std::make_unique<ForExprAST>(IdName, std::move(Start),
562 std::move(End), std::move(Step),
566 And again we hook it up as a primary expression:
570 static std::unique_ptr<ExprAST> ParsePrimary() {
573 return LogError("unknown token when expecting an expression");
575 return ParseIdentifierExpr();
577 return ParseNumberExpr();
579 return ParseParenExpr();
581 return ParseIfExpr();
583 return ParseForExpr();
587 LLVM IR for the 'for' Loop
588 --------------------------
590 Now we get to the good part: the LLVM IR we want to generate for this
591 thing. With the simple example above, we get this LLVM IR (note that
592 this dump is generated with optimizations disabled for clarity):
596 declare double @putchard(double)
598 define double @printstar(double %n) {
600 ; initial value = 1.0 (inlined into phi)
603 loop: ; preds = %loop, %entry
604 %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
606 %calltmp = call double @putchard(double 4.200000e+01)
608 %nextvar = fadd double %i, 1.000000e+00
611 %cmptmp = fcmp ult double %i, %n
612 %booltmp = uitofp i1 %cmptmp to double
613 %loopcond = fcmp one double %booltmp, 0.000000e+00
614 br i1 %loopcond, label %loop, label %afterloop
616 afterloop: ; preds = %loop
617 ; loop always returns 0.0
618 ret double 0.000000e+00
621 This loop contains all the same constructs we saw before: a phi node,
622 several expressions, and some basic blocks. Let's see how this fits
625 Code Generation for the 'for' Loop
626 ----------------------------------
628 The first part of codegen is very simple: we just output the start
629 expression for the loop value:
633 Value *ForExprAST::codegen() {
634 // Emit the start code first, without 'variable' in scope.
635 Value *StartVal = Start->codegen();
639 With this out of the way, the next step is to set up the LLVM basic
640 block for the start of the loop body. In the case above, the whole loop
641 body is one block, but remember that the body code itself could consist
642 of multiple blocks (e.g. if it contains an if/then/else or a for/in
647 // Make the new basic block for the loop header, inserting after current
649 Function *TheFunction = Builder->GetInsertBlock()->getParent();
650 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
652 BasicBlock::Create(*TheContext, "loop", TheFunction);
654 // Insert an explicit fall through from the current block to the LoopBB.
655 Builder->CreateBr(LoopBB);
657 This code is similar to what we saw for if/then/else. Because we will
658 need it to create the Phi node, we remember the block that falls through
659 into the loop. Once we have that, we create the actual block that starts
660 the loop and create an unconditional branch for the fall-through between
665 // Start insertion in LoopBB.
666 Builder->SetInsertPoint(LoopBB);
668 // Start the PHI node with an entry for Start.
669 PHINode *Variable = Builder->CreatePHI(Type::getDoubleTy(*TheContext),
671 Variable->addIncoming(StartVal, PreheaderBB);
673 Now that the "preheader" for the loop is set up, we switch to emitting
674 code for the loop body. To begin with, we move the insertion point and
675 create the PHI node for the loop induction variable. Since we already
676 know the incoming value for the starting value, we add it to the Phi
677 node. Note that the Phi will eventually get a second value for the
678 backedge, but we can't set it up yet (because it doesn't exist!).
682 // Within the loop, the variable is defined equal to the PHI node. If it
683 // shadows an existing variable, we have to restore it, so save it now.
684 Value *OldVal = NamedValues[VarName];
685 NamedValues[VarName] = Variable;
687 // Emit the body of the loop. This, like any other expr, can change the
688 // current BB. Note that we ignore the value computed by the body, but don't
690 if (!Body->codegen())
693 Now the code starts to get more interesting. Our 'for' loop introduces a
694 new variable to the symbol table. This means that our symbol table can
695 now contain either function arguments or loop variables. To handle this,
696 before we codegen the body of the loop, we add the loop variable as the
697 current value for its name. Note that it is possible that there is a
698 variable of the same name in the outer scope. It would be easy to make
699 this an error (emit an error and return null if there is already an
700 entry for VarName) but we choose to allow shadowing of variables. In
701 order to handle this correctly, we remember the Value that we are
702 potentially shadowing in ``OldVal`` (which will be null if there is no
705 Once the loop variable is set into the symbol table, the code
706 recursively codegen's the body. This allows the body to use the loop
707 variable: any references to it will naturally find it in the symbol
712 // Emit the step value.
713 Value *StepVal = nullptr;
715 StepVal = Step->codegen();
719 // If not specified, use 1.0.
720 StepVal = ConstantFP::get(*TheContext, APFloat(1.0));
723 Value *NextVar = Builder->CreateFAdd(Variable, StepVal, "nextvar");
725 Now that the body is emitted, we compute the next value of the iteration
726 variable by adding the step value, or 1.0 if it isn't present.
727 '``NextVar``' will be the value of the loop variable on the next
728 iteration of the loop.
732 // Compute the end condition.
733 Value *EndCond = End->codegen();
737 // Convert condition to a bool by comparing non-equal to 0.0.
738 EndCond = Builder->CreateFCmpONE(
739 EndCond, ConstantFP::get(*TheContext, APFloat(0.0)), "loopcond");
741 Finally, we evaluate the exit value of the loop, to determine whether
742 the loop should exit. This mirrors the condition evaluation for the
743 if/then/else statement.
747 // Create the "after loop" block and insert it.
748 BasicBlock *LoopEndBB = Builder->GetInsertBlock();
749 BasicBlock *AfterBB =
750 BasicBlock::Create(*TheContext, "afterloop", TheFunction);
752 // Insert the conditional branch into the end of LoopEndBB.
753 Builder->CreateCondBr(EndCond, LoopBB, AfterBB);
755 // Any new code will be inserted in AfterBB.
756 Builder->SetInsertPoint(AfterBB);
758 With the code for the body of the loop complete, we just need to finish
759 up the control flow for it. This code remembers the end block (for the
760 phi node), then creates the block for the loop exit ("afterloop"). Based
761 on the value of the exit condition, it creates a conditional branch that
762 chooses between executing the loop again and exiting the loop. Any
763 future code is emitted in the "afterloop" block, so it sets the
764 insertion position to it.
768 // Add a new entry to the PHI node for the backedge.
769 Variable->addIncoming(NextVar, LoopEndBB);
771 // Restore the unshadowed variable.
773 NamedValues[VarName] = OldVal;
775 NamedValues.erase(VarName);
777 // for expr always returns 0.0.
778 return Constant::getNullValue(Type::getDoubleTy(*TheContext));
781 The final code handles various cleanups: now that we have the "NextVar"
782 value, we can add the incoming value to the loop PHI node. After that,
783 we remove the loop variable from the symbol table, so that it isn't in
784 scope after the for loop. Finally, code generation of the for loop
785 always returns 0.0, so that is what we return from
786 ``ForExprAST::codegen()``.
788 With this, we conclude the "adding control flow to Kaleidoscope" chapter
789 of the tutorial. In this chapter we added two control flow constructs,
790 and used them to motivate a couple of aspects of the LLVM IR that are
791 important for front-end implementors to know. In the next chapter of our
792 saga, we will get a bit crazier and add `user-defined
793 operators <LangImpl06.html>`_ to our poor innocent language.
798 Here is the complete code listing for our running example, enhanced with
799 the if/then/else and for expressions. To build this example, use:
804 clang++ -g toy.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o toy
810 .. literalinclude:: ../../../examples/Kaleidoscope/Chapter5/toy.cpp
813 `Next: Extending the language: user-defined operators <LangImpl06.html>`_