Merge LLVMBuilder and FoldingBuilder, calling
[oota-llvm.git] / docs / tutorial / LangImpl4.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: Adding JIT and Optimizer Support</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: Adding JIT and Optimizer Support</div>
15
16 <ul>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
18 <li>Chapter 4
19   <ol>
20     <li><a href="#intro">Chapter 4 Introduction</a></li>
21     <li><a href="#trivialconstfold">Trivial Constant Folding</a></li>
22     <li><a href="#optimizerpasses">LLVM Optimization Passes</a></li>
23     <li><a href="#jit">Adding a JIT Compiler</a></li>
24     <li><a href="#code">Full Code Listing</a></li>
25   </ol>
26 </li>
27 <li><a href="LangImpl5.html">Chapter 5</a>: Extending the Language: Control 
28 Flow</li>
29 </ul>
30
31 <div class="doc_author">
32   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
33 </div>
34
35 <!-- *********************************************************************** -->
36 <div class="doc_section"><a name="intro">Chapter 4 Introduction</a></div>
37 <!-- *********************************************************************** -->
38
39 <div class="doc_text">
40
41 <p>Welcome to Chapter 4 of the "<a href="index.html">Implementing a language
42 with LLVM</a>" tutorial.  Chapters 1-3 described the implementation of a simple
43 language and added support for generating LLVM IR.  This chapter describes
44 two new techniques: adding optimizer support to your language, and adding JIT
45 compiler support.  These additions will demonstrate how to get nice, efficient code 
46 for the Kaleidoscope language.</p>
47
48 </div>
49
50 <!-- *********************************************************************** -->
51 <div class="doc_section"><a name="trivialconstfold">Trivial Constant
52 Folding</a></div>
53 <!-- *********************************************************************** -->
54
55 <div class="doc_text">
56
57 <p>
58 Our demonstration for Chapter 3 is elegant and easy to extend.  Unfortunately,
59 it does not produce wonderful code.  The IRBuilder, however, does give us
60 obvious optimizations when compiling simple code:</p>
61
62 <div class="doc_code">
63 <pre>
64 ready&gt; <b>def test(x) 1+2+x;</b>
65 Read function definition:
66 define double @test(double %x) {
67 entry:
68         %addtmp = add double 3.000000e+00, %x
69         ret double %addtmp
70 }
71 </pre>
72 </div>
73
74 <p>This code is not a literal transcription of the AST built by parsing the 
75 input. That would be:
76
77 <div class="doc_code">
78 <pre>
79 ready&gt; <b>def test(x) 1+2+x;</b>
80 Read function definition:
81 define double @test(double %x) {
82 entry:
83         %addtmp = add double 2.000000e+00, 1.000000e+00
84         %addtmp1 = add double %addtmp, %x
85         ret double %addtmp1
86 }
87 </pre>
88 </div>
89
90 Constant folding, as seen above, in particular, is a very common and very
91 important optimization: so much so that many language implementors implement
92 constant folding support in their AST representation.</p>
93
94 <p>With LLVM, you don't need this support in the AST.  Since all calls to build 
95 LLVM IR go through the LLVM IR builder, the builder itself checked to see if 
96 there was a constant folding opportunity when you call it.  If so, it just does 
97 the constant fold and return the constant instead of creating an instruction.
98
99 <p>Well, that was easy :).  In practice, we recommend always using
100 <tt>IRBuilder</tt> when generating code like this.  It has no
101 "syntactic overhead" for its use (you don't have to uglify your compiler with
102 constant checks everywhere) and it can dramatically reduce the amount of
103 LLVM IR that is generated in some cases (particular for languages with a macro
104 preprocessor or that use a lot of constants).</p>
105
106 <p>On the other hand, the <tt>IRBuilder</tt> is limited by the fact
107 that it does all of its analysis inline with the code as it is built.  If you
108 take a slightly more complex example:</p>
109
110 <div class="doc_code">
111 <pre>
112 ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
113 ready> Read function definition:
114 define double @test(double %x) {
115 entry:
116         %addtmp = add double 3.000000e+00, %x
117         %addtmp1 = add double %x, 3.000000e+00
118         %multmp = mul double %addtmp, %addtmp1
119         ret double %multmp
120 }
121 </pre>
122 </div>
123
124 <p>In this case, the LHS and RHS of the multiplication are the same value.  We'd
125 really like to see this generate "<tt>tmp = x+3; result = tmp*tmp;</tt>" instead
126 of computing "<tt>x*3</tt>" twice.</p>
127
128 <p>Unfortunately, no amount of local analysis will be able to detect and correct
129 this.  This requires two transformations: reassociation of expressions (to 
130 make the add's lexically identical) and Common Subexpression Elimination (CSE)
131 to  delete the redundant add instruction.  Fortunately, LLVM provides a broad
132 range of optimizations that you can use, in the form of "passes".</p>
133
134 </div>
135
136 <!-- *********************************************************************** -->
137 <div class="doc_section"><a name="optimizerpasses">LLVM Optimization
138  Passes</a></div>
139 <!-- *********************************************************************** -->
140
141 <div class="doc_text">
142
143 <p>LLVM provides many optimization passes, which do many different sorts of
144 things and have different tradeoffs.  Unlike other systems, LLVM doesn't hold
145 to the mistaken notion that one set of optimizations is right for all languages
146 and for all situations.  LLVM allows a compiler implementor to make complete
147 decisions about what optimizations to use, in which order, and in what
148 situation.</p>
149
150 <p>As a concrete example, LLVM supports both "whole module" passes, which look
151 across as large of body of code as they can (often a whole file, but if run 
152 at link time, this can be a substantial portion of the whole program).  It also
153 supports and includes "per-function" passes which just operate on a single
154 function at a time, without looking at other functions.  For more information
155 on passes and how they are run, see the <a href="../WritingAnLLVMPass.html">How
156 to Write a Pass</a> document and the <a href="../Passes.html">List of LLVM 
157 Passes</a>.</p>
158
159 <p>For Kaleidoscope, we are currently generating functions on the fly, one at
160 a time, as the user types them in.  We aren't shooting for the ultimate
161 optimization experience in this setting, but we also want to catch the easy and
162 quick stuff where possible.  As such, we will choose to run a few per-function
163 optimizations as the user types the function in.  If we wanted to make a "static
164 Kaleidoscope compiler", we would use exactly the code we have now, except that
165 we would defer running the optimizer until the entire file has been parsed.</p>
166
167 <p>In order to get per-function optimizations going, we need to set up a
168 <a href="../WritingAnLLVMPass.html#passmanager">FunctionPassManager</a> to hold and
169 organize the LLVM optimizations that we want to run.  Once we have that, we can
170 add a set of optimizations to run.  The code looks like this:</p>
171
172 <div class="doc_code">
173 <pre>
174     ExistingModuleProvider OurModuleProvider(TheModule);
175     FunctionPassManager OurFPM(&amp;OurModuleProvider);
176       
177     // Set up the optimizer pipeline.  Start with registering info about how the
178     // target lays out data structures.
179     OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
180     // Do simple "peephole" optimizations and bit-twiddling optzns.
181     OurFPM.add(createInstructionCombiningPass());
182     // Reassociate expressions.
183     OurFPM.add(createReassociatePass());
184     // Eliminate Common SubExpressions.
185     OurFPM.add(createGVNPass());
186     // Simplify the control flow graph (deleting unreachable blocks, etc).
187     OurFPM.add(createCFGSimplificationPass());
188
189     // Set the global so the code gen can use this.
190     TheFPM = &amp;OurFPM;
191
192     // Run the main "interpreter loop" now.
193     MainLoop();
194 </pre>
195 </div>
196
197 <p>This code defines two objects, an <tt>ExistingModuleProvider</tt> and a
198 <tt>FunctionPassManager</tt>.  The former is basically a wrapper around our
199 <tt>Module</tt> that the PassManager requires.  It provides certain flexibility
200 that we're not going to take advantage of here, so I won't dive into any details 
201 about it.</p>
202
203 <p>The meat of the matter here, is the definition of "<tt>OurFPM</tt>".  It
204 requires a pointer to the <tt>Module</tt> (through the <tt>ModuleProvider</tt>)
205 to construct itself.  Once it is set up, we use a series of "add" calls to add
206 a bunch of LLVM passes.  The first pass is basically boilerplate, it adds a pass
207 so that later optimizations know how the data structures in the program are
208 layed out.  The "<tt>TheExecutionEngine</tt>" variable is related to the JIT,
209 which we will get to in the next section.</p>
210
211 <p>In this case, we choose to add 4 optimization passes.  The passes we chose
212 here are a pretty standard set of "cleanup" optimizations that are useful for
213 a wide variety of code.  I won't delve into what they do but, believe me,
214 they are a good starting place :).</p>
215
216 <p>Once the PassManager is set up, we need to make use of it.  We do this by
217 running it after our newly created function is constructed (in 
218 <tt>FunctionAST::Codegen</tt>), but before it is returned to the client:</p>
219
220 <div class="doc_code">
221 <pre>
222   if (Value *RetVal = Body->Codegen()) {
223     // Finish off the function.
224     Builder.CreateRet(RetVal);
225
226     // Validate the generated code, checking for consistency.
227     verifyFunction(*TheFunction);
228
229     <b>// Optimize the function.
230     TheFPM-&gt;run(*TheFunction);</b>
231     
232     return TheFunction;
233   }
234 </pre>
235 </div>
236
237 <p>As you can see, this is pretty straightforward.  The 
238 <tt>FunctionPassManager</tt> optimizes and updates the LLVM Function* in place,
239 improving (hopefully) its body.  With this in place, we can try our test above
240 again:</p>
241
242 <div class="doc_code">
243 <pre>
244 ready&gt; <b>def test(x) (1+2+x)*(x+(1+2));</b>
245 ready> Read function definition:
246 define double @test(double %x) {
247 entry:
248         %addtmp = add double %x, 3.000000e+00
249         %multmp = mul double %addtmp, %addtmp
250         ret double %multmp
251 }
252 </pre>
253 </div>
254
255 <p>As expected, we now get our nicely optimized code, saving a floating point
256 add instruction from every execution of this function.</p>
257
258 <p>LLVM provides a wide variety of optimizations that can be used in certain
259 circumstances.  Some <a href="../Passes.html">documentation about the various 
260 passes</a> is available, but it isn't very complete.  Another good source of
261 ideas can come from looking at the passes that <tt>llvm-gcc</tt> or
262 <tt>llvm-ld</tt> run to get started.  The "<tt>opt</tt>" tool allows you to 
263 experiment with passes from the command line, so you can see if they do
264 anything.</p>
265
266 <p>Now that we have reasonable code coming out of our front-end, lets talk about
267 executing it!</p>
268
269 </div>
270
271 <!-- *********************************************************************** -->
272 <div class="doc_section"><a name="jit">Adding a JIT Compiler</a></div>
273 <!-- *********************************************************************** -->
274
275 <div class="doc_text">
276
277 <p>Code that is available in LLVM IR can have a wide variety of tools 
278 applied to it.  For example, you can run optimizations on it (as we did above),
279 you can dump it out in textual or binary forms, you can compile the code to an
280 assembly file (.s) for some target, or you can JIT compile it.  The nice thing
281 about the LLVM IR representation is that it is the "common currency" between
282 many different parts of the compiler.
283 </p>
284
285 <p>In this section, we'll add JIT compiler support to our interpreter.  The
286 basic idea that we want for Kaleidoscope is to have the user enter function
287 bodies as they do now, but immediately evaluate the top-level expressions they
288 type in.  For example, if they type in "1 + 2;", we should evaluate and print
289 out 3.  If they define a function, they should be able to call it from the 
290 command line.</p>
291
292 <p>In order to do this, we first declare and initialize the JIT.  This is done
293 by adding a global variable and a call in <tt>main</tt>:</p>
294
295 <div class="doc_code">
296 <pre>
297 <b>static ExecutionEngine *TheExecutionEngine;</b>
298 ...
299 int main() {
300   ..
301   <b>// Create the JIT.
302   TheExecutionEngine = ExecutionEngine::create(TheModule);</b>
303   ..
304 }
305 </pre>
306 </div>
307
308 <p>This creates an abstract "Execution Engine" which can be either a JIT
309 compiler or the LLVM interpreter.  LLVM will automatically pick a JIT compiler
310 for you if one is available for your platform, otherwise it will fall back to
311 the interpreter.</p>
312
313 <p>Once the <tt>ExecutionEngine</tt> is created, the JIT is ready to be used.
314 There are a variety of APIs that are useful, but the simplest one is the
315 "<tt>getPointerToFunction(F)</tt>" method.  This method JIT compiles the
316 specified LLVM Function and returns a function pointer to the generated machine
317 code.  In our case, this means that we can change the code that parses a
318 top-level expression to look like this:</p>
319
320 <div class="doc_code">
321 <pre>
322 static void HandleTopLevelExpression() {
323   // Evaluate a top level expression into an anonymous function.
324   if (FunctionAST *F = ParseTopLevelExpr()) {
325     if (Function *LF = F-&gt;Codegen()) {
326       LF->dump();  // Dump the function for exposition purposes.
327     
328       <b>// JIT the function, returning a function pointer.
329       void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
330       
331       // Cast it to the right type (takes no arguments, returns a double) so we
332       // can call it as a native function.
333       double (*FP)() = (double (*)())FPtr;
334       fprintf(stderr, "Evaluated to %f\n", FP());</b>
335     }
336 </pre>
337 </div>
338
339 <p>Recall that we compile top-level expressions into a self-contained LLVM
340 function that takes no arguments and returns the computed double.  Because the 
341 LLVM JIT compiler matches the native platform ABI, this means that you can just
342 cast the result pointer to a function pointer of that type and call it directly.
343 This means, there is no difference between JIT compiled code and native machine
344 code that is statically linked into your application.</p>
345
346 <p>With just these two changes, lets see how Kaleidoscope works now!</p>
347
348 <div class="doc_code">
349 <pre>
350 ready&gt; <b>4+5;</b>
351 define double @""() {
352 entry:
353         ret double 9.000000e+00
354 }
355
356 <em>Evaluated to 9.000000</em>
357 </pre>
358 </div>
359
360 <p>Well this looks like it is basically working.  The dump of the function
361 shows the "no argument function that always returns double" that we synthesize
362 for each top level expression that is typed in.  This demonstrates very basic
363 functionality, but can we do more?</p>
364
365 <div class="doc_code">
366 <pre>
367 ready&gt; <b>def testfunc(x y) x + y*2; </b> 
368 Read function definition:
369 define double @testfunc(double %x, double %y) {
370 entry:
371         %multmp = mul double %y, 2.000000e+00
372         %addtmp = add double %multmp, %x
373         ret double %addtmp
374 }
375
376 ready&gt; <b>testfunc(4, 10);</b>
377 define double @""() {
378 entry:
379         %calltmp = call double @testfunc( double 4.000000e+00, double 1.000000e+01 )
380         ret double %calltmp
381 }
382
383 <em>Evaluated to 24.000000</em>
384 </pre>
385 </div>
386
387 <p>This illustrates that we can now call user code, but there is something a bit subtle
388 going on here.  Note that we only invoke the JIT on the anonymous functions
389 that <em>call testfunc</em>, but we never invoked it on <em>testfunc
390 </em>itself.</p>
391
392 <p>What actually happened here is that the anonymous function was
393 JIT'd when requested.  When the Kaleidoscope app calls through the function
394 pointer that is returned, the anonymous function starts executing.  It ends up
395 making the call to the "testfunc" function, and ends up in a stub that invokes
396 the JIT, lazily, on testfunc.  Once the JIT finishes lazily compiling testfunc,
397 it returns and the code re-executes the call.</p>
398
399 <p>In summary, the JIT will lazily JIT code, on the fly, as it is needed.  The
400 JIT provides a number of other more advanced interfaces for things like freeing
401 allocated machine code, rejit'ing functions to update them, etc.  However, even
402 with this simple code, we get some surprisingly powerful capabilities - check
403 this out (I removed the dump of the anonymous functions, you should get the idea
404 by now :) :</p>
405
406 <div class="doc_code">
407 <pre>
408 ready&gt; <b>extern sin(x);</b>
409 Read extern: 
410 declare double @sin(double)
411
412 ready&gt; <b>extern cos(x);</b>
413 Read extern: 
414 declare double @cos(double)
415
416 ready&gt; <b>sin(1.0);</b>
417 <em>Evaluated to 0.841471</em>
418
419 ready&gt; <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
420 Read function definition:
421 define double @foo(double %x) {
422 entry:
423         %calltmp = call double @sin( double %x )
424         %multmp = mul double %calltmp, %calltmp
425         %calltmp2 = call double @cos( double %x )
426         %multmp4 = mul double %calltmp2, %calltmp2
427         %addtmp = add double %multmp, %multmp4
428         ret double %addtmp
429 }
430
431 ready&gt; <b>foo(4.0);</b>
432 <em>Evaluated to 1.000000</em>
433 </pre>
434 </div>
435
436 <p>Whoa, how does the JIT know about sin and cos?  The answer is surprisingly
437 simple: in this
438 example, the JIT started execution of a function and got to a function call.  It
439 realized that the function was not yet JIT compiled and invoked the standard set
440 of routines to resolve the function.  In this case, there is no body defined
441 for the function, so the JIT ended up calling "<tt>dlsym("sin")</tt>" on the
442 Kaleidoscope process itself.
443 Since "<tt>sin</tt>" is defined within the JIT's address space, it simply
444 patches up calls in the module to call the libm version of <tt>sin</tt>
445 directly.</p>
446
447 <p>The LLVM JIT provides a number of interfaces (look in the 
448 <tt>ExecutionEngine.h</tt> file) for controlling how unknown functions get
449 resolved.  It allows you to establish explicit mappings between IR objects and
450 addresses (useful for LLVM global variables that you want to map to static
451 tables, for example), allows you to dynamically decide on the fly based on the
452 function name, and even allows you to have the JIT abort itself if any lazy
453 compilation is attempted.</p>
454
455 <p>One interesting application of this is that we can now extend the language
456 by writing arbitrary C++ code to implement operations.  For example, if we add:
457 </p>
458
459 <div class="doc_code">
460 <pre>
461 /// putchard - putchar that takes a double and returns 0.
462 extern "C" 
463 double putchard(double X) {
464   putchar((char)X);
465   return 0;
466 }
467 </pre>
468 </div>
469
470 <p>Now we can produce simple output to the console by using things like:
471 "<tt>extern putchard(x); putchard(120);</tt>", which prints a lowercase 'x' on
472 the console (120 is the ASCII code for 'x').  Similar code could be used to 
473 implement file I/O, console input, and many other capabilities in
474 Kaleidoscope.</p>
475
476 <p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
477 this point, we can compile a non-Turing-complete programming language, optimize
478 and JIT compile it in a user-driven way.  Next up we'll look into <a 
479 href="LangImpl5.html">extending the language with control flow constructs</a>,
480 tackling some interesting LLVM IR issues along the way.</p>
481
482 </div>
483
484 <!-- *********************************************************************** -->
485 <div class="doc_section"><a name="code">Full Code Listing</a></div>
486 <!-- *********************************************************************** -->
487
488 <div class="doc_text">
489
490 <p>
491 Here is the complete code listing for our running example, enhanced with the
492 LLVM JIT and optimizer.  To build this example, use:
493 </p>
494
495 <div class="doc_code">
496 <pre>
497    # Compile
498    g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
499    # Run
500    ./toy
501 </pre>
502 </div>
503
504 <p>Here is the code:</p>
505
506 <div class="doc_code">
507 <pre>
508 #include "llvm/DerivedTypes.h"
509 #include "llvm/ExecutionEngine/ExecutionEngine.h"
510 #include "llvm/Module.h"
511 #include "llvm/ModuleProvider.h"
512 #include "llvm/PassManager.h"
513 #include "llvm/Analysis/Verifier.h"
514 #include "llvm/Target/TargetData.h"
515 #include "llvm/Transforms/Scalar.h"
516 #include "llvm/Support/IRBuilder.h"
517 #include &lt;cstdio&gt;
518 #include &lt;string&gt;
519 #include &lt;map&gt;
520 #include &lt;vector&gt;
521 using namespace llvm;
522
523 //===----------------------------------------------------------------------===//
524 // Lexer
525 //===----------------------------------------------------------------------===//
526
527 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
528 // of these for known things.
529 enum Token {
530   tok_eof = -1,
531
532   // commands
533   tok_def = -2, tok_extern = -3,
534
535   // primary
536   tok_identifier = -4, tok_number = -5,
537 };
538
539 static std::string IdentifierStr;  // Filled in if tok_identifier
540 static double NumVal;              // Filled in if tok_number
541
542 /// gettok - Return the next token from standard input.
543 static int gettok() {
544   static int LastChar = ' ';
545
546   // Skip any whitespace.
547   while (isspace(LastChar))
548     LastChar = getchar();
549
550   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
551     IdentifierStr = LastChar;
552     while (isalnum((LastChar = getchar())))
553       IdentifierStr += LastChar;
554
555     if (IdentifierStr == "def") return tok_def;
556     if (IdentifierStr == "extern") return tok_extern;
557     return tok_identifier;
558   }
559
560   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
561     std::string NumStr;
562     do {
563       NumStr += LastChar;
564       LastChar = getchar();
565     } while (isdigit(LastChar) || LastChar == '.');
566
567     NumVal = strtod(NumStr.c_str(), 0);
568     return tok_number;
569   }
570
571   if (LastChar == '#') {
572     // Comment until end of line.
573     do LastChar = getchar();
574     while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
575     
576     if (LastChar != EOF)
577       return gettok();
578   }
579   
580   // Check for end of file.  Don't eat the EOF.
581   if (LastChar == EOF)
582     return tok_eof;
583
584   // Otherwise, just return the character as its ascii value.
585   int ThisChar = LastChar;
586   LastChar = getchar();
587   return ThisChar;
588 }
589
590 //===----------------------------------------------------------------------===//
591 // Abstract Syntax Tree (aka Parse Tree)
592 //===----------------------------------------------------------------------===//
593
594 /// ExprAST - Base class for all expression nodes.
595 class ExprAST {
596 public:
597   virtual ~ExprAST() {}
598   virtual Value *Codegen() = 0;
599 };
600
601 /// NumberExprAST - Expression class for numeric literals like "1.0".
602 class NumberExprAST : public ExprAST {
603   double Val;
604 public:
605   NumberExprAST(double val) : Val(val) {}
606   virtual Value *Codegen();
607 };
608
609 /// VariableExprAST - Expression class for referencing a variable, like "a".
610 class VariableExprAST : public ExprAST {
611   std::string Name;
612 public:
613   VariableExprAST(const std::string &amp;name) : Name(name) {}
614   virtual Value *Codegen();
615 };
616
617 /// BinaryExprAST - Expression class for a binary operator.
618 class BinaryExprAST : public ExprAST {
619   char Op;
620   ExprAST *LHS, *RHS;
621 public:
622   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 
623     : Op(op), LHS(lhs), RHS(rhs) {}
624   virtual Value *Codegen();
625 };
626
627 /// CallExprAST - Expression class for function calls.
628 class CallExprAST : public ExprAST {
629   std::string Callee;
630   std::vector&lt;ExprAST*&gt; Args;
631 public:
632   CallExprAST(const std::string &amp;callee, std::vector&lt;ExprAST*&gt; &amp;args)
633     : Callee(callee), Args(args) {}
634   virtual Value *Codegen();
635 };
636
637 /// PrototypeAST - This class represents the "prototype" for a function,
638 /// which captures its argument names as well as if it is an operator.
639 class PrototypeAST {
640   std::string Name;
641   std::vector&lt;std::string&gt; Args;
642 public:
643   PrototypeAST(const std::string &amp;name, const std::vector&lt;std::string&gt; &amp;args)
644     : Name(name), Args(args) {}
645   
646   Function *Codegen();
647 };
648
649 /// FunctionAST - This class represents a function definition itself.
650 class FunctionAST {
651   PrototypeAST *Proto;
652   ExprAST *Body;
653 public:
654   FunctionAST(PrototypeAST *proto, ExprAST *body)
655     : Proto(proto), Body(body) {}
656   
657   Function *Codegen();
658 };
659
660 //===----------------------------------------------------------------------===//
661 // Parser
662 //===----------------------------------------------------------------------===//
663
664 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
665 /// token the parser it looking at.  getNextToken reads another token from the
666 /// lexer and updates CurTok with its results.
667 static int CurTok;
668 static int getNextToken() {
669   return CurTok = gettok();
670 }
671
672 /// BinopPrecedence - This holds the precedence for each binary operator that is
673 /// defined.
674 static std::map&lt;char, int&gt; BinopPrecedence;
675
676 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
677 static int GetTokPrecedence() {
678   if (!isascii(CurTok))
679     return -1;
680   
681   // Make sure it's a declared binop.
682   int TokPrec = BinopPrecedence[CurTok];
683   if (TokPrec &lt;= 0) return -1;
684   return TokPrec;
685 }
686
687 /// Error* - These are little helper functions for error handling.
688 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
689 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
690 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
691
692 static ExprAST *ParseExpression();
693
694 /// identifierexpr
695 ///   ::= identifier
696 ///   ::= identifier '(' expression* ')'
697 static ExprAST *ParseIdentifierExpr() {
698   std::string IdName = IdentifierStr;
699   
700   getNextToken();  // eat identifier.
701   
702   if (CurTok != '(') // Simple variable ref.
703     return new VariableExprAST(IdName);
704   
705   // Call.
706   getNextToken();  // eat (
707   std::vector&lt;ExprAST*&gt; Args;
708   if (CurTok != ')') {
709     while (1) {
710       ExprAST *Arg = ParseExpression();
711       if (!Arg) return 0;
712       Args.push_back(Arg);
713     
714       if (CurTok == ')') break;
715     
716       if (CurTok != ',')
717         return Error("Expected ')'");
718       getNextToken();
719     }
720   }
721
722   // Eat the ')'.
723   getNextToken();
724   
725   return new CallExprAST(IdName, Args);
726 }
727
728 /// numberexpr ::= number
729 static ExprAST *ParseNumberExpr() {
730   ExprAST *Result = new NumberExprAST(NumVal);
731   getNextToken(); // consume the number
732   return Result;
733 }
734
735 /// parenexpr ::= '(' expression ')'
736 static ExprAST *ParseParenExpr() {
737   getNextToken();  // eat (.
738   ExprAST *V = ParseExpression();
739   if (!V) return 0;
740   
741   if (CurTok != ')')
742     return Error("expected ')'");
743   getNextToken();  // eat ).
744   return V;
745 }
746
747 /// primary
748 ///   ::= identifierexpr
749 ///   ::= numberexpr
750 ///   ::= parenexpr
751 static ExprAST *ParsePrimary() {
752   switch (CurTok) {
753   default: return Error("unknown token when expecting an expression");
754   case tok_identifier: return ParseIdentifierExpr();
755   case tok_number:     return ParseNumberExpr();
756   case '(':            return ParseParenExpr();
757   }
758 }
759
760 /// binoprhs
761 ///   ::= ('+' primary)*
762 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
763   // If this is a binop, find its precedence.
764   while (1) {
765     int TokPrec = GetTokPrecedence();
766     
767     // If this is a binop that binds at least as tightly as the current binop,
768     // consume it, otherwise we are done.
769     if (TokPrec &lt; ExprPrec)
770       return LHS;
771     
772     // Okay, we know this is a binop.
773     int BinOp = CurTok;
774     getNextToken();  // eat binop
775     
776     // Parse the primary expression after the binary operator.
777     ExprAST *RHS = ParsePrimary();
778     if (!RHS) return 0;
779     
780     // If BinOp binds less tightly with RHS than the operator after RHS, let
781     // the pending operator take RHS as its LHS.
782     int NextPrec = GetTokPrecedence();
783     if (TokPrec &lt; NextPrec) {
784       RHS = ParseBinOpRHS(TokPrec+1, RHS);
785       if (RHS == 0) return 0;
786     }
787     
788     // Merge LHS/RHS.
789     LHS = new BinaryExprAST(BinOp, LHS, RHS);
790   }
791 }
792
793 /// expression
794 ///   ::= primary binoprhs
795 ///
796 static ExprAST *ParseExpression() {
797   ExprAST *LHS = ParsePrimary();
798   if (!LHS) return 0;
799   
800   return ParseBinOpRHS(0, LHS);
801 }
802
803 /// prototype
804 ///   ::= id '(' id* ')'
805 static PrototypeAST *ParsePrototype() {
806   if (CurTok != tok_identifier)
807     return ErrorP("Expected function name in prototype");
808
809   std::string FnName = IdentifierStr;
810   getNextToken();
811   
812   if (CurTok != '(')
813     return ErrorP("Expected '(' in prototype");
814   
815   std::vector&lt;std::string&gt; ArgNames;
816   while (getNextToken() == tok_identifier)
817     ArgNames.push_back(IdentifierStr);
818   if (CurTok != ')')
819     return ErrorP("Expected ')' in prototype");
820   
821   // success.
822   getNextToken();  // eat ')'.
823   
824   return new PrototypeAST(FnName, ArgNames);
825 }
826
827 /// definition ::= 'def' prototype expression
828 static FunctionAST *ParseDefinition() {
829   getNextToken();  // eat def.
830   PrototypeAST *Proto = ParsePrototype();
831   if (Proto == 0) return 0;
832
833   if (ExprAST *E = ParseExpression())
834     return new FunctionAST(Proto, E);
835   return 0;
836 }
837
838 /// toplevelexpr ::= expression
839 static FunctionAST *ParseTopLevelExpr() {
840   if (ExprAST *E = ParseExpression()) {
841     // Make an anonymous proto.
842     PrototypeAST *Proto = new PrototypeAST("", std::vector&lt;std::string&gt;());
843     return new FunctionAST(Proto, E);
844   }
845   return 0;
846 }
847
848 /// external ::= 'extern' prototype
849 static PrototypeAST *ParseExtern() {
850   getNextToken();  // eat extern.
851   return ParsePrototype();
852 }
853
854 //===----------------------------------------------------------------------===//
855 // Code Generation
856 //===----------------------------------------------------------------------===//
857
858 static Module *TheModule;
859 static IRBuilder Builder;
860 static std::map&lt;std::string, Value*&gt; NamedValues;
861 static FunctionPassManager *TheFPM;
862
863 Value *ErrorV(const char *Str) { Error(Str); return 0; }
864
865 Value *NumberExprAST::Codegen() {
866   return ConstantFP::get(Type::DoubleTy, APFloat(Val));
867 }
868
869 Value *VariableExprAST::Codegen() {
870   // Look this variable up in the function.
871   Value *V = NamedValues[Name];
872   return V ? V : ErrorV("Unknown variable name");
873 }
874
875 Value *BinaryExprAST::Codegen() {
876   Value *L = LHS-&gt;Codegen();
877   Value *R = RHS-&gt;Codegen();
878   if (L == 0 || R == 0) return 0;
879   
880   switch (Op) {
881   case '+': return Builder.CreateAdd(L, R, "addtmp");
882   case '-': return Builder.CreateSub(L, R, "subtmp");
883   case '*': return Builder.CreateMul(L, R, "multmp");
884   case '&lt;':
885     L = Builder.CreateFCmpULT(L, R, "cmptmp");
886     // Convert bool 0/1 to double 0.0 or 1.0
887     return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
888   default: return ErrorV("invalid binary operator");
889   }
890 }
891
892 Value *CallExprAST::Codegen() {
893   // Look up the name in the global module table.
894   Function *CalleeF = TheModule-&gt;getFunction(Callee);
895   if (CalleeF == 0)
896     return ErrorV("Unknown function referenced");
897   
898   // If argument mismatch error.
899   if (CalleeF-&gt;arg_size() != Args.size())
900     return ErrorV("Incorrect # arguments passed");
901
902   std::vector&lt;Value*&gt; ArgsV;
903   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
904     ArgsV.push_back(Args[i]-&gt;Codegen());
905     if (ArgsV.back() == 0) return 0;
906   }
907   
908   return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
909 }
910
911 Function *PrototypeAST::Codegen() {
912   // Make the function type:  double(double,double) etc.
913   std::vector&lt;const Type*&gt; Doubles(Args.size(), Type::DoubleTy);
914   FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
915   
916   Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
917   
918   // If F conflicted, there was already something named 'Name'.  If it has a
919   // body, don't allow redefinition or reextern.
920   if (F-&gt;getName() != Name) {
921     // Delete the one we just made and get the existing one.
922     F-&gt;eraseFromParent();
923     F = TheModule-&gt;getFunction(Name);
924     
925     // If F already has a body, reject this.
926     if (!F-&gt;empty()) {
927       ErrorF("redefinition of function");
928       return 0;
929     }
930     
931     // If F took a different number of args, reject.
932     if (F-&gt;arg_size() != Args.size()) {
933       ErrorF("redefinition of function with different # args");
934       return 0;
935     }
936   }
937   
938   // Set names for all arguments.
939   unsigned Idx = 0;
940   for (Function::arg_iterator AI = F-&gt;arg_begin(); Idx != Args.size();
941        ++AI, ++Idx) {
942     AI-&gt;setName(Args[Idx]);
943     
944     // Add arguments to variable symbol table.
945     NamedValues[Args[Idx]] = AI;
946   }
947   
948   return F;
949 }
950
951 Function *FunctionAST::Codegen() {
952   NamedValues.clear();
953   
954   Function *TheFunction = Proto-&gt;Codegen();
955   if (TheFunction == 0)
956     return 0;
957   
958   // Create a new basic block to start insertion into.
959   BasicBlock *BB = new BasicBlock("entry", TheFunction);
960   Builder.SetInsertPoint(BB);
961   
962   if (Value *RetVal = Body-&gt;Codegen()) {
963     // Finish off the function.
964     Builder.CreateRet(RetVal);
965
966     // Validate the generated code, checking for consistency.
967     verifyFunction(*TheFunction);
968
969     // Optimize the function.
970     TheFPM-&gt;run(*TheFunction);
971     
972     return TheFunction;
973   }
974   
975   // Error reading body, remove function.
976   TheFunction-&gt;eraseFromParent();
977   return 0;
978 }
979
980 //===----------------------------------------------------------------------===//
981 // Top-Level parsing and JIT Driver
982 //===----------------------------------------------------------------------===//
983
984 static ExecutionEngine *TheExecutionEngine;
985
986 static void HandleDefinition() {
987   if (FunctionAST *F = ParseDefinition()) {
988     if (Function *LF = F-&gt;Codegen()) {
989       fprintf(stderr, "Read function definition:");
990       LF-&gt;dump();
991     }
992   } else {
993     // Skip token for error recovery.
994     getNextToken();
995   }
996 }
997
998 static void HandleExtern() {
999   if (PrototypeAST *P = ParseExtern()) {
1000     if (Function *F = P-&gt;Codegen()) {
1001       fprintf(stderr, "Read extern: ");
1002       F-&gt;dump();
1003     }
1004   } else {
1005     // Skip token for error recovery.
1006     getNextToken();
1007   }
1008 }
1009
1010 static void HandleTopLevelExpression() {
1011   // Evaluate a top level expression into an anonymous function.
1012   if (FunctionAST *F = ParseTopLevelExpr()) {
1013     if (Function *LF = F-&gt;Codegen()) {
1014       // JIT the function, returning a function pointer.
1015       void *FPtr = TheExecutionEngine-&gt;getPointerToFunction(LF);
1016       
1017       // Cast it to the right type (takes no arguments, returns a double) so we
1018       // can call it as a native function.
1019       double (*FP)() = (double (*)())FPtr;
1020       fprintf(stderr, "Evaluated to %f\n", FP());
1021     }
1022   } else {
1023     // Skip token for error recovery.
1024     getNextToken();
1025   }
1026 }
1027
1028 /// top ::= definition | external | expression | ';'
1029 static void MainLoop() {
1030   while (1) {
1031     fprintf(stderr, "ready&gt; ");
1032     switch (CurTok) {
1033     case tok_eof:    return;
1034     case ';':        getNextToken(); break;  // ignore top level semicolons.
1035     case tok_def:    HandleDefinition(); break;
1036     case tok_extern: HandleExtern(); break;
1037     default:         HandleTopLevelExpression(); break;
1038     }
1039   }
1040 }
1041
1042
1043
1044 //===----------------------------------------------------------------------===//
1045 // "Library" functions that can be "extern'd" from user code.
1046 //===----------------------------------------------------------------------===//
1047
1048 /// putchard - putchar that takes a double and returns 0.
1049 extern "C" 
1050 double putchard(double X) {
1051   putchar((char)X);
1052   return 0;
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 // Main driver code.
1057 //===----------------------------------------------------------------------===//
1058
1059 int main() {
1060   // Install standard binary operators.
1061   // 1 is lowest precedence.
1062   BinopPrecedence['&lt;'] = 10;
1063   BinopPrecedence['+'] = 20;
1064   BinopPrecedence['-'] = 20;
1065   BinopPrecedence['*'] = 40;  // highest.
1066
1067   // Prime the first token.
1068   fprintf(stderr, "ready&gt; ");
1069   getNextToken();
1070
1071   // Make the module, which holds all the code.
1072   TheModule = new Module("my cool jit");
1073   
1074   // Create the JIT.
1075   TheExecutionEngine = ExecutionEngine::create(TheModule);
1076
1077   {
1078     ExistingModuleProvider OurModuleProvider(TheModule);
1079     FunctionPassManager OurFPM(&amp;OurModuleProvider);
1080       
1081     // Set up the optimizer pipeline.  Start with registering info about how the
1082     // target lays out data structures.
1083     OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
1084     // Do simple "peephole" optimizations and bit-twiddling optzns.
1085     OurFPM.add(createInstructionCombiningPass());
1086     // Reassociate expressions.
1087     OurFPM.add(createReassociatePass());
1088     // Eliminate Common SubExpressions.
1089     OurFPM.add(createGVNPass());
1090     // Simplify the control flow graph (deleting unreachable blocks, etc).
1091     OurFPM.add(createCFGSimplificationPass());
1092
1093     // Set the global so the code gen can use this.
1094     TheFPM = &amp;OurFPM;
1095
1096     // Run the main "interpreter loop" now.
1097     MainLoop();
1098     
1099     TheFPM = 0;
1100     
1101     // Print out all of the generated code.
1102     TheModule-&gt;dump();
1103   }  // Free module provider (and thus the module) and pass manager.
1104                                    
1105   return 0;
1106 }
1107 </pre>
1108 </div>
1109
1110 <a href="LangImpl5.html">Next: Extending the language: control flow</a>
1111 </div>
1112
1113 <!-- *********************************************************************** -->
1114 <hr>
1115 <address>
1116   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1117   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1118   <a href="http://validator.w3.org/check/referer"><img
1119   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1120
1121   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1122   <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1123   Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
1124 </address>
1125 </body>
1126 </html>