1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
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">
14 <div class="doc_title">Kaleidoscope: Adding JIT and Optimizer Support</div>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
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>
27 <li><a href="LangImpl5.html">Chapter 5</a>: Extending the Language: Control
31 <div class="doc_author">
32 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
35 <!-- *********************************************************************** -->
36 <div class="doc_section"><a name="intro">Chapter 4 Introduction</a></div>
37 <!-- *********************************************************************** -->
39 <div class="doc_text">
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>
50 <!-- *********************************************************************** -->
51 <div class="doc_section"><a name="trivialconstfold">Trivial Constant
53 <!-- *********************************************************************** -->
55 <div class="doc_text">
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>
62 <div class="doc_code">
64 ready> <b>def test(x) 1+2+x;</b>
65 Read function definition:
66 define double @test(double %x) {
68 %addtmp = fadd double 3.000000e+00, %x
74 <p>This code is not a literal transcription of the AST built by parsing the
77 <div class="doc_code">
79 ready> <b>def test(x) 1+2+x;</b>
80 Read function definition:
81 define double @test(double %x) {
83 %addtmp = fadd double 2.000000e+00, 1.000000e+00
84 %addtmp1 = fadd double %addtmp, %x
90 <p>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>
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.
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>
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>
110 <div class="doc_code">
112 ready> <b>def test(x) (1+2+x)*(x+(1+2));</b>
113 ready> Read function definition:
114 define double @test(double %x) {
116 %addtmp = fadd double 3.000000e+00, %x
117 %addtmp1 = fadd double %x, 3.000000e+00
118 %multmp = fmul double %addtmp, %addtmp1
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>
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>
136 <!-- *********************************************************************** -->
137 <div class="doc_section"><a name="optimizerpasses">LLVM Optimization
139 <!-- *********************************************************************** -->
141 <div class="doc_text">
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
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
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>
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>
172 <div class="doc_code">
174 FunctionPassManager OurFPM(TheModule);
176 // Set up the optimizer pipeline. Start with registering info about how the
177 // target lays out data structures.
178 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
179 // Provide basic AliasAnalysis support for GVN.
180 OurFPM.add(createBasicAliasAnalysisPass());
181 // Do simple "peephole" optimizations and bit-twiddling optzns.
182 OurFPM.add(createInstructionCombiningPass());
183 // Reassociate expressions.
184 OurFPM.add(createReassociatePass());
185 // Eliminate Common SubExpressions.
186 OurFPM.add(createGVNPass());
187 // Simplify the control flow graph (deleting unreachable blocks, etc).
188 OurFPM.add(createCFGSimplificationPass());
190 OurFPM.doInitialization();
192 // Set the global so the code gen can use this.
193 TheFPM = &OurFPM;
195 // Run the main "interpreter loop" now.
200 <p>This code defines a <tt>FunctionPassManager</tt>, "<tt>OurFPM</tt>". It
201 requires a pointer to the <tt>Module</tt> to construct itself. Once it is set
202 up, we use a series of "add" calls to add a bunch of LLVM passes. The first
203 pass is basically boilerplate, it adds a pass so that later optimizations know
204 how the data structures in the program are laid out. The
205 "<tt>TheExecutionEngine</tt>" variable is related to the JIT, which we will get
206 to in the next section.</p>
208 <p>In this case, we choose to add 4 optimization passes. The passes we chose
209 here are a pretty standard set of "cleanup" optimizations that are useful for
210 a wide variety of code. I won't delve into what they do but, believe me,
211 they are a good starting place :).</p>
213 <p>Once the PassManager is set up, we need to make use of it. We do this by
214 running it after our newly created function is constructed (in
215 <tt>FunctionAST::Codegen</tt>), but before it is returned to the client:</p>
217 <div class="doc_code">
219 if (Value *RetVal = Body->Codegen()) {
220 // Finish off the function.
221 Builder.CreateRet(RetVal);
223 // Validate the generated code, checking for consistency.
224 verifyFunction(*TheFunction);
226 <b>// Optimize the function.
227 TheFPM->run(*TheFunction);</b>
234 <p>As you can see, this is pretty straightforward. The
235 <tt>FunctionPassManager</tt> optimizes and updates the LLVM Function* in place,
236 improving (hopefully) its body. With this in place, we can try our test above
239 <div class="doc_code">
241 ready> <b>def test(x) (1+2+x)*(x+(1+2));</b>
242 ready> Read function definition:
243 define double @test(double %x) {
245 %addtmp = fadd double %x, 3.000000e+00
246 %multmp = fmul double %addtmp, %addtmp
252 <p>As expected, we now get our nicely optimized code, saving a floating point
253 add instruction from every execution of this function.</p>
255 <p>LLVM provides a wide variety of optimizations that can be used in certain
256 circumstances. Some <a href="../Passes.html">documentation about the various
257 passes</a> is available, but it isn't very complete. Another good source of
258 ideas can come from looking at the passes that <tt>llvm-gcc</tt> or
259 <tt>llvm-ld</tt> run to get started. The "<tt>opt</tt>" tool allows you to
260 experiment with passes from the command line, so you can see if they do
263 <p>Now that we have reasonable code coming out of our front-end, lets talk about
268 <!-- *********************************************************************** -->
269 <div class="doc_section"><a name="jit">Adding a JIT Compiler</a></div>
270 <!-- *********************************************************************** -->
272 <div class="doc_text">
274 <p>Code that is available in LLVM IR can have a wide variety of tools
275 applied to it. For example, you can run optimizations on it (as we did above),
276 you can dump it out in textual or binary forms, you can compile the code to an
277 assembly file (.s) for some target, or you can JIT compile it. The nice thing
278 about the LLVM IR representation is that it is the "common currency" between
279 many different parts of the compiler.
282 <p>In this section, we'll add JIT compiler support to our interpreter. The
283 basic idea that we want for Kaleidoscope is to have the user enter function
284 bodies as they do now, but immediately evaluate the top-level expressions they
285 type in. For example, if they type in "1 + 2;", we should evaluate and print
286 out 3. If they define a function, they should be able to call it from the
289 <p>In order to do this, we first declare and initialize the JIT. This is done
290 by adding a global variable and a call in <tt>main</tt>:</p>
292 <div class="doc_code">
294 <b>static ExecutionEngine *TheExecutionEngine;</b>
298 <b>// Create the JIT. This takes ownership of the module.
299 TheExecutionEngine = EngineBuilder(TheModule).create();</b>
305 <p>This creates an abstract "Execution Engine" which can be either a JIT
306 compiler or the LLVM interpreter. LLVM will automatically pick a JIT compiler
307 for you if one is available for your platform, otherwise it will fall back to
310 <p>Once the <tt>ExecutionEngine</tt> is created, the JIT is ready to be used.
311 There are a variety of APIs that are useful, but the simplest one is the
312 "<tt>getPointerToFunction(F)</tt>" method. This method JIT compiles the
313 specified LLVM Function and returns a function pointer to the generated machine
314 code. In our case, this means that we can change the code that parses a
315 top-level expression to look like this:</p>
317 <div class="doc_code">
319 static void HandleTopLevelExpression() {
320 // Evaluate a top-level expression into an anonymous function.
321 if (FunctionAST *F = ParseTopLevelExpr()) {
322 if (Function *LF = F->Codegen()) {
323 LF->dump(); // Dump the function for exposition purposes.
325 <b>// JIT the function, returning a function pointer.
326 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
328 // Cast it to the right type (takes no arguments, returns a double) so we
329 // can call it as a native function.
330 double (*FP)() = (double (*)())(intptr_t)FPtr;
331 fprintf(stderr, "Evaluated to %f\n", FP());</b>
336 <p>Recall that we compile top-level expressions into a self-contained LLVM
337 function that takes no arguments and returns the computed double. Because the
338 LLVM JIT compiler matches the native platform ABI, this means that you can just
339 cast the result pointer to a function pointer of that type and call it directly.
340 This means, there is no difference between JIT compiled code and native machine
341 code that is statically linked into your application.</p>
343 <p>With just these two changes, lets see how Kaleidoscope works now!</p>
345 <div class="doc_code">
347 ready> <b>4+5;</b>
348 define double @""() {
350 ret double 9.000000e+00
353 <em>Evaluated to 9.000000</em>
357 <p>Well this looks like it is basically working. The dump of the function
358 shows the "no argument function that always returns double" that we synthesize
359 for each top-level expression that is typed in. This demonstrates very basic
360 functionality, but can we do more?</p>
362 <div class="doc_code">
364 ready> <b>def testfunc(x y) x + y*2; </b>
365 Read function definition:
366 define double @testfunc(double %x, double %y) {
368 %multmp = fmul double %y, 2.000000e+00
369 %addtmp = fadd double %multmp, %x
373 ready> <b>testfunc(4, 10);</b>
374 define double @""() {
376 %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
380 <em>Evaluated to 24.000000</em>
384 <p>This illustrates that we can now call user code, but there is something a bit
385 subtle going on here. Note that we only invoke the JIT on the anonymous
386 functions that <em>call testfunc</em>, but we never invoked it
387 on <em>testfunc</em> itself. What actually happened here is that the JIT
388 scanned for all non-JIT'd functions transitively called from the anonymous
389 function and compiled all of them before returning
390 from <tt>getPointerToFunction()</tt>.</p>
392 <p>The JIT provides a number of other more advanced interfaces for things like
393 freeing allocated machine code, rejit'ing functions to update them, etc.
394 However, even with this simple code, we get some surprisingly powerful
395 capabilities - check this out (I removed the dump of the anonymous functions,
396 you should get the idea by now :) :</p>
398 <div class="doc_code">
400 ready> <b>extern sin(x);</b>
402 declare double @sin(double)
404 ready> <b>extern cos(x);</b>
406 declare double @cos(double)
408 ready> <b>sin(1.0);</b>
409 <em>Evaluated to 0.841471</em>
411 ready> <b>def foo(x) sin(x)*sin(x) + cos(x)*cos(x);</b>
412 Read function definition:
413 define double @foo(double %x) {
415 %calltmp = call double @sin(double %x)
416 %multmp = fmul double %calltmp, %calltmp
417 %calltmp2 = call double @cos(double %x)
418 %multmp4 = fmul double %calltmp2, %calltmp2
419 %addtmp = fadd double %multmp, %multmp4
423 ready> <b>foo(4.0);</b>
424 <em>Evaluated to 1.000000</em>
428 <p>Whoa, how does the JIT know about sin and cos? The answer is surprisingly
430 example, the JIT started execution of a function and got to a function call. It
431 realized that the function was not yet JIT compiled and invoked the standard set
432 of routines to resolve the function. In this case, there is no body defined
433 for the function, so the JIT ended up calling "<tt>dlsym("sin")</tt>" on the
434 Kaleidoscope process itself.
435 Since "<tt>sin</tt>" is defined within the JIT's address space, it simply
436 patches up calls in the module to call the libm version of <tt>sin</tt>
439 <p>The LLVM JIT provides a number of interfaces (look in the
440 <tt>ExecutionEngine.h</tt> file) for controlling how unknown functions get
441 resolved. It allows you to establish explicit mappings between IR objects and
442 addresses (useful for LLVM global variables that you want to map to static
443 tables, for example), allows you to dynamically decide on the fly based on the
444 function name, and even allows you to have the JIT compile functions lazily the
445 first time they're called.</p>
447 <p>One interesting application of this is that we can now extend the language
448 by writing arbitrary C++ code to implement operations. For example, if we add:
451 <div class="doc_code">
453 /// putchard - putchar that takes a double and returns 0.
455 double putchard(double X) {
462 <p>Now we can produce simple output to the console by using things like:
463 "<tt>extern putchard(x); putchard(120);</tt>", which prints a lowercase 'x' on
464 the console (120 is the ASCII code for 'x'). Similar code could be used to
465 implement file I/O, console input, and many other capabilities in
468 <p>This completes the JIT and optimizer chapter of the Kaleidoscope tutorial. At
469 this point, we can compile a non-Turing-complete programming language, optimize
470 and JIT compile it in a user-driven way. Next up we'll look into <a
471 href="LangImpl5.html">extending the language with control flow constructs</a>,
472 tackling some interesting LLVM IR issues along the way.</p>
476 <!-- *********************************************************************** -->
477 <div class="doc_section"><a name="code">Full Code Listing</a></div>
478 <!-- *********************************************************************** -->
480 <div class="doc_text">
483 Here is the complete code listing for our running example, enhanced with the
484 LLVM JIT and optimizer. To build this example, use:
487 <div class="doc_code">
490 g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
497 If you are compiling this on Linux, make sure to add the "-rdynamic" option
498 as well. This makes sure that the external functions are resolved properly
501 <p>Here is the code:</p>
503 <div class="doc_code">
505 #include "llvm/DerivedTypes.h"
506 #include "llvm/ExecutionEngine/ExecutionEngine.h"
507 #include "llvm/ExecutionEngine/JIT.h"
508 #include "llvm/LLVMContext.h"
509 #include "llvm/Module.h"
510 #include "llvm/PassManager.h"
511 #include "llvm/Analysis/Verifier.h"
512 #include "llvm/Target/TargetData.h"
513 #include "llvm/Target/TargetSelect.h"
514 #include "llvm/Transforms/Scalar.h"
515 #include "llvm/Support/IRBuilder.h"
516 #include <cstdio>
517 #include <string>
519 #include <vector>
520 using namespace llvm;
522 //===----------------------------------------------------------------------===//
524 //===----------------------------------------------------------------------===//
526 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
527 // of these for known things.
532 tok_def = -2, tok_extern = -3,
535 tok_identifier = -4, tok_number = -5
538 static std::string IdentifierStr; // Filled in if tok_identifier
539 static double NumVal; // Filled in if tok_number
541 /// gettok - Return the next token from standard input.
542 static int gettok() {
543 static int LastChar = ' ';
545 // Skip any whitespace.
546 while (isspace(LastChar))
547 LastChar = getchar();
549 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
550 IdentifierStr = LastChar;
551 while (isalnum((LastChar = getchar())))
552 IdentifierStr += LastChar;
554 if (IdentifierStr == "def") return tok_def;
555 if (IdentifierStr == "extern") return tok_extern;
556 return tok_identifier;
559 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
563 LastChar = getchar();
564 } while (isdigit(LastChar) || LastChar == '.');
566 NumVal = strtod(NumStr.c_str(), 0);
570 if (LastChar == '#') {
571 // Comment until end of line.
572 do LastChar = getchar();
573 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
579 // Check for end of file. Don't eat the EOF.
583 // Otherwise, just return the character as its ascii value.
584 int ThisChar = LastChar;
585 LastChar = getchar();
589 //===----------------------------------------------------------------------===//
590 // Abstract Syntax Tree (aka Parse Tree)
591 //===----------------------------------------------------------------------===//
593 /// ExprAST - Base class for all expression nodes.
596 virtual ~ExprAST() {}
597 virtual Value *Codegen() = 0;
600 /// NumberExprAST - Expression class for numeric literals like "1.0".
601 class NumberExprAST : public ExprAST {
604 NumberExprAST(double val) : Val(val) {}
605 virtual Value *Codegen();
608 /// VariableExprAST - Expression class for referencing a variable, like "a".
609 class VariableExprAST : public ExprAST {
612 VariableExprAST(const std::string &name) : Name(name) {}
613 virtual Value *Codegen();
616 /// BinaryExprAST - Expression class for a binary operator.
617 class BinaryExprAST : public ExprAST {
621 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
622 : Op(op), LHS(lhs), RHS(rhs) {}
623 virtual Value *Codegen();
626 /// CallExprAST - Expression class for function calls.
627 class CallExprAST : public ExprAST {
629 std::vector<ExprAST*> Args;
631 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
632 : Callee(callee), Args(args) {}
633 virtual Value *Codegen();
636 /// PrototypeAST - This class represents the "prototype" for a function,
637 /// which captures its name, and its argument names (thus implicitly the number
638 /// of arguments the function takes).
641 std::vector<std::string> Args;
643 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
644 : Name(name), Args(args) {}
649 /// FunctionAST - This class represents a function definition itself.
654 FunctionAST(PrototypeAST *proto, ExprAST *body)
655 : Proto(proto), Body(body) {}
660 //===----------------------------------------------------------------------===//
662 //===----------------------------------------------------------------------===//
664 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
665 /// token the parser is looking at. getNextToken reads another token from the
666 /// lexer and updates CurTok with its results.
668 static int getNextToken() {
669 return CurTok = gettok();
672 /// BinopPrecedence - This holds the precedence for each binary operator that is
674 static std::map<char, int> BinopPrecedence;
676 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
677 static int GetTokPrecedence() {
678 if (!isascii(CurTok))
681 // Make sure it's a declared binop.
682 int TokPrec = BinopPrecedence[CurTok];
683 if (TokPrec <= 0) return -1;
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; }
692 static ExprAST *ParseExpression();
696 /// ::= identifier '(' expression* ')'
697 static ExprAST *ParseIdentifierExpr() {
698 std::string IdName = IdentifierStr;
700 getNextToken(); // eat identifier.
702 if (CurTok != '(') // Simple variable ref.
703 return new VariableExprAST(IdName);
706 getNextToken(); // eat (
707 std::vector<ExprAST*> Args;
710 ExprAST *Arg = ParseExpression();
714 if (CurTok == ')') break;
717 return Error("Expected ')' or ',' in argument list");
725 return new CallExprAST(IdName, Args);
728 /// numberexpr ::= number
729 static ExprAST *ParseNumberExpr() {
730 ExprAST *Result = new NumberExprAST(NumVal);
731 getNextToken(); // consume the number
735 /// parenexpr ::= '(' expression ')'
736 static ExprAST *ParseParenExpr() {
737 getNextToken(); // eat (.
738 ExprAST *V = ParseExpression();
742 return Error("expected ')'");
743 getNextToken(); // eat ).
748 /// ::= identifierexpr
751 static ExprAST *ParsePrimary() {
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();
761 /// ::= ('+' primary)*
762 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
763 // If this is a binop, find its precedence.
765 int TokPrec = GetTokPrecedence();
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 < ExprPrec)
772 // Okay, we know this is a binop.
774 getNextToken(); // eat binop
776 // Parse the primary expression after the binary operator.
777 ExprAST *RHS = ParsePrimary();
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 < NextPrec) {
784 RHS = ParseBinOpRHS(TokPrec+1, RHS);
785 if (RHS == 0) return 0;
789 LHS = new BinaryExprAST(BinOp, LHS, RHS);
794 /// ::= primary binoprhs
796 static ExprAST *ParseExpression() {
797 ExprAST *LHS = ParsePrimary();
800 return ParseBinOpRHS(0, LHS);
804 /// ::= id '(' id* ')'
805 static PrototypeAST *ParsePrototype() {
806 if (CurTok != tok_identifier)
807 return ErrorP("Expected function name in prototype");
809 std::string FnName = IdentifierStr;
813 return ErrorP("Expected '(' in prototype");
815 std::vector<std::string> ArgNames;
816 while (getNextToken() == tok_identifier)
817 ArgNames.push_back(IdentifierStr);
819 return ErrorP("Expected ')' in prototype");
822 getNextToken(); // eat ')'.
824 return new PrototypeAST(FnName, ArgNames);
827 /// definition ::= 'def' prototype expression
828 static FunctionAST *ParseDefinition() {
829 getNextToken(); // eat def.
830 PrototypeAST *Proto = ParsePrototype();
831 if (Proto == 0) return 0;
833 if (ExprAST *E = ParseExpression())
834 return new FunctionAST(Proto, E);
838 /// toplevelexpr ::= expression
839 static FunctionAST *ParseTopLevelExpr() {
840 if (ExprAST *E = ParseExpression()) {
841 // Make an anonymous proto.
842 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
843 return new FunctionAST(Proto, E);
848 /// external ::= 'extern' prototype
849 static PrototypeAST *ParseExtern() {
850 getNextToken(); // eat extern.
851 return ParsePrototype();
854 //===----------------------------------------------------------------------===//
856 //===----------------------------------------------------------------------===//
858 static Module *TheModule;
859 static IRBuilder<> Builder(getGlobalContext());
860 static std::map<std::string, Value*> NamedValues;
861 static FunctionPassManager *TheFPM;
863 Value *ErrorV(const char *Str) { Error(Str); return 0; }
865 Value *NumberExprAST::Codegen() {
866 return ConstantFP::get(getGlobalContext(), APFloat(Val));
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");
875 Value *BinaryExprAST::Codegen() {
876 Value *L = LHS->Codegen();
877 Value *R = RHS->Codegen();
878 if (L == 0 || R == 0) return 0;
881 case '+': return Builder.CreateFAdd(L, R, "addtmp");
882 case '-': return Builder.CreateFSub(L, R, "subtmp");
883 case '*': return Builder.CreateFMul(L, R, "multmp");
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::getDoubleTy(getGlobalContext()),
889 default: return ErrorV("invalid binary operator");
893 Value *CallExprAST::Codegen() {
894 // Look up the name in the global module table.
895 Function *CalleeF = TheModule->getFunction(Callee);
897 return ErrorV("Unknown function referenced");
899 // If argument mismatch error.
900 if (CalleeF->arg_size() != Args.size())
901 return ErrorV("Incorrect # arguments passed");
903 std::vector<Value*> ArgsV;
904 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
905 ArgsV.push_back(Args[i]->Codegen());
906 if (ArgsV.back() == 0) return 0;
909 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
912 Function *PrototypeAST::Codegen() {
913 // Make the function type: double(double,double) etc.
914 std::vector<const Type*> Doubles(Args.size(),
915 Type::getDoubleTy(getGlobalContext()));
916 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
919 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
921 // If F conflicted, there was already something named 'Name'. If it has a
922 // body, don't allow redefinition or reextern.
923 if (F->getName() != Name) {
924 // Delete the one we just made and get the existing one.
925 F->eraseFromParent();
926 F = TheModule->getFunction(Name);
928 // If F already has a body, reject this.
929 if (!F->empty()) {
930 ErrorF("redefinition of function");
934 // If F took a different number of args, reject.
935 if (F->arg_size() != Args.size()) {
936 ErrorF("redefinition of function with different # args");
941 // Set names for all arguments.
943 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
945 AI->setName(Args[Idx]);
947 // Add arguments to variable symbol table.
948 NamedValues[Args[Idx]] = AI;
954 Function *FunctionAST::Codegen() {
957 Function *TheFunction = Proto->Codegen();
958 if (TheFunction == 0)
961 // Create a new basic block to start insertion into.
962 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
963 Builder.SetInsertPoint(BB);
965 if (Value *RetVal = Body->Codegen()) {
966 // Finish off the function.
967 Builder.CreateRet(RetVal);
969 // Validate the generated code, checking for consistency.
970 verifyFunction(*TheFunction);
972 // Optimize the function.
973 TheFPM->run(*TheFunction);
978 // Error reading body, remove function.
979 TheFunction->eraseFromParent();
983 //===----------------------------------------------------------------------===//
984 // Top-Level parsing and JIT Driver
985 //===----------------------------------------------------------------------===//
987 static ExecutionEngine *TheExecutionEngine;
989 static void HandleDefinition() {
990 if (FunctionAST *F = ParseDefinition()) {
991 if (Function *LF = F->Codegen()) {
992 fprintf(stderr, "Read function definition:");
996 // Skip token for error recovery.
1001 static void HandleExtern() {
1002 if (PrototypeAST *P = ParseExtern()) {
1003 if (Function *F = P->Codegen()) {
1004 fprintf(stderr, "Read extern: ");
1008 // Skip token for error recovery.
1013 static void HandleTopLevelExpression() {
1014 // Evaluate a top-level expression into an anonymous function.
1015 if (FunctionAST *F = ParseTopLevelExpr()) {
1016 if (Function *LF = F->Codegen()) {
1017 // JIT the function, returning a function pointer.
1018 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1020 // Cast it to the right type (takes no arguments, returns a double) so we
1021 // can call it as a native function.
1022 double (*FP)() = (double (*)())(intptr_t)FPtr;
1023 fprintf(stderr, "Evaluated to %f\n", FP());
1026 // Skip token for error recovery.
1031 /// top ::= definition | external | expression | ';'
1032 static void MainLoop() {
1034 fprintf(stderr, "ready> ");
1036 case tok_eof: return;
1037 case ';': getNextToken(); break; // ignore top-level semicolons.
1038 case tok_def: HandleDefinition(); break;
1039 case tok_extern: HandleExtern(); break;
1040 default: HandleTopLevelExpression(); break;
1045 //===----------------------------------------------------------------------===//
1046 // "Library" functions that can be "extern'd" from user code.
1047 //===----------------------------------------------------------------------===//
1049 /// putchard - putchar that takes a double and returns 0.
1051 double putchard(double X) {
1056 //===----------------------------------------------------------------------===//
1057 // Main driver code.
1058 //===----------------------------------------------------------------------===//
1061 InitializeNativeTarget();
1062 LLVMContext &Context = getGlobalContext();
1064 // Install standard binary operators.
1065 // 1 is lowest precedence.
1066 BinopPrecedence['<'] = 10;
1067 BinopPrecedence['+'] = 20;
1068 BinopPrecedence['-'] = 20;
1069 BinopPrecedence['*'] = 40; // highest.
1071 // Prime the first token.
1072 fprintf(stderr, "ready> ");
1075 // Make the module, which holds all the code.
1076 TheModule = new Module("my cool jit", Context);
1078 // Create the JIT. This takes ownership of the module.
1080 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
1081 if (!TheExecutionEngine) {
1082 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1086 FunctionPassManager OurFPM(TheModule);
1088 // Set up the optimizer pipeline. Start with registering info about how the
1089 // target lays out data structures.
1090 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
1091 // Provide basic AliasAnalysis support for GVN.
1092 OurFPM.add(createBasicAliasAnalysisPass());
1093 // Do simple "peephole" optimizations and bit-twiddling optzns.
1094 OurFPM.add(createInstructionCombiningPass());
1095 // Reassociate expressions.
1096 OurFPM.add(createReassociatePass());
1097 // Eliminate Common SubExpressions.
1098 OurFPM.add(createGVNPass());
1099 // Simplify the control flow graph (deleting unreachable blocks, etc).
1100 OurFPM.add(createCFGSimplificationPass());
1102 OurFPM.doInitialization();
1104 // Set the global so the code gen can use this.
1105 TheFPM = &OurFPM;
1107 // Run the main "interpreter loop" now.
1112 // Print out all of the generated code.
1113 TheModule->dump();
1120 <a href="LangImpl5.html">Next: Extending the language: control flow</a>
1123 <!-- *********************************************************************** -->
1126 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1127 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1128 <a href="http://validator.w3.org/check/referer"><img
1129 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1131 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1132 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1133 Last modified: $Date$