22987e552bf4e6a63f5a10a1c82c35cfc2ed7f52
[oota-llvm.git] / docs / tutorial / LangImpl3.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3
4 <html>
5 <head>
6   <title>Kaleidoscope: Implementing code generation to LLVM IR</title>
7   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8   <meta name="author" content="Chris Lattner">
9   <link rel="stylesheet" href="../llvm.css" type="text/css">
10 </head>
11
12 <body>
13
14 <div class="doc_title">Kaleidoscope: Code generation to LLVM IR</div>
15
16 <ul>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
18 <li>Chapter 3
19   <ol>
20     <li><a href="#intro">Chapter 3 Introduction</a></li>
21     <li><a href="#basics">Code Generation setup</a></li>
22     <li><a href="#exprs">Expression Code Generation</a></li>
23     <li><a href="#funcs">Function Code Generation</a></li>
24     <li><a href="#driver">Driver Changes and Closing Thoughts</a></li>
25     <li><a href="#code">Full Code Listing</a></li>
26   </ol>
27 </li>
28 <li><a href="LangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer 
29 Support</li>
30 </ul>
31
32 <div class="doc_author">
33   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
34 </div>
35
36 <!-- *********************************************************************** -->
37 <div class="doc_section"><a name="intro">Chapter 3 Introduction</a></div>
38 <!-- *********************************************************************** -->
39
40 <div class="doc_text">
41
42 <p>Welcome to Chapter 3 of the "<a href="index.html">Implementing a language
43 with LLVM</a>" tutorial.  This chapter shows you how to transform the <a 
44 href="LangImpl2.html">Abstract Syntax Tree built in Chapter 2</a> into LLVM IR.
45 This will teach you a little bit about how LLVM does things, as well as
46 demonstrate how easy it is to use.  It's much more work to build a lexer and
47 parser than it is to generate LLVM IR code.
48 </p>
49
50 </div>
51
52 <!-- *********************************************************************** -->
53 <div class="doc_section"><a name="basics">Code Generation setup</a></div>
54 <!-- *********************************************************************** -->
55
56 <div class="doc_text">
57
58 <p>
59 In order to generate LLVM IR, we want some simple setup to get started.  First,
60 we define virtual codegen methods in each AST class:</p>
61
62 <div class="doc_code">
63 <pre>
64 /// ExprAST - Base class for all expression nodes.
65 class ExprAST {
66 public:
67   virtual ~ExprAST() {}
68   <b>virtual Value *Codegen() = 0;</b>
69 };
70
71 /// NumberExprAST - Expression class for numeric literals like "1.0".
72 class NumberExprAST : public ExprAST {
73   double Val;
74 public:
75   explicit NumberExprAST(double val) : Val(val) {}
76   <b>virtual Value *Codegen();</b>
77 };
78 ...
79 </pre>
80 </div>
81
82 <p>The Codegen() method says to emit IR for that AST node and all things it
83 depends on, and they all return an LLVM Value object. 
84 "Value" is the class used to represent a "<a 
85 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
86 Assignment (SSA)</a> register" or "SSA value" in LLVM.  The most distinct aspect
87 of SSA values is that their value is computed as the related instruction
88 executes, and it does not get a new value until (and if) the instruction
89 re-executes.  In order words, there is no way to "change" an SSA value.  For
90 more information, please read up on <a 
91 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
92 Assignment</a> - the concepts are really quite natural once you grok them.</p>
93
94 <p>Note that instead of adding virtual methods to the ExprAST class hierarchy,
95 it could also make sense to use a visitor pattern or some other way to model
96 this.  Again, this tutorial won't dwell on good software engineering practices:
97 for our purposes, adding a virtual method is simplest.</p>
98
99 <p>The
100 second thing we want is an "Error" method like we used for parser, which will
101 be used to report errors found during code generation (for example, use of an
102 undeclared parameter):</p>
103
104 <div class="doc_code">
105 <pre>
106 Value *ErrorV(const char *Str) { Error(Str); return 0; }
107
108 static Module *TheModule;
109 static LLVMBuilder Builder;
110 static std::map&lt;std::string, Value*&gt; NamedValues;
111 </pre>
112 </div>
113
114 <p>The static variables will be used during code generation.  <tt>TheModule</tt>
115 is the LLVM construct that contains all of the functions and global variables in
116 a chunk of code.  In many ways, it is the top-level structure that the LLVM IR
117 uses to contain code.</p>
118
119 <p>The <tt>Builder</tt> object is a helper object that makes it easy to generate
120 LLVM instructions.  Instances of the <a 
121 href="http://llvm.org/doxygen/LLVMBuilder_8h-source.html"><tt>LLVMBuilder</tt> 
122 class</a> keeps track of the current place to
123 insert instructions and has methods to create new instructions.</p>
124
125 <p>The <tt>NamedValues</tt> map keeps track of which values are defined in the
126 current scope and what their LLVM representation is.  In this form of
127 Kaleidoscope, the only things that can be referenced are function parameters.
128 As such, function parameters will be in this map when generating code for their
129 function body.</p>
130
131 <p>
132 With these basics in place, we can start talking about how to generate code for
133 each expression.  Note that this assumes that the <tt>Builder</tt> has been set
134 up to generate code <em>into</em> something.  For now, we'll assume that this
135 has already been done, and we'll just use it to emit code.
136 </p>
137
138 </div>
139
140 <!-- *********************************************************************** -->
141 <div class="doc_section"><a name="exprs">Expression Code Generation</a></div>
142 <!-- *********************************************************************** -->
143
144 <div class="doc_text">
145
146 <p>Generating LLVM code for expression nodes is very straight-forward: less
147 than 45 lines of commented code for all four of our expression nodes.  First,
148 we'll do numeric literals:</p>
149
150 <div class="doc_code">
151 <pre>
152 Value *NumberExprAST::Codegen() {
153   return ConstantFP::get(Type::DoubleTy, APFloat(Val));
154 }
155 </pre>
156 </div>
157
158 <p>In the LLVM IR, numeric constants are represented with the
159 <tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
160 internally (<tt>APFloat</tt> has the capability of holding floating point
161 constants of <em>A</em>rbitrary <em>P</em>recision).  This code basically just
162 creates and returns a <tt>ConstantFP</tt>.  Note that in the LLVM IR
163 that constants are all uniqued together and shared.  For this reason, the API
164 uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::create(..).</p>
165
166 <div class="doc_code">
167 <pre>
168 Value *VariableExprAST::Codegen() {
169   // Look this variable up in the function.
170   Value *V = NamedValues[Name];
171   return V ? V : ErrorV("Unknown variable name");
172 }
173 </pre>
174 </div>
175
176 <p>References to variables is also quite simple here.  In the simple version
177 of Kaleidoscope, we assume that the variable has already been emited somewhere
178 and its value is available.  In practice, the only values that can be in the
179 <tt>NamedValues</tt> map are function arguments.  This
180 code simply checks to see that the specified name is in the map (if not, an 
181 unknown variable is being referenced) and returns the value for it.</p>
182
183 <div class="doc_code">
184 <pre>
185 Value *BinaryExprAST::Codegen() {
186   Value *L = LHS-&gt;Codegen();
187   Value *R = RHS-&gt;Codegen();
188   if (L == 0 || R == 0) return 0;
189   
190   switch (Op) {
191   case '+': return Builder.CreateAdd(L, R, "addtmp");
192   case '-': return Builder.CreateSub(L, R, "subtmp");
193   case '*': return Builder.CreateMul(L, R, "multmp");
194   case '&lt;':
195     L = Builder.CreateFCmpULT(L, R, "multmp");
196     // Convert bool 0/1 to double 0.0 or 1.0
197     return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
198   default: return ErrorV("invalid binary operator");
199   }
200 }
201 </pre>
202 </div>
203
204 <p>Binary operators start to get more interesting.  The basic idea here is that
205 we recursively emit code for the left-hand side of the expression, then the 
206 right-hand side, then we compute the result of the binary expression.  In this
207 code, we do a simple switch on the opcode to create the right LLVM instruction.
208 </p>
209
210 <p>In this example, the LLVM builder class is starting to show its value.  
211 Because it knows where to insert the newly created instruction, you just have to
212 specificy what instruction to create (e.g. with <tt>CreateAdd</tt>), which
213 operands to use (<tt>L</tt> and <tt>R</tt> here) and optionally provide a name
214 for the generated instruction.  One nice thing about LLVM is that the name is 
215 just a hint: if there are multiple additions in a single function, the first
216 will be named "addtmp" and the second will be "autorenamed" by adding a suffix,
217 giving it a name like "addtmp42".  Local value names for instructions are purely
218 optional, but it makes it much easier to read the IR dumps.</p>
219
220 <p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained to
221 have very strict type properties: for example, the Left and Right operators of
222 an <a href="../LangRef.html#i_add">add instruction</a> have to have the same
223 type, and that the result of the add matches the operands.  Because all values
224 in Kaleidoscope are doubles, this makes for very simple code for add, sub and
225 mul.</p>
226
227 <p>On the other hand, LLVM specifies that the <a 
228 href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
229 (a one bit integer).  However, Kaleidoscope wants the value to be a 0.0 or 1.0
230 value.  In order to get these semantics, we combine the fcmp instruction with
231 a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>.  This instruction
232 converts its input integer into a floating point value by treating the input
233 as an unsigned value.  In contrast, if we used the <a 
234 href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '<'
235 operator would return 0.0 and -1.0, depending on the input value.</p>
236
237 <div class="doc_code">
238 <pre>
239 Value *CallExprAST::Codegen() {
240   // Look up the name in the global module table.
241   Function *CalleeF = TheModule-&gt;getFunction(Callee);
242   if (CalleeF == 0)
243     return ErrorV("Unknown function referenced");
244   
245   // If argument mismatch error.
246   if (CalleeF-&gt;arg_size() != Args.size())
247     return ErrorV("Incorrect # arguments passed");
248
249   std::vector&lt;Value*&gt; ArgsV;
250   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
251     ArgsV.push_back(Args[i]-&gt;Codegen());
252     if (ArgsV.back() == 0) return 0;
253   }
254   
255   return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
256 }
257 </pre>
258 </div>
259
260 <p>Code generation for function calls is quite straight-forward with LLVM.  The
261 code above first looks the name of the function up in the LLVM Module's symbol
262 table.  Recall that the LLVM Module is the container that holds all of the
263 functions we are JIT'ing.  By giving each function the same name as what the
264 user specifies, we can use the LLVM symbol table to resolve function names for
265 us.</p>
266
267 <p>Once we have the function to call, we recursively codegen each argument that
268 is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
269 instruction</a>.  Note that LLVM uses the native C calling conventions by
270 default, allowing these calls to call into standard library functions like
271 "sin" and "cos" with no additional effort.</p>
272
273 <p>This wraps up our handling of the four basic expressions that we have so far
274 in Kaleidoscope.  Feel free to go in and add some more.  For example, by 
275 browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
276 several other interesting instructions that are really easy to plug into our
277 basic framework.</p>
278
279 </div>
280
281 <!-- *********************************************************************** -->
282 <div class="doc_section"><a name="funcs">Function Code Generation</a></div>
283 <!-- *********************************************************************** -->
284
285 <div class="doc_text">
286
287 <p>Code generation for prototypes and functions has to handle a number of
288 details, which make their code less beautiful and elegant than expression code
289 generation, but they illustrate some important points.  First, lets talk about
290 code generation for prototypes: this is used both for function bodies as well
291 as external function declarations.  The code starts with:</p>
292
293 <div class="doc_code">
294 <pre>
295 Function *PrototypeAST::Codegen() {
296   // Make the function type:  double(double,double) etc.
297   std::vector&lt;const Type*&gt; Doubles(Args.size(), Type::DoubleTy);
298   FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
299   
300   Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
301 </pre>
302 </div>
303
304 <p>This code packs a lot of power into a few lines.  Note first that this 
305 function returns a Function* instead of a Value*.  Because a "prototype" really
306 talks about the external interface for a function (not the value computed by
307 an expression), it makes sense for it to return the LLVM Function it corresponds
308 to when codegen'd.</p>
309
310 <p>The next step is to create
311 the <tt>FunctionType</tt> that should be used for a given Prototype.  Since all
312 function arguments in Kaleidoscope are of type double, the first line creates
313 a vector of "N" LLVM Double types.  It then uses the <tt>FunctionType::get</tt>
314 method to create a function type that takes "N" doubles as arguments, returns
315 one double as a result, and that is not vararg (the false parameter indicates
316 this).  Note that Types in LLVM are uniqued just like Constants are, so you
317 don't "new" a type, you "get" it.</p>
318
319 <p>The final line above actually creates the function that the prototype will
320 correspond to.  This indicates which type, linkage, and name to use, and which
321 module to insert into.  "<a href="LangRef.html#linkage">external linkage</a>"
322 means that the function may be defined outside the current module and/or that it
323 is callable by functions outside the module.  The Name passed in is the name the
324 user specified: since "<tt>TheModule</tt>" is specified, this name is registered
325 in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
326 above.</p>
327
328 <div class="doc_code">
329 <pre>
330   // If F conflicted, there was already something named 'Name'.  If it has a
331   // body, don't allow redefinition or reextern.
332   if (F-&gt;getName() != Name) {
333     // Delete the one we just made and get the existing one.
334     F-&gt;eraseFromParent();
335     F = TheModule-&gt;getFunction(Name);
336 </pre>
337 </div>
338
339 <p>The Module symbol table works just like the Function symbol table when it
340 comes to name conflicts: if a new function is created with a name was previously
341 added to the symbol table, it will get implicitly renamed when added to the
342 Module.  The code above exploits this fact to tell if there was a previous
343 definition of this function.</p>
344
345 <p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
346 first, we want to allow 'extern'ing a function more than once, so long as the
347 prototypes for the externs match (since all arguments have the same type, we
348 just have to check that the number of arguments match).  Second, we want to
349 allow 'extern'ing a function and then definining a body for it.  This is useful
350 when defining mutually recursive functions.</p>
351
352 <p>In order to implement this, the code above first checks to see if there is
353 a collision on the name of the function.  If so, it deletes the function we just
354 created (by calling <tt>eraseFromParent</tt>) and then calling 
355 <tt>getFunction</tt> to get the existing function with the specified name.  Note
356 that many APIs in LLVM have "erase" forms and "remove" forms.  The "remove" form
357 unlinks the object from its parent (e.g. a Function from a Module) and returns
358 it.  The "erase" form unlinks the object and then deletes it.</p>
359    
360 <div class="doc_code">
361 <pre>
362     // If F already has a body, reject this.
363     if (!F-&gt;empty()) {
364       ErrorF("redefinition of function");
365       return 0;
366     }
367     
368     // If F took a different number of args, reject.
369     if (F-&gt;arg_size() != Args.size()) {
370       ErrorF("redefinition of function with different # args");
371       return 0;
372     }
373   }
374 </pre>
375 </div>
376
377 <p>In order to verify the logic above, we first check to see if the preexisting
378 function is "empty".  In this case, empty means that it has no basic blocks in
379 it, which means it has no body.  If it has no body, this means its a forward 
380 declaration.  Since we don't allow anything after a full definition of the
381 function, the code rejects this case.  If the previous reference to a function
382 was an 'extern', we simply verify that the number of arguments for that
383 definition and this one match up.  If not, we emit an error.</p>
384
385 <div class="doc_code">
386 <pre>
387   // Set names for all arguments.
388   unsigned Idx = 0;
389   for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
390        ++AI, ++Idx) {
391     AI-&gt;setName(Args[Idx]);
392     
393     // Add arguments to variable symbol table.
394     NamedValues[Args[Idx]] = AI;
395   }
396   return F;
397 }
398 </pre>
399 </div>
400
401 <p>The last bit of code for prototypes loops over all of the arguments in the
402 function, setting the name of the LLVM Argument objects to match and registering
403 the arguments in the <tt>NamedValues</tt> map for future use by the
404 <tt>VariableExprAST</tt> AST node.  Once this is set up, it returns the Function
405 object to the caller.  Note that we don't check for conflicting 
406 argument names here (e.g. "extern foo(a b a)").  Doing so would be very
407 straight-forward.</p>
408
409 <div class="doc_code">
410 <pre>
411 Function *FunctionAST::Codegen() {
412   NamedValues.clear();
413   
414   Function *TheFunction = Proto-&gt;Codegen();
415   if (TheFunction == 0)
416     return 0;
417 </pre>
418 </div>
419
420 <p>Code generation for function definitions starts out simply enough: first we
421 codegen the prototype and verify that it is ok.  We also clear out the
422 <tt>NamedValues</tt> map to make sure that there isn't anything in it from the
423 last function we compiled.</p>
424
425 <div class="doc_code">
426 <pre>
427   // Create a new basic block to start insertion into.
428   BasicBlock *BB = new BasicBlock("entry", TheFunction);
429   Builder.SetInsertPoint(BB);
430   
431   if (Value *RetVal = Body-&gt;Codegen()) {
432 </pre>
433 </div>
434
435 <p>Now we get to the point where the <tt>Builder</tt> is set up.  The first
436 line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
437 block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>.  The
438 second line then tells the builder that new instructions should be inserted into
439 the end of the new basic block.  Basic blocks in LLVM are an important part
440 of functions that define the <a 
441 href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
442 Since we don't have any control flow, our functions will only contain one 
443 block so far.  We'll fix this in a future installment :).</p>
444
445 <div class="doc_code">
446 <pre>
447   if (Value *RetVal = Body-&gt;Codegen()) {
448     // Finish off the function.
449     Builder.CreateRet(RetVal);
450     
451     // Validate the generated code, checking for consistency.
452     verifyFunction(*TheFunction);
453     return TheFunction;
454   }
455 </pre>
456 </div>
457
458 <p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
459 the root expression of the function.  If no error happens, this emits code to
460 compute the expression into the entry block and returns the value that was
461 computed.  Assuming no error, we then create an LLVM <a 
462 href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
463 Once the function is built, we call the <tt>verifyFunction</tt> function, which
464 is provided by LLVM.  This function does a variety of consistency checks on the
465 generated code, to determine if our compiler is doing everything right.  Using
466 this is important: it can catch a lot of bugs.  Once the function is finished
467 and validated, we return it.</p>
468   
469 <div class="doc_code">
470 <pre>
471   // Error reading body, remove function.
472   TheFunction-&gt;eraseFromParent();
473   return 0;
474 }
475 </pre>
476 </div>
477
478 <p>The only piece left here is handling of the error case.  For simplicity, we
479 simply handle this by deleting the function we produced with the 
480 <tt>eraseFromParent</tt> method.  This allows the user to redefine a function
481 that they incorrectly typed in before: if we didn't delete it, it would live in
482 the symbol table, with a body, preventing future redefinition.</p>
483
484 <p>This code does have a bug though.  Since the <tt>PrototypeAST::Codegen</tt>
485 can return a previously defined forward declaration, this can actually delete
486 a forward declaration.  There are a number of ways to fix this bug, see what you
487 can come up with!  Here is a testcase:</p>
488
489 <div class="doc_code">
490 <pre>
491 extern foo(a b);     # ok, defines foo.
492 def foo(a b) c;      # error, 'c' is invalid.
493 def bar() foo(1, 2); # error, unknown function "foo"
494 </pre>
495 </div>
496
497 </div>
498
499 <!-- *********************************************************************** -->
500 <div class="doc_section"><a name="driver">Driver Changes and 
501 Closing Thoughts</a></div>
502 <!-- *********************************************************************** -->
503
504 <div class="doc_text">
505
506 <p>
507 For now, code generation to LLVM doesn't really get us much, except that we can
508 look at the pretty IR calls.  The sample code inserts calls to Codegen into the
509 "<tt>HandleDefinition</tt>", "<tt>HandleExtern</tt>" etc functions, and then
510 dumps out the LLVM IR.  This gives a nice way to look at the LLVM IR for simple
511 functions.  For example:
512 </p>
513
514 <div class="doc_code">
515 <pre>
516 ready> <b>4+5</b>;
517 ready> Read top-level expression:
518 define double @""() {
519 entry:
520         %addtmp = add double 4.000000e+00, 5.000000e+00
521         ret double %addtmp
522 }
523 </pre>
524 </div>
525
526 <p>Note how the parser turns the top-level expression into anonymous functions
527 for us.  This will be handy when we add JIT support in the next chapter.  Also
528 note that the code is very literally transcribed, no optimizations are being
529 performed.  We will add optimizations explicitly in the next chapter.</p>
530
531 <div class="doc_code">
532 <pre>
533 ready&gt; <b>def foo(a b) a*a + 2*a*b + b*b;</b>
534 ready&gt; Read function definition:
535 define double @foo(double %a, double %b) {
536 entry:
537         %multmp = mul double %a, %a
538         %multmp1 = mul double 2.000000e+00, %a
539         %multmp2 = mul double %multmp1, %b
540         %addtmp = add double %multmp, %multmp2
541         %multmp3 = mul double %b, %b
542         %addtmp4 = add double %addtmp, %multmp3
543         ret double %addtmp4
544 }
545 </pre>
546 </div>
547
548 <p>This shows some simple arithmetic. Notice the striking similarity to the
549 LLVM builder calls that we use to create the instructions.</p>
550
551 <div class="doc_code">
552 <pre>
553 ready&gt; <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
554 ready&gt; Read function definition:
555 define double @bar(double %a) {
556 entry:
557         %calltmp = call double @foo( double %a, double 4.000000e+00 )
558         %calltmp1 = call double @bar( double 3.133700e+04 )
559         %addtmp = add double %calltmp, %calltmp1
560         ret double %addtmp
561 }
562 </pre>
563 </div>
564
565 <p>This shows some function calls.  Note that this function will take a long
566 time to execute if you call it.  In the future we'll add conditional control 
567 flow to make recursion actually be useful :).</p>
568
569 <div class="doc_code">
570 <pre>
571 ready&gt; <b>extern cos(x);</b>
572 ready&gt; Read extern: 
573 declare double @cos(double)
574
575 ready&gt; <b>cos(1.234);</b>
576 ready&gt; Read top-level expression:
577 define double @""() {
578 entry:
579         %calltmp = call double @cos( double 1.234000e+00 )
580         ret double %calltmp
581 }
582 </pre>
583 </div>
584
585 <p>This shows an extern for the libm "cos" function, and a call to it.</p>
586
587
588 <div class="doc_code">
589 <pre>
590 ready&gt; <b>^D</b>
591 ; ModuleID = 'my cool jit'
592
593 define double @""() {
594 entry:
595         %addtmp = add double 4.000000e+00, 5.000000e+00
596         ret double %addtmp
597 }
598
599 define double @foo(double %a, double %b) {
600 entry:
601         %multmp = mul double %a, %a
602         %multmp1 = mul double 2.000000e+00, %a
603         %multmp2 = mul double %multmp1, %b
604         %addtmp = add double %multmp, %multmp2
605         %multmp3 = mul double %b, %b
606         %addtmp4 = add double %addtmp, %multmp3
607         ret double %addtmp4
608 }
609
610 define double @bar(double %a) {
611 entry:
612         %calltmp = call double @foo( double %a, double 4.000000e+00 )
613         %calltmp1 = call double @bar( double 3.133700e+04 )
614         %addtmp = add double %calltmp, %calltmp1
615         ret double %addtmp
616 }
617
618 declare double @cos(double)
619
620 define double @""() {
621 entry:
622         %calltmp = call double @cos( double 1.234000e+00 )
623         ret double %calltmp
624 }
625 </pre>
626 </div>
627
628 <p>When you quit the current demo, it dumps out the IR for the entire module
629 generated.  Here you can see the big picture with all the functions referencing
630 each other.</p>
631
632 <p>This wraps up this chapter of the Kaleidoscope tutorial.  Up next we'll
633 describe how to <a href="LangImpl4.html">add JIT codegen and optimizer
634 support</a> to this so we can actually start running code!</p>
635
636 </div>
637
638
639 <!-- *********************************************************************** -->
640 <div class="doc_section"><a name="code">Full Code Listing</a></div>
641 <!-- *********************************************************************** -->
642
643 <div class="doc_text">
644
645 <p>
646 Here is the complete code listing for our running example, enhanced with the
647 LLVM code generator.    Because this uses the LLVM libraries, we need to link
648 them in.  To do this, we use the <a 
649 href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
650 our makefile/command line about which options to use:</p>
651
652 <div class="doc_code">
653 <pre>
654    # Compile
655    g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core` -o toy
656    # Run
657    ./toy
658 </pre>
659 </div>
660
661 <p>Here is the code:</p>
662
663 <div class="doc_code">
664 <pre>
665 // To build this:
666 // See example below.
667
668 #include "llvm/DerivedTypes.h"
669 #include "llvm/Module.h"
670 #include "llvm/Analysis/Verifier.h"
671 #include "llvm/Support/LLVMBuilder.h"
672 #include &lt;cstdio&gt;
673 #include &lt;string&gt;
674 #include &lt;map&gt;
675 #include &lt;vector&gt;
676 using namespace llvm;
677
678 //===----------------------------------------------------------------------===//
679 // Lexer
680 //===----------------------------------------------------------------------===//
681
682 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
683 // of these for known things.
684 enum Token {
685   tok_eof = -1,
686
687   // commands
688   tok_def = -2, tok_extern = -3,
689
690   // primary
691   tok_identifier = -4, tok_number = -5,
692 };
693
694 static std::string IdentifierStr;  // Filled in if tok_identifier
695 static double NumVal;              // Filled in if tok_number
696
697 /// gettok - Return the next token from standard input.
698 static int gettok() {
699   static int LastChar = ' ';
700
701   // Skip any whitespace.
702   while (isspace(LastChar))
703     LastChar = getchar();
704
705   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
706     IdentifierStr = LastChar;
707     while (isalnum((LastChar = getchar())))
708       IdentifierStr += LastChar;
709
710     if (IdentifierStr == "def") return tok_def;
711     if (IdentifierStr == "extern") return tok_extern;
712     return tok_identifier;
713   }
714
715   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
716     std::string NumStr;
717     do {
718       NumStr += LastChar;
719       LastChar = getchar();
720     } while (isdigit(LastChar) || LastChar == '.');
721
722     NumVal = strtod(NumStr.c_str(), 0);
723     return tok_number;
724   }
725
726   if (LastChar == '#') {
727     // Comment until end of line.
728     do LastChar = getchar();
729     while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp; LastChar != '\r');
730     
731     if (LastChar != EOF)
732       return gettok();
733   }
734   
735   // Check for end of file.  Don't eat the EOF.
736   if (LastChar == EOF)
737     return tok_eof;
738
739   // Otherwise, just return the character as its ascii value.
740   int ThisChar = LastChar;
741   LastChar = getchar();
742   return ThisChar;
743 }
744
745 //===----------------------------------------------------------------------===//
746 // Abstract Syntax Tree (aka Parse Tree)
747 //===----------------------------------------------------------------------===//
748
749 /// ExprAST - Base class for all expression nodes.
750 class ExprAST {
751 public:
752   virtual ~ExprAST() {}
753   virtual Value *Codegen() = 0;
754 };
755
756 /// NumberExprAST - Expression class for numeric literals like "1.0".
757 class NumberExprAST : public ExprAST {
758   double Val;
759 public:
760   explicit NumberExprAST(double val) : Val(val) {}
761   virtual Value *Codegen();
762 };
763
764 /// VariableExprAST - Expression class for referencing a variable, like "a".
765 class VariableExprAST : public ExprAST {
766   std::string Name;
767 public:
768   explicit VariableExprAST(const std::string &amp;name) : Name(name) {}
769   virtual Value *Codegen();
770 };
771
772 /// BinaryExprAST - Expression class for a binary operator.
773 class BinaryExprAST : public ExprAST {
774   char Op;
775   ExprAST *LHS, *RHS;
776 public:
777   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 
778     : Op(op), LHS(lhs), RHS(rhs) {}
779   virtual Value *Codegen();
780 };
781
782 /// CallExprAST - Expression class for function calls.
783 class CallExprAST : public ExprAST {
784   std::string Callee;
785   std::vector&lt;ExprAST*&gt; Args;
786 public:
787   CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
788     : Callee(callee), Args(args) {}
789   virtual Value *Codegen();
790 };
791
792 /// PrototypeAST - This class represents the "prototype" for a function,
793 /// which captures its argument names as well as if it is an operator.
794 class PrototypeAST {
795   std::string Name;
796   std::vector&lt;std::string&gt; Args;
797 public:
798   PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
799     : Name(name), Args(args) {}
800   
801   Function *Codegen();
802 };
803
804 /// FunctionAST - This class represents a function definition itself.
805 class FunctionAST {
806   PrototypeAST *Proto;
807   ExprAST *Body;
808 public:
809   FunctionAST(PrototypeAST *proto, ExprAST *body)
810     : Proto(proto), Body(body) {}
811   
812   Function *Codegen();
813 };
814
815 //===----------------------------------------------------------------------===//
816 // Parser
817 //===----------------------------------------------------------------------===//
818
819 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
820 /// token the parser it looking at.  getNextToken reads another token from the
821 /// lexer and updates CurTok with its results.
822 static int CurTok;
823 static int getNextToken() {
824   return CurTok = gettok();
825 }
826
827 /// BinopPrecedence - This holds the precedence for each binary operator that is
828 /// defined.
829 static std::map&lt;char, int&gt; BinopPrecedence;
830
831 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
832 static int GetTokPrecedence() {
833   if (!isascii(CurTok))
834     return -1;
835   
836   // Make sure it's a declared binop.
837   int TokPrec = BinopPrecedence[CurTok];
838   if (TokPrec &lt;= 0) return -1;
839   return TokPrec;
840 }
841
842 /// Error* - These are little helper functions for error handling.
843 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
844 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
845 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
846
847 static ExprAST *ParseExpression();
848
849 /// identifierexpr
850 ///   ::= identifier
851 ///   ::= identifier '(' expression* ')'
852 static ExprAST *ParseIdentifierExpr() {
853   std::string IdName = IdentifierStr;
854   
855   getNextToken();  // eat identifier.
856   
857   if (CurTok != '(') // Simple variable ref.
858     return new VariableExprAST(IdName);
859   
860   // Call.
861   getNextToken();  // eat (
862   std::vector&lt;ExprAST*&gt; Args;
863   while (1) {
864     ExprAST *Arg = ParseExpression();
865     if (!Arg) return 0;
866     Args.push_back(Arg);
867     
868     if (CurTok == ')') break;
869     
870     if (CurTok != ',')
871       return Error("Expected ')'");
872     getNextToken();
873   }
874
875   // Eat the ')'.
876   getNextToken();
877   
878   return new CallExprAST(IdName, Args);
879 }
880
881 /// numberexpr ::= number
882 static ExprAST *ParseNumberExpr() {
883   ExprAST *Result = new NumberExprAST(NumVal);
884   getNextToken(); // consume the number
885   return Result;
886 }
887
888 /// parenexpr ::= '(' expression ')'
889 static ExprAST *ParseParenExpr() {
890   getNextToken();  // eat (.
891   ExprAST *V = ParseExpression();
892   if (!V) return 0;
893   
894   if (CurTok != ')')
895     return Error("expected ')'");
896   getNextToken();  // eat ).
897   return V;
898 }
899
900 /// primary
901 ///   ::= identifierexpr
902 ///   ::= numberexpr
903 ///   ::= parenexpr
904 static ExprAST *ParsePrimary() {
905   switch (CurTok) {
906   default: return Error("unknown token when expecting an expression");
907   case tok_identifier: return ParseIdentifierExpr();
908   case tok_number:     return ParseNumberExpr();
909   case '(':            return ParseParenExpr();
910   }
911 }
912
913 /// binoprhs
914 ///   ::= ('+' primary)*
915 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
916   // If this is a binop, find its precedence.
917   while (1) {
918     int TokPrec = GetTokPrecedence();
919     
920     // If this is a binop that binds at least as tightly as the current binop,
921     // consume it, otherwise we are done.
922     if (TokPrec &lt; ExprPrec)
923       return LHS;
924     
925     // Okay, we know this is a binop.
926     int BinOp = CurTok;
927     getNextToken();  // eat binop
928     
929     // Parse the primary expression after the binary operator.
930     ExprAST *RHS = ParsePrimary();
931     if (!RHS) return 0;
932     
933     // If BinOp binds less tightly with RHS than the operator after RHS, let
934     // the pending operator take RHS as its LHS.
935     int NextPrec = GetTokPrecedence();
936     if (TokPrec &lt; NextPrec) {
937       RHS = ParseBinOpRHS(TokPrec+1, RHS);
938       if (RHS == 0) return 0;
939     }
940     
941     // Merge LHS/RHS.
942     LHS = new BinaryExprAST(BinOp, LHS, RHS);
943   }
944 }
945
946 /// expression
947 ///   ::= primary binoprhs
948 ///
949 static ExprAST *ParseExpression() {
950   ExprAST *LHS = ParsePrimary();
951   if (!LHS) return 0;
952   
953   return ParseBinOpRHS(0, LHS);
954 }
955
956 /// prototype
957 ///   ::= id '(' id* ')'
958 static PrototypeAST *ParsePrototype() {
959   if (CurTok != tok_identifier)
960     return ErrorP("Expected function name in prototype");
961
962   std::string FnName = IdentifierStr;
963   getNextToken();
964   
965   if (CurTok != '(')
966     return ErrorP("Expected '(' in prototype");
967   
968   std::vector&lt;std::string&gt; ArgNames;
969   while (getNextToken() == tok_identifier)
970     ArgNames.push_back(IdentifierStr);
971   if (CurTok != ')')
972     return ErrorP("Expected ')' in prototype");
973   
974   // success.
975   getNextToken();  // eat ')'.
976   
977   return new PrototypeAST(FnName, ArgNames);
978 }
979
980 /// definition ::= 'def' prototype expression
981 static FunctionAST *ParseDefinition() {
982   getNextToken();  // eat def.
983   PrototypeAST *Proto = ParsePrototype();
984   if (Proto == 0) return 0;
985
986   if (ExprAST *E = ParseExpression())
987     return new FunctionAST(Proto, E);
988   return 0;
989 }
990
991 /// toplevelexpr ::= expression
992 static FunctionAST *ParseTopLevelExpr() {
993   if (ExprAST *E = ParseExpression()) {
994     // Make an anonymous proto.
995     PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
996     return new FunctionAST(Proto, E);
997   }
998   return 0;
999 }
1000
1001 /// external ::= 'extern' prototype
1002 static PrototypeAST *ParseExtern() {
1003   getNextToken();  // eat extern.
1004   return ParsePrototype();
1005 }
1006
1007 //===----------------------------------------------------------------------===//
1008 // Code Generation
1009 //===----------------------------------------------------------------------===//
1010
1011 static Module *TheModule;
1012 static LLVMBuilder Builder;
1013 static std::map&lt;std::string, Value*&gt; NamedValues;
1014
1015 Value *ErrorV(const char *Str) { Error(Str); return 0; }
1016
1017 Value *NumberExprAST::Codegen() {
1018   return ConstantFP::get(Type::DoubleTy, APFloat(Val));
1019 }
1020
1021 Value *VariableExprAST::Codegen() {
1022   // Look this variable up in the function.
1023   Value *V = NamedValues[Name];
1024   return V ? V : ErrorV("Unknown variable name");
1025 }
1026
1027 Value *BinaryExprAST::Codegen() {
1028   Value *L = LHS-&gt;Codegen();
1029   Value *R = RHS-&gt;Codegen();
1030   if (L == 0 || R == 0) return 0;
1031   
1032   switch (Op) {
1033   case '+': return Builder.CreateAdd(L, R, "addtmp");
1034   case '-': return Builder.CreateSub(L, R, "subtmp");
1035   case '*': return Builder.CreateMul(L, R, "multmp");
1036   case '&lt;':
1037     L = Builder.CreateFCmpULT(L, R, "multmp");
1038     // Convert bool 0/1 to double 0.0 or 1.0
1039     return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
1040   default: return ErrorV("invalid binary operator");
1041   }
1042 }
1043
1044 Value *CallExprAST::Codegen() {
1045   // Look up the name in the global module table.
1046   Function *CalleeF = TheModule-&gt;getFunction(Callee);
1047   if (CalleeF == 0)
1048     return ErrorV("Unknown function referenced");
1049   
1050   // If argument mismatch error.
1051   if (CalleeF-&gt;arg_size() != Args.size())
1052     return ErrorV("Incorrect # arguments passed");
1053
1054   std::vector&lt;Value*&gt; ArgsV;
1055   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1056     ArgsV.push_back(Args[i]-&gt;Codegen());
1057     if (ArgsV.back() == 0) return 0;
1058   }
1059   
1060   return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
1061 }
1062
1063 Function *PrototypeAST::Codegen() {
1064   // Make the function type:  double(double,double) etc.
1065   std::vector&lt;const Type*&gt; Doubles(Args.size(), Type::DoubleTy);
1066   FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
1067   
1068   Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
1069   
1070   // If F conflicted, there was already something named 'Name'.  If it has a
1071   // body, don't allow redefinition or reextern.
1072   if (F-&gt;getName() != Name) {
1073     // Delete the one we just made and get the existing one.
1074     F-&gt;eraseFromParent();
1075     F = TheModule-&gt;getFunction(Name);
1076     
1077     // If F already has a body, reject this.
1078     if (!F-&gt;empty()) {
1079       ErrorF("redefinition of function");
1080       return 0;
1081     }
1082     
1083     // If F took a different number of args, reject.
1084     if (F-&gt;arg_size() != Args.size()) {
1085       ErrorF("redefinition of function with different # args");
1086       return 0;
1087     }
1088   }
1089   
1090   // Set names for all arguments.
1091   unsigned Idx = 0;
1092   for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
1093        ++AI, ++Idx) {
1094     AI-&gt;setName(Args[Idx]);
1095     
1096     // Add arguments to variable symbol table.
1097     NamedValues[Args[Idx]] = AI;
1098   }
1099   
1100   return F;
1101 }
1102
1103 Function *FunctionAST::Codegen() {
1104   NamedValues.clear();
1105   
1106   Function *TheFunction = Proto-&gt;Codegen();
1107   if (TheFunction == 0)
1108     return 0;
1109   
1110   // Create a new basic block to start insertion into.
1111   BasicBlock *BB = new BasicBlock("entry", TheFunction);
1112   Builder.SetInsertPoint(BB);
1113   
1114   if (Value *RetVal = Body-&gt;Codegen()) {
1115     // Finish off the function.
1116     Builder.CreateRet(RetVal);
1117     
1118     // Validate the generated code, checking for consistency.
1119     verifyFunction(*TheFunction);
1120     return TheFunction;
1121   }
1122   
1123   // Error reading body, remove function.
1124   TheFunction-&gt;eraseFromParent();
1125   return 0;
1126 }
1127
1128 //===----------------------------------------------------------------------===//
1129 // Top-Level parsing and JIT Driver
1130 //===----------------------------------------------------------------------===//
1131
1132 static void HandleDefinition() {
1133   if (FunctionAST *F = ParseDefinition()) {
1134     if (Function *LF = F-&gt;Codegen()) {
1135       fprintf(stderr, "Read function definition:");
1136       LF-&gt;dump();
1137     }
1138   } else {
1139     // Skip token for error recovery.
1140     getNextToken();
1141   }
1142 }
1143
1144 static void HandleExtern() {
1145   if (PrototypeAST *P = ParseExtern()) {
1146     if (Function *F = P-&gt;Codegen()) {
1147       fprintf(stderr, "Read extern: ");
1148       F-&gt;dump();
1149     }
1150   } else {
1151     // Skip token for error recovery.
1152     getNextToken();
1153   }
1154 }
1155
1156 static void HandleTopLevelExpression() {
1157   // Evaluate a top level expression into an anonymous function.
1158   if (FunctionAST *F = ParseTopLevelExpr()) {
1159     if (Function *LF = F-&gt;Codegen()) {
1160       fprintf(stderr, "Read top-level expression:");
1161       LF-&gt;dump();
1162     }
1163   } else {
1164     // Skip token for error recovery.
1165     getNextToken();
1166   }
1167 }
1168
1169 /// top ::= definition | external | expression | ';'
1170 static void MainLoop() {
1171   while (1) {
1172     fprintf(stderr, "ready&gt; ");
1173     switch (CurTok) {
1174     case tok_eof:    return;
1175     case ';':        getNextToken(); break;  // ignore top level semicolons.
1176     case tok_def:    HandleDefinition(); break;
1177     case tok_extern: HandleExtern(); break;
1178     default:         HandleTopLevelExpression(); break;
1179     }
1180   }
1181 }
1182
1183
1184
1185 //===----------------------------------------------------------------------===//
1186 // "Library" functions that can be "extern'd" from user code.
1187 //===----------------------------------------------------------------------===//
1188
1189 /// putchard - putchar that takes a double and returns 0.
1190 extern "C" 
1191 double putchard(double X) {
1192   putchar((char)X);
1193   return 0;
1194 }
1195
1196 //===----------------------------------------------------------------------===//
1197 // Main driver code.
1198 //===----------------------------------------------------------------------===//
1199
1200 int main() {
1201   TheModule = new Module("my cool jit");
1202
1203   // Install standard binary operators.
1204   // 1 is lowest precedence.
1205   BinopPrecedence['&lt;'] = 10;
1206   BinopPrecedence['+'] = 20;
1207   BinopPrecedence['-'] = 20;
1208   BinopPrecedence['*'] = 40;  // highest.
1209
1210   // Prime the first token.
1211   fprintf(stderr, "ready&gt; ");
1212   getNextToken();
1213
1214   MainLoop();
1215   TheModule-&gt;dump();
1216   return 0;
1217 }
1218 </pre>
1219 </div>
1220 </div>
1221
1222 <!-- *********************************************************************** -->
1223 <hr>
1224 <address>
1225   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1226   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1227   <a href="http://validator.w3.org/check/referer"><img
1228   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1229
1230   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1231   <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1232   Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
1233 </address>
1234 </body>
1235 </html>