[docs] Remove explicit authorship.
[oota-llvm.git] / docs / tutorial / LangImpl5.rst
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, tok_then = -7, tok_else = -8,
70
71 Once we have that, we recognize the new keywords in the lexer. This is
72 pretty simple stuff:
73
74 .. code-block:: c++
75
76         ...
77         if (IdentifierStr == "def") return tok_def;
78         if (IdentifierStr == "extern") return tok_extern;
79         if (IdentifierStr == "if") return tok_if;
80         if (IdentifierStr == "then") return tok_then;
81         if (IdentifierStr == "else") return tok_else;
82         return tok_identifier;
83
84 AST Extensions for If/Then/Else
85 -------------------------------
86
87 To represent the new expression we add a new AST node for it:
88
89 .. code-block:: c++
90
91     /// IfExprAST - Expression class for if/then/else.
92     class IfExprAST : public ExprAST {
93       ExprAST *Cond, *Then, *Else;
94     public:
95       IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
96         : Cond(cond), Then(then), Else(_else) {}
97       virtual Value *Codegen();
98     };
99
100 The AST node just has pointers to the various subexpressions.
101
102 Parser Extensions for If/Then/Else
103 ----------------------------------
104
105 Now that we have the relevant tokens coming from the lexer and we have
106 the AST node to build, our parsing logic is relatively straightforward.
107 First we define a new parsing function:
108
109 .. code-block:: c++
110
111     /// ifexpr ::= 'if' expression 'then' expression 'else' expression
112     static ExprAST *ParseIfExpr() {
113       getNextToken();  // eat the if.
114
115       // condition.
116       ExprAST *Cond = ParseExpression();
117       if (!Cond) return 0;
118
119       if (CurTok != tok_then)
120         return Error("expected then");
121       getNextToken();  // eat the then
122
123       ExprAST *Then = ParseExpression();
124       if (Then == 0) return 0;
125
126       if (CurTok != tok_else)
127         return Error("expected else");
128
129       getNextToken();
130
131       ExprAST *Else = ParseExpression();
132       if (!Else) return 0;
133
134       return new IfExprAST(Cond, Then, Else);
135     }
136
137 Next we hook it up as a primary expression:
138
139 .. code-block:: c++
140
141     static ExprAST *ParsePrimary() {
142       switch (CurTok) {
143       default: return Error("unknown token when expecting an expression");
144       case tok_identifier: return ParseIdentifierExpr();
145       case tok_number:     return ParseNumberExpr();
146       case '(':            return ParseParenExpr();
147       case tok_if:         return ParseIfExpr();
148       }
149     }
150
151 LLVM IR for If/Then/Else
152 ------------------------
153
154 Now that we have it parsing and building the AST, the final piece is
155 adding LLVM code generation support. This is the most interesting part
156 of the if/then/else example, because this is where it starts to
157 introduce new concepts. All of the code above has been thoroughly
158 described in previous chapters.
159
160 To motivate the code we want to produce, lets take a look at a simple
161 example. Consider:
162
163 ::
164
165     extern foo();
166     extern bar();
167     def baz(x) if x then foo() else bar();
168
169 If you disable optimizations, the code you'll (soon) get from
170 Kaleidoscope looks like this:
171
172 .. code-block:: llvm
173
174     declare double @foo()
175
176     declare double @bar()
177
178     define double @baz(double %x) {
179     entry:
180       %ifcond = fcmp one double %x, 0.000000e+00
181       br i1 %ifcond, label %then, label %else
182
183     then:       ; preds = %entry
184       %calltmp = call double @foo()
185       br label %ifcont
186
187     else:       ; preds = %entry
188       %calltmp1 = call double @bar()
189       br label %ifcont
190
191     ifcont:     ; preds = %else, %then
192       %iftmp = phi double [ %calltmp, %then ], [ %calltmp1, %else ]
193       ret double %iftmp
194     }
195
196 To visualize the control flow graph, you can use a nifty feature of the
197 LLVM '`opt <http://llvm.org/cmds/opt.html>`_' tool. If you put this LLVM
198 IR into "t.ll" and run "``llvm-as < t.ll | opt -analyze -view-cfg``", `a
199 window will pop up <../ProgrammersManual.html#ViewGraph>`_ and you'll
200 see this graph:
201
202 .. figure:: LangImpl5-cfg.png
203    :align: center
204    :alt: Example CFG
205
206    Example CFG
207
208 Another way to get this is to call "``F->viewCFG()``" or
209 "``F->viewCFGOnly()``" (where F is a "``Function*``") either by
210 inserting actual calls into the code and recompiling or by calling these
211 in the debugger. LLVM has many nice features for visualizing various
212 graphs.
213
214 Getting back to the generated code, it is fairly simple: the entry block
215 evaluates the conditional expression ("x" in our case here) and compares
216 the result to 0.0 with the "``fcmp one``" instruction ('one' is "Ordered
217 and Not Equal"). Based on the result of this expression, the code jumps
218 to either the "then" or "else" blocks, which contain the expressions for
219 the true/false cases.
220
221 Once the then/else blocks are finished executing, they both branch back
222 to the 'ifcont' block to execute the code that happens after the
223 if/then/else. In this case the only thing left to do is to return to the
224 caller of the function. The question then becomes: how does the code
225 know which expression to return?
226
227 The answer to this question involves an important SSA operation: the
228 `Phi
229 operation <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_.
230 If you're not familiar with SSA, `the wikipedia
231 article <http://en.wikipedia.org/wiki/Static_single_assignment_form>`_
232 is a good introduction and there are various other introductions to it
233 available on your favorite search engine. The short version is that
234 "execution" of the Phi operation requires "remembering" which block
235 control came from. The Phi operation takes on the value corresponding to
236 the input control block. In this case, if control comes in from the
237 "then" block, it gets the value of "calltmp". If control comes from the
238 "else" block, it gets the value of "calltmp1".
239
240 At this point, you are probably starting to think "Oh no! This means my
241 simple and elegant front-end will have to start generating SSA form in
242 order to use LLVM!". Fortunately, this is not the case, and we strongly
243 advise *not* implementing an SSA construction algorithm in your
244 front-end unless there is an amazingly good reason to do so. In
245 practice, there are two sorts of values that float around in code
246 written for your average imperative programming language that might need
247 Phi nodes:
248
249 #. Code that involves user variables: ``x = 1; x = x + 1;``
250 #. Values that are implicit in the structure of your AST, such as the
251    Phi node in this case.
252
253 In `Chapter 7 <LangImpl7.html>`_ of this tutorial ("mutable variables"),
254 we'll talk about #1 in depth. For now, just believe me that you don't
255 need SSA construction to handle this case. For #2, you have the choice
256 of using the techniques that we will describe for #1, or you can insert
257 Phi nodes directly, if convenient. In this case, it is really really
258 easy to generate the Phi node, so we choose to do it directly.
259
260 Okay, enough of the motivation and overview, lets generate code!
261
262 Code Generation for If/Then/Else
263 --------------------------------
264
265 In order to generate code for this, we implement the ``Codegen`` method
266 for ``IfExprAST``:
267
268 .. code-block:: c++
269
270     Value *IfExprAST::Codegen() {
271       Value *CondV = Cond->Codegen();
272       if (CondV == 0) return 0;
273
274       // Convert condition to a bool by comparing equal to 0.0.
275       CondV = Builder.CreateFCmpONE(CondV,
276                                   ConstantFP::get(getGlobalContext(), APFloat(0.0)),
277                                     "ifcond");
278
279 This code is straightforward and similar to what we saw before. We emit
280 the expression for the condition, then compare that value to zero to get
281 a truth value as a 1-bit (bool) value.
282
283 .. code-block:: c++
284
285       Function *TheFunction = Builder.GetInsertBlock()->getParent();
286
287       // Create blocks for the then and else cases.  Insert the 'then' block at the
288       // end of the function.
289       BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
290       BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
291       BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
292
293       Builder.CreateCondBr(CondV, ThenBB, ElseBB);
294
295 This code creates the basic blocks that are related to the if/then/else
296 statement, and correspond directly to the blocks in the example above.
297 The first line gets the current Function object that is being built. It
298 gets this by asking the builder for the current BasicBlock, and asking
299 that block for its "parent" (the function it is currently embedded
300 into).
301
302 Once it has that, it creates three blocks. Note that it passes
303 "TheFunction" into the constructor for the "then" block. This causes the
304 constructor to automatically insert the new block into the end of the
305 specified function. The other two blocks are created, but aren't yet
306 inserted into the function.
307
308 Once the blocks are created, we can emit the conditional branch that
309 chooses between them. Note that creating new blocks does not implicitly
310 affect the IRBuilder, so it is still inserting into the block that the
311 condition went into. Also note that it is creating a branch to the
312 "then" block and the "else" block, even though the "else" block isn't
313 inserted into the function yet. This is all ok: it is the standard way
314 that LLVM supports forward references.
315
316 .. code-block:: c++
317
318       // Emit then value.
319       Builder.SetInsertPoint(ThenBB);
320
321       Value *ThenV = Then->Codegen();
322       if (ThenV == 0) return 0;
323
324       Builder.CreateBr(MergeBB);
325       // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
326       ThenBB = Builder.GetInsertBlock();
327
328 After the conditional branch is inserted, we move the builder to start
329 inserting into the "then" block. Strictly speaking, this call moves the
330 insertion point to be at the end of the specified block. However, since
331 the "then" block is empty, it also starts out by inserting at the
332 beginning of the block. :)
333
334 Once the insertion point is set, we recursively codegen the "then"
335 expression from the AST. To finish off the "then" block, we create an
336 unconditional branch to the merge block. One interesting (and very
337 important) aspect of the LLVM IR is that it `requires all basic blocks
338 to be "terminated" <../LangRef.html#functionstructure>`_ with a `control
339 flow instruction <../LangRef.html#terminators>`_ such as return or
340 branch. This means that all control flow, *including fall throughs* must
341 be made explicit in the LLVM IR. If you violate this rule, the verifier
342 will emit an error.
343
344 The final line here is quite subtle, but is very important. The basic
345 issue is that when we create the Phi node in the merge block, we need to
346 set up the block/value pairs that indicate how the Phi will work.
347 Importantly, the Phi node expects to have an entry for each predecessor
348 of the block in the CFG. Why then, are we getting the current block when
349 we just set it to ThenBB 5 lines above? The problem is that the "Then"
350 expression may actually itself change the block that the Builder is
351 emitting into if, for example, it contains a nested "if/then/else"
352 expression. Because calling Codegen recursively could arbitrarily change
353 the notion of the current block, we are required to get an up-to-date
354 value for code that will set up the Phi node.
355
356 .. code-block:: c++
357
358       // Emit else block.
359       TheFunction->getBasicBlockList().push_back(ElseBB);
360       Builder.SetInsertPoint(ElseBB);
361
362       Value *ElseV = Else->Codegen();
363       if (ElseV == 0) return 0;
364
365       Builder.CreateBr(MergeBB);
366       // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
367       ElseBB = Builder.GetInsertBlock();
368
369 Code generation for the 'else' block is basically identical to codegen
370 for the 'then' block. The only significant difference is the first line,
371 which adds the 'else' block to the function. Recall previously that the
372 'else' block was created, but not added to the function. Now that the
373 'then' and 'else' blocks are emitted, we can finish up with the merge
374 code:
375
376 .. code-block:: c++
377
378       // Emit merge block.
379       TheFunction->getBasicBlockList().push_back(MergeBB);
380       Builder.SetInsertPoint(MergeBB);
381       PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
382                                       "iftmp");
383
384       PN->addIncoming(ThenV, ThenBB);
385       PN->addIncoming(ElseV, ElseBB);
386       return PN;
387     }
388
389 The first two lines here are now familiar: the first adds the "merge"
390 block to the Function object (it was previously floating, like the else
391 block above). The second block changes the insertion point so that newly
392 created code will go into the "merge" block. Once that is done, we need
393 to create the PHI node and set up the block/value pairs for the PHI.
394
395 Finally, the CodeGen function returns the phi node as the value computed
396 by the if/then/else expression. In our example above, this returned
397 value will feed into the code for the top-level function, which will
398 create the return instruction.
399
400 Overall, we now have the ability to execute conditional code in
401 Kaleidoscope. With this extension, Kaleidoscope is a fairly complete
402 language that can calculate a wide variety of numeric functions. Next up
403 we'll add another useful expression that is familiar from non-functional
404 languages...
405
406 'for' Loop Expression
407 =====================
408
409 Now that we know how to add basic control flow constructs to the
410 language, we have the tools to add more powerful things. Lets add
411 something more aggressive, a 'for' expression:
412
413 ::
414
415      extern putchard(char)
416      def printstar(n)
417        for i = 1, i < n, 1.0 in
418          putchard(42);  # ascii 42 = '*'
419
420      # print 100 '*' characters
421      printstar(100);
422
423 This expression defines a new variable ("i" in this case) which iterates
424 from a starting value, while the condition ("i < n" in this case) is
425 true, incrementing by an optional step value ("1.0" in this case). If
426 the step value is omitted, it defaults to 1.0. While the loop is true,
427 it executes its body expression. Because we don't have anything better
428 to return, we'll just define the loop as always returning 0.0. In the
429 future when we have mutable variables, it will get more useful.
430
431 As before, lets talk about the changes that we need to Kaleidoscope to
432 support this.
433
434 Lexer Extensions for the 'for' Loop
435 -----------------------------------
436
437 The lexer extensions are the same sort of thing as for if/then/else:
438
439 .. code-block:: c++
440
441       ... in enum Token ...
442       // control
443       tok_if = -6, tok_then = -7, tok_else = -8,
444       tok_for = -9, tok_in = -10
445
446       ... in gettok ...
447       if (IdentifierStr == "def") return tok_def;
448       if (IdentifierStr == "extern") return tok_extern;
449       if (IdentifierStr == "if") return tok_if;
450       if (IdentifierStr == "then") return tok_then;
451       if (IdentifierStr == "else") return tok_else;
452       if (IdentifierStr == "for") return tok_for;
453       if (IdentifierStr == "in") return tok_in;
454       return tok_identifier;
455
456 AST Extensions for the 'for' Loop
457 ---------------------------------
458
459 The AST node is just as simple. It basically boils down to capturing the
460 variable name and the constituent expressions in the node.
461
462 .. code-block:: c++
463
464     /// ForExprAST - Expression class for for/in.
465     class ForExprAST : public ExprAST {
466       std::string VarName;
467       ExprAST *Start, *End, *Step, *Body;
468     public:
469       ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
470                  ExprAST *step, ExprAST *body)
471         : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
472       virtual Value *Codegen();
473     };
474
475 Parser Extensions for the 'for' Loop
476 ------------------------------------
477
478 The parser code is also fairly standard. The only interesting thing here
479 is handling of the optional step value. The parser code handles it by
480 checking to see if the second comma is present. If not, it sets the step
481 value to null in the AST node:
482
483 .. code-block:: c++
484
485     /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
486     static ExprAST *ParseForExpr() {
487       getNextToken();  // eat the for.
488
489       if (CurTok != tok_identifier)
490         return Error("expected identifier after for");
491
492       std::string IdName = IdentifierStr;
493       getNextToken();  // eat identifier.
494
495       if (CurTok != '=')
496         return Error("expected '=' after for");
497       getNextToken();  // eat '='.
498
499
500       ExprAST *Start = ParseExpression();
501       if (Start == 0) return 0;
502       if (CurTok != ',')
503         return Error("expected ',' after for start value");
504       getNextToken();
505
506       ExprAST *End = ParseExpression();
507       if (End == 0) return 0;
508
509       // The step value is optional.
510       ExprAST *Step = 0;
511       if (CurTok == ',') {
512         getNextToken();
513         Step = ParseExpression();
514         if (Step == 0) return 0;
515       }
516
517       if (CurTok != tok_in)
518         return Error("expected 'in' after for");
519       getNextToken();  // eat 'in'.
520
521       ExprAST *Body = ParseExpression();
522       if (Body == 0) return 0;
523
524       return new ForExprAST(IdName, Start, End, Step, Body);
525     }
526
527 LLVM IR for the 'for' Loop
528 --------------------------
529
530 Now we get to the good part: the LLVM IR we want to generate for this
531 thing. With the simple example above, we get this LLVM IR (note that
532 this dump is generated with optimizations disabled for clarity):
533
534 .. code-block:: llvm
535
536     declare double @putchard(double)
537
538     define double @printstar(double %n) {
539     entry:
540       ; initial value = 1.0 (inlined into phi)
541       br label %loop
542
543     loop:       ; preds = %loop, %entry
544       %i = phi double [ 1.000000e+00, %entry ], [ %nextvar, %loop ]
545       ; body
546       %calltmp = call double @putchard(double 4.200000e+01)
547       ; increment
548       %nextvar = fadd double %i, 1.000000e+00
549
550       ; termination test
551       %cmptmp = fcmp ult double %i, %n
552       %booltmp = uitofp i1 %cmptmp to double
553       %loopcond = fcmp one double %booltmp, 0.000000e+00
554       br i1 %loopcond, label %loop, label %afterloop
555
556     afterloop:      ; preds = %loop
557       ; loop always returns 0.0
558       ret double 0.000000e+00
559     }
560
561 This loop contains all the same constructs we saw before: a phi node,
562 several expressions, and some basic blocks. Lets see how this fits
563 together.
564
565 Code Generation for the 'for' Loop
566 ----------------------------------
567
568 The first part of Codegen is very simple: we just output the start
569 expression for the loop value:
570
571 .. code-block:: c++
572
573     Value *ForExprAST::Codegen() {
574       // Emit the start code first, without 'variable' in scope.
575       Value *StartVal = Start->Codegen();
576       if (StartVal == 0) return 0;
577
578 With this out of the way, the next step is to set up the LLVM basic
579 block for the start of the loop body. In the case above, the whole loop
580 body is one block, but remember that the body code itself could consist
581 of multiple blocks (e.g. if it contains an if/then/else or a for/in
582 expression).
583
584 .. code-block:: c++
585
586       // Make the new basic block for the loop header, inserting after current
587       // block.
588       Function *TheFunction = Builder.GetInsertBlock()->getParent();
589       BasicBlock *PreheaderBB = Builder.GetInsertBlock();
590       BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
591
592       // Insert an explicit fall through from the current block to the LoopBB.
593       Builder.CreateBr(LoopBB);
594
595 This code is similar to what we saw for if/then/else. Because we will
596 need it to create the Phi node, we remember the block that falls through
597 into the loop. Once we have that, we create the actual block that starts
598 the loop and create an unconditional branch for the fall-through between
599 the two blocks.
600
601 .. code-block:: c++
602
603       // Start insertion in LoopBB.
604       Builder.SetInsertPoint(LoopBB);
605
606       // Start the PHI node with an entry for Start.
607       PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
608       Variable->addIncoming(StartVal, PreheaderBB);
609
610 Now that the "preheader" for the loop is set up, we switch to emitting
611 code for the loop body. To begin with, we move the insertion point and
612 create the PHI node for the loop induction variable. Since we already
613 know the incoming value for the starting value, we add it to the Phi
614 node. Note that the Phi will eventually get a second value for the
615 backedge, but we can't set it up yet (because it doesn't exist!).
616
617 .. code-block:: c++
618
619       // Within the loop, the variable is defined equal to the PHI node.  If it
620       // shadows an existing variable, we have to restore it, so save it now.
621       Value *OldVal = NamedValues[VarName];
622       NamedValues[VarName] = Variable;
623
624       // Emit the body of the loop.  This, like any other expr, can change the
625       // current BB.  Note that we ignore the value computed by the body, but don't
626       // allow an error.
627       if (Body->Codegen() == 0)
628         return 0;
629
630 Now the code starts to get more interesting. Our 'for' loop introduces a
631 new variable to the symbol table. This means that our symbol table can
632 now contain either function arguments or loop variables. To handle this,
633 before we codegen the body of the loop, we add the loop variable as the
634 current value for its name. Note that it is possible that there is a
635 variable of the same name in the outer scope. It would be easy to make
636 this an error (emit an error and return null if there is already an
637 entry for VarName) but we choose to allow shadowing of variables. In
638 order to handle this correctly, we remember the Value that we are
639 potentially shadowing in ``OldVal`` (which will be null if there is no
640 shadowed variable).
641
642 Once the loop variable is set into the symbol table, the code
643 recursively codegen's the body. This allows the body to use the loop
644 variable: any references to it will naturally find it in the symbol
645 table.
646
647 .. code-block:: c++
648
649       // Emit the step value.
650       Value *StepVal;
651       if (Step) {
652         StepVal = Step->Codegen();
653         if (StepVal == 0) return 0;
654       } else {
655         // If not specified, use 1.0.
656         StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
657       }
658
659       Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
660
661 Now that the body is emitted, we compute the next value of the iteration
662 variable by adding the step value, or 1.0 if it isn't present.
663 '``NextVar``' will be the value of the loop variable on the next
664 iteration of the loop.
665
666 .. code-block:: c++
667
668       // Compute the end condition.
669       Value *EndCond = End->Codegen();
670       if (EndCond == 0) return EndCond;
671
672       // Convert condition to a bool by comparing equal to 0.0.
673       EndCond = Builder.CreateFCmpONE(EndCond,
674                                   ConstantFP::get(getGlobalContext(), APFloat(0.0)),
675                                       "loopcond");
676
677 Finally, we evaluate the exit value of the loop, to determine whether
678 the loop should exit. This mirrors the condition evaluation for the
679 if/then/else statement.
680
681 .. code-block:: c++
682
683       // Create the "after loop" block and insert it.
684       BasicBlock *LoopEndBB = Builder.GetInsertBlock();
685       BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
686
687       // Insert the conditional branch into the end of LoopEndBB.
688       Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
689
690       // Any new code will be inserted in AfterBB.
691       Builder.SetInsertPoint(AfterBB);
692
693 With the code for the body of the loop complete, we just need to finish
694 up the control flow for it. This code remembers the end block (for the
695 phi node), then creates the block for the loop exit ("afterloop"). Based
696 on the value of the exit condition, it creates a conditional branch that
697 chooses between executing the loop again and exiting the loop. Any
698 future code is emitted in the "afterloop" block, so it sets the
699 insertion position to it.
700
701 .. code-block:: c++
702
703       // Add a new entry to the PHI node for the backedge.
704       Variable->addIncoming(NextVar, LoopEndBB);
705
706       // Restore the unshadowed variable.
707       if (OldVal)
708         NamedValues[VarName] = OldVal;
709       else
710         NamedValues.erase(VarName);
711
712       // for expr always returns 0.0.
713       return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
714     }
715
716 The final code handles various cleanups: now that we have the "NextVar"
717 value, we can add the incoming value to the loop PHI node. After that,
718 we remove the loop variable from the symbol table, so that it isn't in
719 scope after the for loop. Finally, code generation of the for loop
720 always returns 0.0, so that is what we return from
721 ``ForExprAST::Codegen``.
722
723 With this, we conclude the "adding control flow to Kaleidoscope" chapter
724 of the tutorial. In this chapter we added two control flow constructs,
725 and used them to motivate a couple of aspects of the LLVM IR that are
726 important for front-end implementors to know. In the next chapter of our
727 saga, we will get a bit crazier and add `user-defined
728 operators <LangImpl6.html>`_ to our poor innocent language.
729
730 Full Code Listing
731 =================
732
733 Here is the complete code listing for our running example, enhanced with
734 the if/then/else and for expressions.. To build this example, use:
735
736 .. code-block:: bash
737
738     # Compile
739     clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
740     # Run
741     ./toy
742
743 Here is the code:
744
745 .. code-block:: c++
746
747     #include "llvm/DerivedTypes.h"
748     #include "llvm/ExecutionEngine/ExecutionEngine.h"
749     #include "llvm/ExecutionEngine/JIT.h"
750     #include "llvm/IRBuilder.h"
751     #include "llvm/LLVMContext.h"
752     #include "llvm/Module.h"
753     #include "llvm/PassManager.h"
754     #include "llvm/Analysis/Verifier.h"
755     #include "llvm/Analysis/Passes.h"
756     #include "llvm/DataLayout.h"
757     #include "llvm/Transforms/Scalar.h"
758     #include "llvm/Support/TargetSelect.h"
759     #include <cstdio>
760     #include <string>
761     #include <map>
762     #include <vector>
763     using namespace llvm;
764
765     //===----------------------------------------------------------------------===//
766     // Lexer
767     //===----------------------------------------------------------------------===//
768
769     // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
770     // of these for known things.
771     enum Token {
772       tok_eof = -1,
773
774       // commands
775       tok_def = -2, tok_extern = -3,
776
777       // primary
778       tok_identifier = -4, tok_number = -5,
779
780       // control
781       tok_if = -6, tok_then = -7, tok_else = -8,
782       tok_for = -9, tok_in = -10
783     };
784
785     static std::string IdentifierStr;  // Filled in if tok_identifier
786     static double NumVal;              // Filled in if tok_number
787
788     /// gettok - Return the next token from standard input.
789     static int gettok() {
790       static int LastChar = ' ';
791
792       // Skip any whitespace.
793       while (isspace(LastChar))
794         LastChar = getchar();
795
796       if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
797         IdentifierStr = LastChar;
798         while (isalnum((LastChar = getchar())))
799           IdentifierStr += LastChar;
800
801         if (IdentifierStr == "def") return tok_def;
802         if (IdentifierStr == "extern") return tok_extern;
803         if (IdentifierStr == "if") return tok_if;
804         if (IdentifierStr == "then") return tok_then;
805         if (IdentifierStr == "else") return tok_else;
806         if (IdentifierStr == "for") return tok_for;
807         if (IdentifierStr == "in") return tok_in;
808         return tok_identifier;
809       }
810
811       if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
812         std::string NumStr;
813         do {
814           NumStr += LastChar;
815           LastChar = getchar();
816         } while (isdigit(LastChar) || LastChar == '.');
817
818         NumVal = strtod(NumStr.c_str(), 0);
819         return tok_number;
820       }
821
822       if (LastChar == '#') {
823         // Comment until end of line.
824         do LastChar = getchar();
825         while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
826
827         if (LastChar != EOF)
828           return gettok();
829       }
830
831       // Check for end of file.  Don't eat the EOF.
832       if (LastChar == EOF)
833         return tok_eof;
834
835       // Otherwise, just return the character as its ascii value.
836       int ThisChar = LastChar;
837       LastChar = getchar();
838       return ThisChar;
839     }
840
841     //===----------------------------------------------------------------------===//
842     // Abstract Syntax Tree (aka Parse Tree)
843     //===----------------------------------------------------------------------===//
844
845     /// ExprAST - Base class for all expression nodes.
846     class ExprAST {
847     public:
848       virtual ~ExprAST() {}
849       virtual Value *Codegen() = 0;
850     };
851
852     /// NumberExprAST - Expression class for numeric literals like "1.0".
853     class NumberExprAST : public ExprAST {
854       double Val;
855     public:
856       NumberExprAST(double val) : Val(val) {}
857       virtual Value *Codegen();
858     };
859
860     /// VariableExprAST - Expression class for referencing a variable, like "a".
861     class VariableExprAST : public ExprAST {
862       std::string Name;
863     public:
864       VariableExprAST(const std::string &name) : Name(name) {}
865       virtual Value *Codegen();
866     };
867
868     /// BinaryExprAST - Expression class for a binary operator.
869     class BinaryExprAST : public ExprAST {
870       char Op;
871       ExprAST *LHS, *RHS;
872     public:
873       BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
874         : Op(op), LHS(lhs), RHS(rhs) {}
875       virtual Value *Codegen();
876     };
877
878     /// CallExprAST - Expression class for function calls.
879     class CallExprAST : public ExprAST {
880       std::string Callee;
881       std::vector<ExprAST*> Args;
882     public:
883       CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
884         : Callee(callee), Args(args) {}
885       virtual Value *Codegen();
886     };
887
888     /// IfExprAST - Expression class for if/then/else.
889     class IfExprAST : public ExprAST {
890       ExprAST *Cond, *Then, *Else;
891     public:
892       IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
893       : Cond(cond), Then(then), Else(_else) {}
894       virtual Value *Codegen();
895     };
896
897     /// ForExprAST - Expression class for for/in.
898     class ForExprAST : public ExprAST {
899       std::string VarName;
900       ExprAST *Start, *End, *Step, *Body;
901     public:
902       ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
903                  ExprAST *step, ExprAST *body)
904         : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
905       virtual Value *Codegen();
906     };
907
908     /// PrototypeAST - This class represents the "prototype" for a function,
909     /// which captures its name, and its argument names (thus implicitly the number
910     /// of arguments the function takes).
911     class PrototypeAST {
912       std::string Name;
913       std::vector<std::string> Args;
914     public:
915       PrototypeAST(const std::string &name, const std::vector<std::string> &args)
916         : Name(name), Args(args) {}
917
918       Function *Codegen();
919     };
920
921     /// FunctionAST - This class represents a function definition itself.
922     class FunctionAST {
923       PrototypeAST *Proto;
924       ExprAST *Body;
925     public:
926       FunctionAST(PrototypeAST *proto, ExprAST *body)
927         : Proto(proto), Body(body) {}
928
929       Function *Codegen();
930     };
931
932     //===----------------------------------------------------------------------===//
933     // Parser
934     //===----------------------------------------------------------------------===//
935
936     /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
937     /// token the parser is looking at.  getNextToken reads another token from the
938     /// lexer and updates CurTok with its results.
939     static int CurTok;
940     static int getNextToken() {
941       return CurTok = gettok();
942     }
943
944     /// BinopPrecedence - This holds the precedence for each binary operator that is
945     /// defined.
946     static std::map<char, int> BinopPrecedence;
947
948     /// GetTokPrecedence - Get the precedence of the pending binary operator token.
949     static int GetTokPrecedence() {
950       if (!isascii(CurTok))
951         return -1;
952
953       // Make sure it's a declared binop.
954       int TokPrec = BinopPrecedence[CurTok];
955       if (TokPrec <= 0) return -1;
956       return TokPrec;
957     }
958
959     /// Error* - These are little helper functions for error handling.
960     ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
961     PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
962     FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
963
964     static ExprAST *ParseExpression();
965
966     /// identifierexpr
967     ///   ::= identifier
968     ///   ::= identifier '(' expression* ')'
969     static ExprAST *ParseIdentifierExpr() {
970       std::string IdName = IdentifierStr;
971
972       getNextToken();  // eat identifier.
973
974       if (CurTok != '(') // Simple variable ref.
975         return new VariableExprAST(IdName);
976
977       // Call.
978       getNextToken();  // eat (
979       std::vector<ExprAST*> Args;
980       if (CurTok != ')') {
981         while (1) {
982           ExprAST *Arg = ParseExpression();
983           if (!Arg) return 0;
984           Args.push_back(Arg);
985
986           if (CurTok == ')') break;
987
988           if (CurTok != ',')
989             return Error("Expected ')' or ',' in argument list");
990           getNextToken();
991         }
992       }
993
994       // Eat the ')'.
995       getNextToken();
996
997       return new CallExprAST(IdName, Args);
998     }
999
1000     /// numberexpr ::= number
1001     static ExprAST *ParseNumberExpr() {
1002       ExprAST *Result = new NumberExprAST(NumVal);
1003       getNextToken(); // consume the number
1004       return Result;
1005     }
1006
1007     /// parenexpr ::= '(' expression ')'
1008     static ExprAST *ParseParenExpr() {
1009       getNextToken();  // eat (.
1010       ExprAST *V = ParseExpression();
1011       if (!V) return 0;
1012
1013       if (CurTok != ')')
1014         return Error("expected ')'");
1015       getNextToken();  // eat ).
1016       return V;
1017     }
1018
1019     /// ifexpr ::= 'if' expression 'then' expression 'else' expression
1020     static ExprAST *ParseIfExpr() {
1021       getNextToken();  // eat the if.
1022
1023       // condition.
1024       ExprAST *Cond = ParseExpression();
1025       if (!Cond) return 0;
1026
1027       if (CurTok != tok_then)
1028         return Error("expected then");
1029       getNextToken();  // eat the then
1030
1031       ExprAST *Then = ParseExpression();
1032       if (Then == 0) return 0;
1033
1034       if (CurTok != tok_else)
1035         return Error("expected else");
1036
1037       getNextToken();
1038
1039       ExprAST *Else = ParseExpression();
1040       if (!Else) return 0;
1041
1042       return new IfExprAST(Cond, Then, Else);
1043     }
1044
1045     /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
1046     static ExprAST *ParseForExpr() {
1047       getNextToken();  // eat the for.
1048
1049       if (CurTok != tok_identifier)
1050         return Error("expected identifier after for");
1051
1052       std::string IdName = IdentifierStr;
1053       getNextToken();  // eat identifier.
1054
1055       if (CurTok != '=')
1056         return Error("expected '=' after for");
1057       getNextToken();  // eat '='.
1058
1059
1060       ExprAST *Start = ParseExpression();
1061       if (Start == 0) return 0;
1062       if (CurTok != ',')
1063         return Error("expected ',' after for start value");
1064       getNextToken();
1065
1066       ExprAST *End = ParseExpression();
1067       if (End == 0) return 0;
1068
1069       // The step value is optional.
1070       ExprAST *Step = 0;
1071       if (CurTok == ',') {
1072         getNextToken();
1073         Step = ParseExpression();
1074         if (Step == 0) return 0;
1075       }
1076
1077       if (CurTok != tok_in)
1078         return Error("expected 'in' after for");
1079       getNextToken();  // eat 'in'.
1080
1081       ExprAST *Body = ParseExpression();
1082       if (Body == 0) return 0;
1083
1084       return new ForExprAST(IdName, Start, End, Step, Body);
1085     }
1086
1087     /// primary
1088     ///   ::= identifierexpr
1089     ///   ::= numberexpr
1090     ///   ::= parenexpr
1091     ///   ::= ifexpr
1092     ///   ::= forexpr
1093     static ExprAST *ParsePrimary() {
1094       switch (CurTok) {
1095       default: return Error("unknown token when expecting an expression");
1096       case tok_identifier: return ParseIdentifierExpr();
1097       case tok_number:     return ParseNumberExpr();
1098       case '(':            return ParseParenExpr();
1099       case tok_if:         return ParseIfExpr();
1100       case tok_for:        return ParseForExpr();
1101       }
1102     }
1103
1104     /// binoprhs
1105     ///   ::= ('+' primary)*
1106     static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
1107       // If this is a binop, find its precedence.
1108       while (1) {
1109         int TokPrec = GetTokPrecedence();
1110
1111         // If this is a binop that binds at least as tightly as the current binop,
1112         // consume it, otherwise we are done.
1113         if (TokPrec < ExprPrec)
1114           return LHS;
1115
1116         // Okay, we know this is a binop.
1117         int BinOp = CurTok;
1118         getNextToken();  // eat binop
1119
1120         // Parse the primary expression after the binary operator.
1121         ExprAST *RHS = ParsePrimary();
1122         if (!RHS) return 0;
1123
1124         // If BinOp binds less tightly with RHS than the operator after RHS, let
1125         // the pending operator take RHS as its LHS.
1126         int NextPrec = GetTokPrecedence();
1127         if (TokPrec < NextPrec) {
1128           RHS = ParseBinOpRHS(TokPrec+1, RHS);
1129           if (RHS == 0) return 0;
1130         }
1131
1132         // Merge LHS/RHS.
1133         LHS = new BinaryExprAST(BinOp, LHS, RHS);
1134       }
1135     }
1136
1137     /// expression
1138     ///   ::= primary binoprhs
1139     ///
1140     static ExprAST *ParseExpression() {
1141       ExprAST *LHS = ParsePrimary();
1142       if (!LHS) return 0;
1143
1144       return ParseBinOpRHS(0, LHS);
1145     }
1146
1147     /// prototype
1148     ///   ::= id '(' id* ')'
1149     static PrototypeAST *ParsePrototype() {
1150       if (CurTok != tok_identifier)
1151         return ErrorP("Expected function name in prototype");
1152
1153       std::string FnName = IdentifierStr;
1154       getNextToken();
1155
1156       if (CurTok != '(')
1157         return ErrorP("Expected '(' in prototype");
1158
1159       std::vector<std::string> ArgNames;
1160       while (getNextToken() == tok_identifier)
1161         ArgNames.push_back(IdentifierStr);
1162       if (CurTok != ')')
1163         return ErrorP("Expected ')' in prototype");
1164
1165       // success.
1166       getNextToken();  // eat ')'.
1167
1168       return new PrototypeAST(FnName, ArgNames);
1169     }
1170
1171     /// definition ::= 'def' prototype expression
1172     static FunctionAST *ParseDefinition() {
1173       getNextToken();  // eat def.
1174       PrototypeAST *Proto = ParsePrototype();
1175       if (Proto == 0) return 0;
1176
1177       if (ExprAST *E = ParseExpression())
1178         return new FunctionAST(Proto, E);
1179       return 0;
1180     }
1181
1182     /// toplevelexpr ::= expression
1183     static FunctionAST *ParseTopLevelExpr() {
1184       if (ExprAST *E = ParseExpression()) {
1185         // Make an anonymous proto.
1186         PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
1187         return new FunctionAST(Proto, E);
1188       }
1189       return 0;
1190     }
1191
1192     /// external ::= 'extern' prototype
1193     static PrototypeAST *ParseExtern() {
1194       getNextToken();  // eat extern.
1195       return ParsePrototype();
1196     }
1197
1198     //===----------------------------------------------------------------------===//
1199     // Code Generation
1200     //===----------------------------------------------------------------------===//
1201
1202     static Module *TheModule;
1203     static IRBuilder<> Builder(getGlobalContext());
1204     static std::map<std::string, Value*> NamedValues;
1205     static FunctionPassManager *TheFPM;
1206
1207     Value *ErrorV(const char *Str) { Error(Str); return 0; }
1208
1209     Value *NumberExprAST::Codegen() {
1210       return ConstantFP::get(getGlobalContext(), APFloat(Val));
1211     }
1212
1213     Value *VariableExprAST::Codegen() {
1214       // Look this variable up in the function.
1215       Value *V = NamedValues[Name];
1216       return V ? V : ErrorV("Unknown variable name");
1217     }
1218
1219     Value *BinaryExprAST::Codegen() {
1220       Value *L = LHS->Codegen();
1221       Value *R = RHS->Codegen();
1222       if (L == 0 || R == 0) return 0;
1223
1224       switch (Op) {
1225       case '+': return Builder.CreateFAdd(L, R, "addtmp");
1226       case '-': return Builder.CreateFSub(L, R, "subtmp");
1227       case '*': return Builder.CreateFMul(L, R, "multmp");
1228       case '<':
1229         L = Builder.CreateFCmpULT(L, R, "cmptmp");
1230         // Convert bool 0/1 to double 0.0 or 1.0
1231         return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
1232                                     "booltmp");
1233       default: return ErrorV("invalid binary operator");
1234       }
1235     }
1236
1237     Value *CallExprAST::Codegen() {
1238       // Look up the name in the global module table.
1239       Function *CalleeF = TheModule->getFunction(Callee);
1240       if (CalleeF == 0)
1241         return ErrorV("Unknown function referenced");
1242
1243       // If argument mismatch error.
1244       if (CalleeF->arg_size() != Args.size())
1245         return ErrorV("Incorrect # arguments passed");
1246
1247       std::vector<Value*> ArgsV;
1248       for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1249         ArgsV.push_back(Args[i]->Codegen());
1250         if (ArgsV.back() == 0) return 0;
1251       }
1252
1253       return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
1254     }
1255
1256     Value *IfExprAST::Codegen() {
1257       Value *CondV = Cond->Codegen();
1258       if (CondV == 0) return 0;
1259
1260       // Convert condition to a bool by comparing equal to 0.0.
1261       CondV = Builder.CreateFCmpONE(CondV,
1262                                   ConstantFP::get(getGlobalContext(), APFloat(0.0)),
1263                                     "ifcond");
1264
1265       Function *TheFunction = Builder.GetInsertBlock()->getParent();
1266
1267       // Create blocks for the then and else cases.  Insert the 'then' block at the
1268       // end of the function.
1269       BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
1270       BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
1271       BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1272
1273       Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1274
1275       // Emit then value.
1276       Builder.SetInsertPoint(ThenBB);
1277
1278       Value *ThenV = Then->Codegen();
1279       if (ThenV == 0) return 0;
1280
1281       Builder.CreateBr(MergeBB);
1282       // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1283       ThenBB = Builder.GetInsertBlock();
1284
1285       // Emit else block.
1286       TheFunction->getBasicBlockList().push_back(ElseBB);
1287       Builder.SetInsertPoint(ElseBB);
1288
1289       Value *ElseV = Else->Codegen();
1290       if (ElseV == 0) return 0;
1291
1292       Builder.CreateBr(MergeBB);
1293       // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1294       ElseBB = Builder.GetInsertBlock();
1295
1296       // Emit merge block.
1297       TheFunction->getBasicBlockList().push_back(MergeBB);
1298       Builder.SetInsertPoint(MergeBB);
1299       PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
1300                                       "iftmp");
1301
1302       PN->addIncoming(ThenV, ThenBB);
1303       PN->addIncoming(ElseV, ElseBB);
1304       return PN;
1305     }
1306
1307     Value *ForExprAST::Codegen() {
1308       // Output this as:
1309       //   ...
1310       //   start = startexpr
1311       //   goto loop
1312       // loop:
1313       //   variable = phi [start, loopheader], [nextvariable, loopend]
1314       //   ...
1315       //   bodyexpr
1316       //   ...
1317       // loopend:
1318       //   step = stepexpr
1319       //   nextvariable = variable + step
1320       //   endcond = endexpr
1321       //   br endcond, loop, endloop
1322       // outloop:
1323
1324       // Emit the start code first, without 'variable' in scope.
1325       Value *StartVal = Start->Codegen();
1326       if (StartVal == 0) return 0;
1327
1328       // Make the new basic block for the loop header, inserting after current
1329       // block.
1330       Function *TheFunction = Builder.GetInsertBlock()->getParent();
1331       BasicBlock *PreheaderBB = Builder.GetInsertBlock();
1332       BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1333
1334       // Insert an explicit fall through from the current block to the LoopBB.
1335       Builder.CreateBr(LoopBB);
1336
1337       // Start insertion in LoopBB.
1338       Builder.SetInsertPoint(LoopBB);
1339
1340       // Start the PHI node with an entry for Start.
1341       PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
1342       Variable->addIncoming(StartVal, PreheaderBB);
1343
1344       // Within the loop, the variable is defined equal to the PHI node.  If it
1345       // shadows an existing variable, we have to restore it, so save it now.
1346       Value *OldVal = NamedValues[VarName];
1347       NamedValues[VarName] = Variable;
1348
1349       // Emit the body of the loop.  This, like any other expr, can change the
1350       // current BB.  Note that we ignore the value computed by the body, but don't
1351       // allow an error.
1352       if (Body->Codegen() == 0)
1353         return 0;
1354
1355       // Emit the step value.
1356       Value *StepVal;
1357       if (Step) {
1358         StepVal = Step->Codegen();
1359         if (StepVal == 0) return 0;
1360       } else {
1361         // If not specified, use 1.0.
1362         StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1363       }
1364
1365       Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
1366
1367       // Compute the end condition.
1368       Value *EndCond = End->Codegen();
1369       if (EndCond == 0) return EndCond;
1370
1371       // Convert condition to a bool by comparing equal to 0.0.
1372       EndCond = Builder.CreateFCmpONE(EndCond,
1373                                   ConstantFP::get(getGlobalContext(), APFloat(0.0)),
1374                                       "loopcond");
1375
1376       // Create the "after loop" block and insert it.
1377       BasicBlock *LoopEndBB = Builder.GetInsertBlock();
1378       BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1379
1380       // Insert the conditional branch into the end of LoopEndBB.
1381       Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1382
1383       // Any new code will be inserted in AfterBB.
1384       Builder.SetInsertPoint(AfterBB);
1385
1386       // Add a new entry to the PHI node for the backedge.
1387       Variable->addIncoming(NextVar, LoopEndBB);
1388
1389       // Restore the unshadowed variable.
1390       if (OldVal)
1391         NamedValues[VarName] = OldVal;
1392       else
1393         NamedValues.erase(VarName);
1394
1395
1396       // for expr always returns 0.0.
1397       return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1398     }
1399
1400     Function *PrototypeAST::Codegen() {
1401       // Make the function type:  double(double,double) etc.
1402       std::vector<Type*> Doubles(Args.size(),
1403                                  Type::getDoubleTy(getGlobalContext()));
1404       FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1405                                            Doubles, false);
1406
1407       Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1408
1409       // If F conflicted, there was already something named 'Name'.  If it has a
1410       // body, don't allow redefinition or reextern.
1411       if (F->getName() != Name) {
1412         // Delete the one we just made and get the existing one.
1413         F->eraseFromParent();
1414         F = TheModule->getFunction(Name);
1415
1416         // If F already has a body, reject this.
1417         if (!F->empty()) {
1418           ErrorF("redefinition of function");
1419           return 0;
1420         }
1421
1422         // If F took a different number of args, reject.
1423         if (F->arg_size() != Args.size()) {
1424           ErrorF("redefinition of function with different # args");
1425           return 0;
1426         }
1427       }
1428
1429       // Set names for all arguments.
1430       unsigned Idx = 0;
1431       for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1432            ++AI, ++Idx) {
1433         AI->setName(Args[Idx]);
1434
1435         // Add arguments to variable symbol table.
1436         NamedValues[Args[Idx]] = AI;
1437       }
1438
1439       return F;
1440     }
1441
1442     Function *FunctionAST::Codegen() {
1443       NamedValues.clear();
1444
1445       Function *TheFunction = Proto->Codegen();
1446       if (TheFunction == 0)
1447         return 0;
1448
1449       // Create a new basic block to start insertion into.
1450       BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1451       Builder.SetInsertPoint(BB);
1452
1453       if (Value *RetVal = Body->Codegen()) {
1454         // Finish off the function.
1455         Builder.CreateRet(RetVal);
1456
1457         // Validate the generated code, checking for consistency.
1458         verifyFunction(*TheFunction);
1459
1460         // Optimize the function.
1461         TheFPM->run(*TheFunction);
1462
1463         return TheFunction;
1464       }
1465
1466       // Error reading body, remove function.
1467       TheFunction->eraseFromParent();
1468       return 0;
1469     }
1470
1471     //===----------------------------------------------------------------------===//
1472     // Top-Level parsing and JIT Driver
1473     //===----------------------------------------------------------------------===//
1474
1475     static ExecutionEngine *TheExecutionEngine;
1476
1477     static void HandleDefinition() {
1478       if (FunctionAST *F = ParseDefinition()) {
1479         if (Function *LF = F->Codegen()) {
1480           fprintf(stderr, "Read function definition:");
1481           LF->dump();
1482         }
1483       } else {
1484         // Skip token for error recovery.
1485         getNextToken();
1486       }
1487     }
1488
1489     static void HandleExtern() {
1490       if (PrototypeAST *P = ParseExtern()) {
1491         if (Function *F = P->Codegen()) {
1492           fprintf(stderr, "Read extern: ");
1493           F->dump();
1494         }
1495       } else {
1496         // Skip token for error recovery.
1497         getNextToken();
1498       }
1499     }
1500
1501     static void HandleTopLevelExpression() {
1502       // Evaluate a top-level expression into an anonymous function.
1503       if (FunctionAST *F = ParseTopLevelExpr()) {
1504         if (Function *LF = F->Codegen()) {
1505           // JIT the function, returning a function pointer.
1506           void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1507
1508           // Cast it to the right type (takes no arguments, returns a double) so we
1509           // can call it as a native function.
1510           double (*FP)() = (double (*)())(intptr_t)FPtr;
1511           fprintf(stderr, "Evaluated to %f\n", FP());
1512         }
1513       } else {
1514         // Skip token for error recovery.
1515         getNextToken();
1516       }
1517     }
1518
1519     /// top ::= definition | external | expression | ';'
1520     static void MainLoop() {
1521       while (1) {
1522         fprintf(stderr, "ready> ");
1523         switch (CurTok) {
1524         case tok_eof:    return;
1525         case ';':        getNextToken(); break;  // ignore top-level semicolons.
1526         case tok_def:    HandleDefinition(); break;
1527         case tok_extern: HandleExtern(); break;
1528         default:         HandleTopLevelExpression(); break;
1529         }
1530       }
1531     }
1532
1533     //===----------------------------------------------------------------------===//
1534     // "Library" functions that can be "extern'd" from user code.
1535     //===----------------------------------------------------------------------===//
1536
1537     /// putchard - putchar that takes a double and returns 0.
1538     extern "C"
1539     double putchard(double X) {
1540       putchar((char)X);
1541       return 0;
1542     }
1543
1544     //===----------------------------------------------------------------------===//
1545     // Main driver code.
1546     //===----------------------------------------------------------------------===//
1547
1548     int main() {
1549       InitializeNativeTarget();
1550       LLVMContext &Context = getGlobalContext();
1551
1552       // Install standard binary operators.
1553       // 1 is lowest precedence.
1554       BinopPrecedence['<'] = 10;
1555       BinopPrecedence['+'] = 20;
1556       BinopPrecedence['-'] = 20;
1557       BinopPrecedence['*'] = 40;  // highest.
1558
1559       // Prime the first token.
1560       fprintf(stderr, "ready> ");
1561       getNextToken();
1562
1563       // Make the module, which holds all the code.
1564       TheModule = new Module("my cool jit", Context);
1565
1566       // Create the JIT.  This takes ownership of the module.
1567       std::string ErrStr;
1568       TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
1569       if (!TheExecutionEngine) {
1570         fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1571         exit(1);
1572       }
1573
1574       FunctionPassManager OurFPM(TheModule);
1575
1576       // Set up the optimizer pipeline.  Start with registering info about how the
1577       // target lays out data structures.
1578       OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
1579       // Provide basic AliasAnalysis support for GVN.
1580       OurFPM.add(createBasicAliasAnalysisPass());
1581       // Do simple "peephole" optimizations and bit-twiddling optzns.
1582       OurFPM.add(createInstructionCombiningPass());
1583       // Reassociate expressions.
1584       OurFPM.add(createReassociatePass());
1585       // Eliminate Common SubExpressions.
1586       OurFPM.add(createGVNPass());
1587       // Simplify the control flow graph (deleting unreachable blocks, etc).
1588       OurFPM.add(createCFGSimplificationPass());
1589
1590       OurFPM.doInitialization();
1591
1592       // Set the global so the code gen can use this.
1593       TheFPM = &OurFPM;
1594
1595       // Run the main "interpreter loop" now.
1596       MainLoop();
1597
1598       TheFPM = 0;
1599
1600       // Print out all of the generated code.
1601       TheModule->dump();
1602
1603       return 0;
1604     }
1605
1606 `Next: Extending the language: user-defined operators <LangImpl6.html>`_
1607