1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
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">
14 <div class="doc_title">Kaleidoscope: Code generation to LLVM IR</div>
17 <li><a href="index.html">Up to Tutorial Index</a></li>
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>
28 <li><a href="LangImpl4.html">Chapter 4</a>: Adding JIT and Optimizer
32 <div class="doc_author">
33 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
36 <!-- *********************************************************************** -->
37 <div class="doc_section"><a name="intro">Chapter 3 Introduction</a></div>
38 <!-- *********************************************************************** -->
40 <div class="doc_text">
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</a>, built in Chapter 2, 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. :)
50 <p><b>Please note</b>: the code in this chapter and later require LLVM 2.2 or
51 LLVM SVN to work. LLVM 2.1 and before will not work with it.</p>
55 <!-- *********************************************************************** -->
56 <div class="doc_section"><a name="basics">Code Generation Setup</a></div>
57 <!-- *********************************************************************** -->
59 <div class="doc_text">
62 In order to generate LLVM IR, we want some simple setup to get started. First,
63 we define virtual codegen methods in each AST class:</p>
65 <div class="doc_code">
67 /// ExprAST - Base class for all expression nodes.
71 <b>virtual Value *Codegen() = 0;</b>
74 /// NumberExprAST - Expression class for numeric literals like "1.0".
75 class NumberExprAST : public ExprAST {
78 explicit NumberExprAST(double val) : Val(val) {}
79 <b>virtual Value *Codegen();</b>
85 <p>The Codegen() method says to emit IR for that AST node along with all the things it
86 depends on, and they all return an LLVM Value object.
87 "Value" is the class used to represent a "<a
88 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
89 Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
90 of SSA values is that their value is computed as the related instruction
91 executes, and it does not get a new value until (and if) the instruction
92 re-executes. In other words, there is no way to "change" an SSA value. For
93 more information, please read up on <a
94 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
95 Assignment</a> - the concepts are really quite natural once you grok them.</p>
97 <p>Note that instead of adding virtual methods to the ExprAST class hierarchy,
98 it could also make sense to use a visitor pattern or some other way to model
99 this. Again, this tutorial won't dwell on good software engineering practices:
100 for our purposes, adding a virtual method is simplest.</p>
103 second thing we want is an "Error" method like we used for the parser, which will
104 be used to report errors found during code generation (for example, use of an
105 undeclared parameter):</p>
107 <div class="doc_code">
109 Value *ErrorV(const char *Str) { Error(Str); return 0; }
111 static Module *TheModule;
112 static LLVMBuilder Builder;
113 static std::map<std::string, Value*> NamedValues;
117 <p>The static variables will be used during code generation. <tt>TheModule</tt>
118 is the LLVM construct that contains all of the functions and global variables in
119 a chunk of code. In many ways, it is the top-level structure that the LLVM IR
120 uses to contain code.</p>
122 <p>The <tt>Builder</tt> object is a helper object that makes it easy to generate
123 LLVM instructions. Instances of the <a
124 href="http://llvm.org/doxygen/LLVMBuilder_8h-source.html"><tt>LLVMBuilder</tt>
125 class</a> keep track of the current place to
126 insert instructions and has methods to create new instructions.</p>
128 <p>The <tt>NamedValues</tt> map keeps track of which values are defined in the
129 current scope and what their LLVM representation is (in other words, it is a
130 symbol table for the code). In this form of
131 Kaleidoscope, the only things that can be referenced are function parameters.
132 As such, function parameters will be in this map when generating code for their
136 With these basics in place, we can start talking about how to generate code for
137 each expression. Note that this assumes that the <tt>Builder</tt> has been set
138 up to generate code <em>into</em> something. For now, we'll assume that this
139 has already been done, and we'll just use it to emit code.
144 <!-- *********************************************************************** -->
145 <div class="doc_section"><a name="exprs">Expression Code Generation</a></div>
146 <!-- *********************************************************************** -->
148 <div class="doc_text">
150 <p>Generating LLVM code for expression nodes is very straightforward: less
151 than 45 lines of commented code for all four of our expression nodes. First,
152 we'll do numeric literals:</p>
154 <div class="doc_code">
156 Value *NumberExprAST::Codegen() {
157 return ConstantFP::get(Type::DoubleTy, APFloat(Val));
162 <p>In the LLVM IR, numeric constants are represented with the
163 <tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
164 internally (<tt>APFloat</tt> has the capability of holding floating point
165 constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
166 creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
167 that constants are all uniqued together and shared. For this reason, the API
168 uses "the foo::get(..)" idiom instead of "new foo(..)" or "foo::create(..)".</p>
170 <div class="doc_code">
172 Value *VariableExprAST::Codegen() {
173 // Look this variable up in the function.
174 Value *V = NamedValues[Name];
175 return V ? V : ErrorV("Unknown variable name");
180 <p>References to variables are also quite simple using LLVM. In the simple version
181 of Kaleidoscope, we assume that the variable has already been emited somewhere
182 and its value is available. In practice, the only values that can be in the
183 <tt>NamedValues</tt> map are function arguments. This
184 code simply checks to see that the specified name is in the map (if not, an
185 unknown variable is being referenced) and returns the value for it. In future
186 chapters, we'll add support for <a href="LangImpl5.html#for">loop induction
187 variables</a> in the symbol table, and for <a
188 href="LangImpl7.html#localvars">local variables</a>.</p>
190 <div class="doc_code">
192 Value *BinaryExprAST::Codegen() {
193 Value *L = LHS->Codegen();
194 Value *R = RHS->Codegen();
195 if (L == 0 || R == 0) return 0;
198 case '+': return Builder.CreateAdd(L, R, "addtmp");
199 case '-': return Builder.CreateSub(L, R, "subtmp");
200 case '*': return Builder.CreateMul(L, R, "multmp");
202 L = Builder.CreateFCmpULT(L, R, "cmptmp");
203 // Convert bool 0/1 to double 0.0 or 1.0
204 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
205 default: return ErrorV("invalid binary operator");
211 <p>Binary operators start to get more interesting. The basic idea here is that
212 we recursively emit code for the left-hand side of the expression, then the
213 right-hand side, then we compute the result of the binary expression. In this
214 code, we do a simple switch on the opcode to create the right LLVM instruction.
217 <p>In the example above, the LLVM builder class is starting to show its value.
218 LLVMBuilder knows where to insert the newly created instruction, all you have to
219 do is specify what instruction to create (e.g. with <tt>CreateAdd</tt>), which
220 operands to use (<tt>L</tt> and <tt>R</tt> here) and optionally provide a name
221 for the generated instruction. One nice thing about LLVM is that the name is
222 just a hint: if there are multiple additions in a single function, the first
223 will be named "addtmp" and the second will be "autorenamed" by adding a suffix,
224 giving it a name like "addtmp42". Local value names for instructions are purely
225 optional, but it makes it much easier to read the IR dumps.</p>
227 <p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
228 strict rules: for example, the Left and Right operators of
229 an <a href="../LangRef.html#i_add">add instruction</a> must have the same
230 type, and the result type of the add must match the operand types. Because
231 all values in Kaleidoscope are doubles, this makes for very simple code for add,
234 <p>On the other hand, LLVM specifies that the <a
235 href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
236 (a one bit integer). The problem with this is that Kaleidoscope wants the value to be a 0.0 or 1.0 value. In order to get these semantics, we combine the fcmp instruction with
237 a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
238 converts its input integer into a floating point value by treating the input
239 as an unsigned value. In contrast, if we used the <a
240 href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '<'
241 operator would return 0.0 and -1.0, depending on the input value.</p>
243 <div class="doc_code">
245 Value *CallExprAST::Codegen() {
246 // Look up the name in the global module table.
247 Function *CalleeF = TheModule->getFunction(Callee);
249 return ErrorV("Unknown function referenced");
251 // If argument mismatch error.
252 if (CalleeF->arg_size() != Args.size())
253 return ErrorV("Incorrect # arguments passed");
255 std::vector<Value*> ArgsV;
256 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
257 ArgsV.push_back(Args[i]->Codegen());
258 if (ArgsV.back() == 0) return 0;
261 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
266 <p>Code generation for function calls is quite straightforward with LLVM. The
267 code above initially does a function name lookup in the LLVM Module's symbol
268 table. Recall that the LLVM Module is the container that holds all of the
269 functions we are JIT'ing. By giving each function the same name as what the
270 user specifies, we can use the LLVM symbol table to resolve function names for
273 <p>Once we have the function to call, we recursively codegen each argument that
274 is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
275 instruction</a>. Note that LLVM uses the native C calling conventions by
276 default, allowing these calls to also call into standard library functions like
277 "sin" and "cos", with no additional effort.</p>
279 <p>This wraps up our handling of the four basic expressions that we have so far
280 in Kaleidoscope. Feel free to go in and add some more. For example, by
281 browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
282 several other interesting instructions that are really easy to plug into our
287 <!-- *********************************************************************** -->
288 <div class="doc_section"><a name="funcs">Function Code Generation</a></div>
289 <!-- *********************************************************************** -->
291 <div class="doc_text">
293 <p>Code generation for prototypes and functions must handle a number of
294 details, which make their code less beautiful than expression code
295 generation, but allows us to illustrate some important points. First, lets
296 talk about code generation for prototypes: they are used both for function
297 bodies and external function declarations. The code starts with:</p>
299 <div class="doc_code">
301 Function *PrototypeAST::Codegen() {
302 // Make the function type: double(double,double) etc.
303 std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
304 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
306 Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
310 <p>This code packs a lot of power into a few lines. Note first that this
311 function returns a "Function*" instead of a "Value*". Because a "prototype"
312 really talks about the external interface for a function (not the value computed
313 by an expression), it makes sense for it to return the LLVM Function it
314 corresponds to when codegen'd.</p>
316 <p>The call to <tt>FunctionType::get</tt> creates
317 the <tt>FunctionType</tt> that should be used for a given Prototype. Since all
318 function arguments in Kaleidoscope are of type double, the first line creates
319 a vector of "N" LLVM double types. It then uses the <tt>FunctionType::get</tt>
320 method to create a function type that takes "N" doubles as arguments, returns
321 one double as a result, and that is not vararg (the false parameter indicates
322 this). Note that Types in LLVM are uniqued just like Constants are, so you
323 don't "new" a type, you "get" it.</p>
325 <p>The final line above actually creates the function that the prototype will
326 correspond to. This indicates the type, linkage and name to use, as well as which
327 module to insert into. "<a href="LangRef.html#linkage">external linkage</a>"
328 means that the function may be defined outside the current module and/or that it
329 is callable by functions outside the module. The Name passed in is the name the
330 user specified: since "<tt>TheModule</tt>" is specified, this name is registered
331 in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
334 <div class="doc_code">
336 // If F conflicted, there was already something named 'Name'. If it has a
337 // body, don't allow redefinition or reextern.
338 if (F->getName() != Name) {
339 // Delete the one we just made and get the existing one.
340 F->eraseFromParent();
341 F = TheModule->getFunction(Name);
345 <p>The Module symbol table works just like the Function symbol table when it
346 comes to name conflicts: if a new function is created with a name was previously
347 added to the symbol table, it will get implicitly renamed when added to the
348 Module. The code above exploits this fact to determine if there was a previous
349 definition of this function.</p>
351 <p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
352 first, we want to allow 'extern'ing a function more than once, as long as the
353 prototypes for the externs match (since all arguments have the same type, we
354 just have to check that the number of arguments match). Second, we want to
355 allow 'extern'ing a function and then definining a body for it. This is useful
356 when defining mutually recursive functions.</p>
358 <p>In order to implement this, the code above first checks to see if there is
359 a collision on the name of the function. If so, it deletes the function we just
360 created (by calling <tt>eraseFromParent</tt>) and then calling
361 <tt>getFunction</tt> to get the existing function with the specified name. Note
362 that many APIs in LLVM have "erase" forms and "remove" forms. The "remove" form
363 unlinks the object from its parent (e.g. a Function from a Module) and returns
364 it. The "erase" form unlinks the object and then deletes it.</p>
366 <div class="doc_code">
368 // If F already has a body, reject this.
369 if (!F->empty()) {
370 ErrorF("redefinition of function");
374 // If F took a different number of args, reject.
375 if (F->arg_size() != Args.size()) {
376 ErrorF("redefinition of function with different # args");
383 <p>In order to verify the logic above, we first check to see if the pre-existing
384 function is "empty". In this case, empty means that it has no basic blocks in
385 it, which means it has no body. If it has no body, it is a forward
386 declaration. Since we don't allow anything after a full definition of the
387 function, the code rejects this case. If the previous reference to a function
388 was an 'extern', we simply verify that the number of arguments for that
389 definition and this one match up. If not, we emit an error.</p>
391 <div class="doc_code">
393 // Set names for all arguments.
395 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
397 AI->setName(Args[Idx]);
399 // Add arguments to variable symbol table.
400 NamedValues[Args[Idx]] = AI;
407 <p>The last bit of code for prototypes loops over all of the arguments in the
408 function, setting the name of the LLVM Argument objects to match, and registering
409 the arguments in the <tt>NamedValues</tt> map for future use by the
410 <tt>VariableExprAST</tt> AST node. Once this is set up, it returns the Function
411 object to the caller. Note that we don't check for conflicting
412 argument names here (e.g. "extern foo(a b a)"). Doing so would be very
413 straight-forward with the mechanics we have already used above.</p>
415 <div class="doc_code">
417 Function *FunctionAST::Codegen() {
420 Function *TheFunction = Proto->Codegen();
421 if (TheFunction == 0)
426 <p>Code generation for function definitions starts out simply enough: we just
427 codegen the prototype (Proto) and verify that it is ok. We then clear out the
428 <tt>NamedValues</tt> map to make sure that there isn't anything in it from the
429 last function we compiled. Code generation of the prototype ensures that there
430 is an LLVM Function object that is ready to go for us.</p>
432 <div class="doc_code">
434 // Create a new basic block to start insertion into.
435 BasicBlock *BB = new BasicBlock("entry", TheFunction);
436 Builder.SetInsertPoint(BB);
438 if (Value *RetVal = Body->Codegen()) {
442 <p>Now we get to the point where the <tt>Builder</tt> is set up. The first
443 line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
444 block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>. The
445 second line then tells the builder that new instructions should be inserted into
446 the end of the new basic block. Basic blocks in LLVM are an important part
447 of functions that define the <a
448 href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
449 Since we don't have any control flow, our functions will only contain one
450 block at this point. We'll fix this in <a href="LangImpl5.html">Chapter 5</a> :).</p>
452 <div class="doc_code">
454 if (Value *RetVal = Body->Codegen()) {
455 // Finish off the function.
456 Builder.CreateRet(RetVal);
458 // Validate the generated code, checking for consistency.
459 verifyFunction(*TheFunction);
465 <p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
466 the root expression of the function. If no error happens, this emits code to
467 compute the expression into the entry block and returns the value that was
468 computed. Assuming no error, we then create an LLVM <a
469 href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
470 Once the function is built, we call <tt>verifyFunction</tt>, which
471 is provided by LLVM. This function does a variety of consistency checks on the
472 generated code, to determine if our compiler is doing everything right. Using
473 this is important: it can catch a lot of bugs. Once the function is finished
474 and validated, we return it.</p>
476 <div class="doc_code">
478 // Error reading body, remove function.
479 TheFunction->eraseFromParent();
485 <p>The only piece left here is handling of the error case. For simplicity, we
486 handle this by merely deleting the function we produced with the
487 <tt>eraseFromParent</tt> method. This allows the user to redefine a function
488 that they incorrectly typed in before: if we didn't delete it, it would live in
489 the symbol table, with a body, preventing future redefinition.</p>
491 <p>This code does have a bug, though. Since the <tt>PrototypeAST::Codegen</tt>
492 can return a previously defined forward declaration, our code can actually delete
493 a forward declaration. There are a number of ways to fix this bug, see what you
494 can come up with! Here is a testcase:</p>
496 <div class="doc_code">
498 extern foo(a b); # ok, defines foo.
499 def foo(a b) c; # error, 'c' is invalid.
500 def bar() foo(1, 2); # error, unknown function "foo"
506 <!-- *********************************************************************** -->
507 <div class="doc_section"><a name="driver">Driver Changes and
508 Closing Thoughts</a></div>
509 <!-- *********************************************************************** -->
511 <div class="doc_text">
514 For now, code generation to LLVM doesn't really get us much, except that we can
515 look at the pretty IR calls. The sample code inserts calls to Codegen into the
516 "<tt>HandleDefinition</tt>", "<tt>HandleExtern</tt>" etc functions, and then
517 dumps out the LLVM IR. This gives a nice way to look at the LLVM IR for simple
518 functions. For example:
521 <div class="doc_code">
524 Read top-level expression:
525 define double @""() {
527 %addtmp = add double 4.000000e+00, 5.000000e+00
533 <p>Note how the parser turns the top-level expression into anonymous functions
534 for us. This will be handy when we add <a href="LangImpl4.html#jit">JIT
535 support</a> in the next chapter. Also note that the code is very literally
536 transcribed, no optimizations are being performed. We will
537 <a href="LangImpl4.html#trivialconstfold">add optimizations</a> explicitly in
538 the next chapter.</p>
540 <div class="doc_code">
542 ready> <b>def foo(a b) a*a + 2*a*b + b*b;</b>
543 Read function definition:
544 define double @foo(double %a, double %b) {
546 %multmp = mul double %a, %a
547 %multmp1 = mul double 2.000000e+00, %a
548 %multmp2 = mul double %multmp1, %b
549 %addtmp = add double %multmp, %multmp2
550 %multmp3 = mul double %b, %b
551 %addtmp4 = add double %addtmp, %multmp3
557 <p>This shows some simple arithmetic. Notice the striking similarity to the
558 LLVM builder calls that we use to create the instructions.</p>
560 <div class="doc_code">
562 ready> <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
563 Read function definition:
564 define double @bar(double %a) {
566 %calltmp = call double @foo( double %a, double 4.000000e+00 )
567 %calltmp1 = call double @bar( double 3.133700e+04 )
568 %addtmp = add double %calltmp, %calltmp1
574 <p>This shows some function calls. Note that this function will take a long
575 time to execute if you call it. In the future we'll add conditional control
576 flow to actually make recursion useful :).</p>
578 <div class="doc_code">
580 ready> <b>extern cos(x);</b>
582 declare double @cos(double)
584 ready> <b>cos(1.234);</b>
585 Read top-level expression:
586 define double @""() {
588 %calltmp = call double @cos( double 1.234000e+00 )
594 <p>This shows an extern for the libm "cos" function, and a call to it.</p>
597 <div class="doc_code">
600 ; ModuleID = 'my cool jit'
602 define double @""() {
604 %addtmp = add double 4.000000e+00, 5.000000e+00
608 define double @foo(double %a, double %b) {
610 %multmp = mul double %a, %a
611 %multmp1 = mul double 2.000000e+00, %a
612 %multmp2 = mul double %multmp1, %b
613 %addtmp = add double %multmp, %multmp2
614 %multmp3 = mul double %b, %b
615 %addtmp4 = add double %addtmp, %multmp3
619 define double @bar(double %a) {
621 %calltmp = call double @foo( double %a, double 4.000000e+00 )
622 %calltmp1 = call double @bar( double 3.133700e+04 )
623 %addtmp = add double %calltmp, %calltmp1
627 declare double @cos(double)
629 define double @""() {
631 %calltmp = call double @cos( double 1.234000e+00 )
637 <p>When you quit the current demo, it dumps out the IR for the entire module
638 generated. Here you can see the big picture with all the functions referencing
641 <p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next, we'll
642 describe how to <a href="LangImpl4.html">add JIT codegen and optimizer
643 support</a> to this so we can actually start running code!</p>
648 <!-- *********************************************************************** -->
649 <div class="doc_section"><a name="code">Full Code Listing</a></div>
650 <!-- *********************************************************************** -->
652 <div class="doc_text">
655 Here is the complete code listing for our running example, enhanced with the
656 LLVM code generator. Because this uses the LLVM libraries, we need to link
657 them in. To do this, we use the <a
658 href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
659 our makefile/command line about which options to use:</p>
661 <div class="doc_code">
664 g++ -g -O3 toy.cpp `llvm-config --cppflags --ldflags --libs core` -o toy
670 <p>Here is the code:</p>
672 <div class="doc_code">
675 // See example below.
677 #include "llvm/DerivedTypes.h"
678 #include "llvm/Module.h"
679 #include "llvm/Analysis/Verifier.h"
680 #include "llvm/Support/LLVMBuilder.h"
681 #include <cstdio>
682 #include <string>
684 #include <vector>
685 using namespace llvm;
687 //===----------------------------------------------------------------------===//
689 //===----------------------------------------------------------------------===//
691 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
692 // of these for known things.
697 tok_def = -2, tok_extern = -3,
700 tok_identifier = -4, tok_number = -5,
703 static std::string IdentifierStr; // Filled in if tok_identifier
704 static double NumVal; // Filled in if tok_number
706 /// gettok - Return the next token from standard input.
707 static int gettok() {
708 static int LastChar = ' ';
710 // Skip any whitespace.
711 while (isspace(LastChar))
712 LastChar = getchar();
714 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
715 IdentifierStr = LastChar;
716 while (isalnum((LastChar = getchar())))
717 IdentifierStr += LastChar;
719 if (IdentifierStr == "def") return tok_def;
720 if (IdentifierStr == "extern") return tok_extern;
721 return tok_identifier;
724 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
728 LastChar = getchar();
729 } while (isdigit(LastChar) || LastChar == '.');
731 NumVal = strtod(NumStr.c_str(), 0);
735 if (LastChar == '#') {
736 // Comment until end of line.
737 do LastChar = getchar();
738 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
744 // Check for end of file. Don't eat the EOF.
748 // Otherwise, just return the character as its ascii value.
749 int ThisChar = LastChar;
750 LastChar = getchar();
754 //===----------------------------------------------------------------------===//
755 // Abstract Syntax Tree (aka Parse Tree)
756 //===----------------------------------------------------------------------===//
758 /// ExprAST - Base class for all expression nodes.
761 virtual ~ExprAST() {}
762 virtual Value *Codegen() = 0;
765 /// NumberExprAST - Expression class for numeric literals like "1.0".
766 class NumberExprAST : public ExprAST {
769 explicit NumberExprAST(double val) : Val(val) {}
770 virtual Value *Codegen();
773 /// VariableExprAST - Expression class for referencing a variable, like "a".
774 class VariableExprAST : public ExprAST {
777 explicit VariableExprAST(const std::string &name) : Name(name) {}
778 virtual Value *Codegen();
781 /// BinaryExprAST - Expression class for a binary operator.
782 class BinaryExprAST : public ExprAST {
786 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
787 : Op(op), LHS(lhs), RHS(rhs) {}
788 virtual Value *Codegen();
791 /// CallExprAST - Expression class for function calls.
792 class CallExprAST : public ExprAST {
794 std::vector<ExprAST*> Args;
796 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
797 : Callee(callee), Args(args) {}
798 virtual Value *Codegen();
801 /// PrototypeAST - This class represents the "prototype" for a function,
802 /// which captures its argument names as well as if it is an operator.
805 std::vector<std::string> Args;
807 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
808 : Name(name), Args(args) {}
813 /// FunctionAST - This class represents a function definition itself.
818 FunctionAST(PrototypeAST *proto, ExprAST *body)
819 : Proto(proto), Body(body) {}
824 //===----------------------------------------------------------------------===//
826 //===----------------------------------------------------------------------===//
828 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
829 /// token the parser it looking at. getNextToken reads another token from the
830 /// lexer and updates CurTok with its results.
832 static int getNextToken() {
833 return CurTok = gettok();
836 /// BinopPrecedence - This holds the precedence for each binary operator that is
838 static std::map<char, int> BinopPrecedence;
840 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
841 static int GetTokPrecedence() {
842 if (!isascii(CurTok))
845 // Make sure it's a declared binop.
846 int TokPrec = BinopPrecedence[CurTok];
847 if (TokPrec <= 0) return -1;
851 /// Error* - These are little helper functions for error handling.
852 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
853 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
854 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
856 static ExprAST *ParseExpression();
860 /// ::= identifier '(' expression* ')'
861 static ExprAST *ParseIdentifierExpr() {
862 std::string IdName = IdentifierStr;
864 getNextToken(); // eat identifier.
866 if (CurTok != '(') // Simple variable ref.
867 return new VariableExprAST(IdName);
870 getNextToken(); // eat (
871 std::vector<ExprAST*> Args;
874 ExprAST *Arg = ParseExpression();
878 if (CurTok == ')') break;
881 return Error("Expected ')'");
889 return new CallExprAST(IdName, Args);
892 /// numberexpr ::= number
893 static ExprAST *ParseNumberExpr() {
894 ExprAST *Result = new NumberExprAST(NumVal);
895 getNextToken(); // consume the number
899 /// parenexpr ::= '(' expression ')'
900 static ExprAST *ParseParenExpr() {
901 getNextToken(); // eat (.
902 ExprAST *V = ParseExpression();
906 return Error("expected ')'");
907 getNextToken(); // eat ).
912 /// ::= identifierexpr
915 static ExprAST *ParsePrimary() {
917 default: return Error("unknown token when expecting an expression");
918 case tok_identifier: return ParseIdentifierExpr();
919 case tok_number: return ParseNumberExpr();
920 case '(': return ParseParenExpr();
925 /// ::= ('+' primary)*
926 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
927 // If this is a binop, find its precedence.
929 int TokPrec = GetTokPrecedence();
931 // If this is a binop that binds at least as tightly as the current binop,
932 // consume it, otherwise we are done.
933 if (TokPrec < ExprPrec)
936 // Okay, we know this is a binop.
938 getNextToken(); // eat binop
940 // Parse the primary expression after the binary operator.
941 ExprAST *RHS = ParsePrimary();
944 // If BinOp binds less tightly with RHS than the operator after RHS, let
945 // the pending operator take RHS as its LHS.
946 int NextPrec = GetTokPrecedence();
947 if (TokPrec < NextPrec) {
948 RHS = ParseBinOpRHS(TokPrec+1, RHS);
949 if (RHS == 0) return 0;
953 LHS = new BinaryExprAST(BinOp, LHS, RHS);
958 /// ::= primary binoprhs
960 static ExprAST *ParseExpression() {
961 ExprAST *LHS = ParsePrimary();
964 return ParseBinOpRHS(0, LHS);
968 /// ::= id '(' id* ')'
969 static PrototypeAST *ParsePrototype() {
970 if (CurTok != tok_identifier)
971 return ErrorP("Expected function name in prototype");
973 std::string FnName = IdentifierStr;
977 return ErrorP("Expected '(' in prototype");
979 std::vector<std::string> ArgNames;
980 while (getNextToken() == tok_identifier)
981 ArgNames.push_back(IdentifierStr);
983 return ErrorP("Expected ')' in prototype");
986 getNextToken(); // eat ')'.
988 return new PrototypeAST(FnName, ArgNames);
991 /// definition ::= 'def' prototype expression
992 static FunctionAST *ParseDefinition() {
993 getNextToken(); // eat def.
994 PrototypeAST *Proto = ParsePrototype();
995 if (Proto == 0) return 0;
997 if (ExprAST *E = ParseExpression())
998 return new FunctionAST(Proto, E);
1002 /// toplevelexpr ::= expression
1003 static FunctionAST *ParseTopLevelExpr() {
1004 if (ExprAST *E = ParseExpression()) {
1005 // Make an anonymous proto.
1006 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
1007 return new FunctionAST(Proto, E);
1012 /// external ::= 'extern' prototype
1013 static PrototypeAST *ParseExtern() {
1014 getNextToken(); // eat extern.
1015 return ParsePrototype();
1018 //===----------------------------------------------------------------------===//
1020 //===----------------------------------------------------------------------===//
1022 static Module *TheModule;
1023 static LLVMBuilder Builder;
1024 static std::map<std::string, Value*> NamedValues;
1026 Value *ErrorV(const char *Str) { Error(Str); return 0; }
1028 Value *NumberExprAST::Codegen() {
1029 return ConstantFP::get(Type::DoubleTy, APFloat(Val));
1032 Value *VariableExprAST::Codegen() {
1033 // Look this variable up in the function.
1034 Value *V = NamedValues[Name];
1035 return V ? V : ErrorV("Unknown variable name");
1038 Value *BinaryExprAST::Codegen() {
1039 Value *L = LHS->Codegen();
1040 Value *R = RHS->Codegen();
1041 if (L == 0 || R == 0) return 0;
1044 case '+': return Builder.CreateAdd(L, R, "addtmp");
1045 case '-': return Builder.CreateSub(L, R, "subtmp");
1046 case '*': return Builder.CreateMul(L, R, "multmp");
1048 L = Builder.CreateFCmpULT(L, R, "cmptmp");
1049 // Convert bool 0/1 to double 0.0 or 1.0
1050 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
1051 default: return ErrorV("invalid binary operator");
1055 Value *CallExprAST::Codegen() {
1056 // Look up the name in the global module table.
1057 Function *CalleeF = TheModule->getFunction(Callee);
1059 return ErrorV("Unknown function referenced");
1061 // If argument mismatch error.
1062 if (CalleeF->arg_size() != Args.size())
1063 return ErrorV("Incorrect # arguments passed");
1065 std::vector<Value*> ArgsV;
1066 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1067 ArgsV.push_back(Args[i]->Codegen());
1068 if (ArgsV.back() == 0) return 0;
1071 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
1074 Function *PrototypeAST::Codegen() {
1075 // Make the function type: double(double,double) etc.
1076 std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
1077 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
1079 Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
1081 // If F conflicted, there was already something named 'Name'. If it has a
1082 // body, don't allow redefinition or reextern.
1083 if (F->getName() != Name) {
1084 // Delete the one we just made and get the existing one.
1085 F->eraseFromParent();
1086 F = TheModule->getFunction(Name);
1088 // If F already has a body, reject this.
1089 if (!F->empty()) {
1090 ErrorF("redefinition of function");
1094 // If F took a different number of args, reject.
1095 if (F->arg_size() != Args.size()) {
1096 ErrorF("redefinition of function with different # args");
1101 // Set names for all arguments.
1103 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1105 AI->setName(Args[Idx]);
1107 // Add arguments to variable symbol table.
1108 NamedValues[Args[Idx]] = AI;
1114 Function *FunctionAST::Codegen() {
1115 NamedValues.clear();
1117 Function *TheFunction = Proto->Codegen();
1118 if (TheFunction == 0)
1121 // Create a new basic block to start insertion into.
1122 BasicBlock *BB = new BasicBlock("entry", TheFunction);
1123 Builder.SetInsertPoint(BB);
1125 if (Value *RetVal = Body->Codegen()) {
1126 // Finish off the function.
1127 Builder.CreateRet(RetVal);
1129 // Validate the generated code, checking for consistency.
1130 verifyFunction(*TheFunction);
1134 // Error reading body, remove function.
1135 TheFunction->eraseFromParent();
1139 //===----------------------------------------------------------------------===//
1140 // Top-Level parsing and JIT Driver
1141 //===----------------------------------------------------------------------===//
1143 static void HandleDefinition() {
1144 if (FunctionAST *F = ParseDefinition()) {
1145 if (Function *LF = F->Codegen()) {
1146 fprintf(stderr, "Read function definition:");
1150 // Skip token for error recovery.
1155 static void HandleExtern() {
1156 if (PrototypeAST *P = ParseExtern()) {
1157 if (Function *F = P->Codegen()) {
1158 fprintf(stderr, "Read extern: ");
1162 // Skip token for error recovery.
1167 static void HandleTopLevelExpression() {
1168 // Evaluate a top level expression into an anonymous function.
1169 if (FunctionAST *F = ParseTopLevelExpr()) {
1170 if (Function *LF = F->Codegen()) {
1171 fprintf(stderr, "Read top-level expression:");
1175 // Skip token for error recovery.
1180 /// top ::= definition | external | expression | ';'
1181 static void MainLoop() {
1183 fprintf(stderr, "ready> ");
1185 case tok_eof: return;
1186 case ';': getNextToken(); break; // ignore top level semicolons.
1187 case tok_def: HandleDefinition(); break;
1188 case tok_extern: HandleExtern(); break;
1189 default: HandleTopLevelExpression(); break;
1196 //===----------------------------------------------------------------------===//
1197 // "Library" functions that can be "extern'd" from user code.
1198 //===----------------------------------------------------------------------===//
1200 /// putchard - putchar that takes a double and returns 0.
1202 double putchard(double X) {
1207 //===----------------------------------------------------------------------===//
1208 // Main driver code.
1209 //===----------------------------------------------------------------------===//
1212 TheModule = new Module("my cool jit");
1214 // Install standard binary operators.
1215 // 1 is lowest precedence.
1216 BinopPrecedence['<'] = 10;
1217 BinopPrecedence['+'] = 20;
1218 BinopPrecedence['-'] = 20;
1219 BinopPrecedence['*'] = 40; // highest.
1221 // Prime the first token.
1222 fprintf(stderr, "ready> ");
1226 TheModule->dump();
1233 <!-- *********************************************************************** -->
1236 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1237 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1238 <a href="http://validator.w3.org/check/referer"><img
1239 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1241 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1242 <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
1243 Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $