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 <h1>Kaleidoscope: Code generation to LLVM IR</h1>
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 <h2><a name="intro">Chapter 3 Introduction</a></h2>
38 <!-- *********************************************************************** -->
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 later. LLVM 2.1 and before will not work with it. Also note that you need
52 to use a version of this tutorial that matches your LLVM release: If you are
53 using an official LLVM release, use the version of the documentation included
54 with your release or on the <a href="http://llvm.org/releases/">llvm.org
55 releases page</a>.</p>
59 <!-- *********************************************************************** -->
60 <h2><a name="basics">Code Generation Setup</a></h2>
61 <!-- *********************************************************************** -->
66 In order to generate LLVM IR, we want some simple setup to get started. First
67 we define virtual code generation (codegen) methods in each AST class:</p>
69 <div class="doc_code">
71 /// ExprAST - Base class for all expression nodes.
75 <b>virtual Value *Codegen() = 0;</b>
78 /// NumberExprAST - Expression class for numeric literals like "1.0".
79 class NumberExprAST : public ExprAST {
82 NumberExprAST(double val) : Val(val) {}
83 <b>virtual Value *Codegen();</b>
89 <p>The Codegen() method says to emit IR for that AST node along with all the things it
90 depends on, and they all return an LLVM Value object.
91 "Value" is the class used to represent a "<a
92 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
93 Assignment (SSA)</a> register" or "SSA value" in LLVM. The most distinct aspect
94 of SSA values is that their value is computed as the related instruction
95 executes, and it does not get a new value until (and if) the instruction
96 re-executes. In other words, there is no way to "change" an SSA value. For
97 more information, please read up on <a
98 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
99 Assignment</a> - the concepts are really quite natural once you grok them.</p>
101 <p>Note that instead of adding virtual methods to the ExprAST class hierarchy,
102 it could also make sense to use a <a
103 href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor pattern</a> or some
104 other way to model this. Again, this tutorial won't dwell on good software
105 engineering practices: for our purposes, adding a virtual method is
109 second thing we want is an "Error" method like we used for the parser, which will
110 be used to report errors found during code generation (for example, use of an
111 undeclared parameter):</p>
113 <div class="doc_code">
115 Value *ErrorV(const char *Str) { Error(Str); return 0; }
117 static Module *TheModule;
118 static IRBuilder<> Builder(getGlobalContext());
119 static std::map<std::string, Value*> NamedValues;
123 <p>The static variables will be used during code generation. <tt>TheModule</tt>
124 is the LLVM construct that contains all of the functions and global variables in
125 a chunk of code. In many ways, it is the top-level structure that the LLVM IR
126 uses to contain code.</p>
128 <p>The <tt>Builder</tt> object is a helper object that makes it easy to generate
129 LLVM instructions. Instances of the <a
130 href="http://llvm.org/doxygen/IRBuilder_8h-source.html"><tt>IRBuilder</tt></a>
131 class template keep track of the current place to insert instructions and has
132 methods to create new instructions.</p>
134 <p>The <tt>NamedValues</tt> map keeps track of which values are defined in the
135 current scope and what their LLVM representation is. (In other words, it is a
136 symbol table for the code). In this form of Kaleidoscope, the only things that
137 can be referenced are function parameters. As such, function parameters will
138 be in this map when generating code for their function body.</p>
141 With these basics in place, we can start talking about how to generate code for
142 each expression. Note that this assumes that the <tt>Builder</tt> has been set
143 up to generate code <em>into</em> something. For now, we'll assume that this
144 has already been done, and we'll just use it to emit code.
149 <!-- *********************************************************************** -->
150 <h2><a name="exprs">Expression Code Generation</a></h2>
151 <!-- *********************************************************************** -->
155 <p>Generating LLVM code for expression nodes is very straightforward: less
156 than 45 lines of commented code for all four of our expression nodes. First
157 we'll do numeric literals:</p>
159 <div class="doc_code">
161 Value *NumberExprAST::Codegen() {
162 return ConstantFP::get(getGlobalContext(), APFloat(Val));
167 <p>In the LLVM IR, numeric constants are represented with the
168 <tt>ConstantFP</tt> class, which holds the numeric value in an <tt>APFloat</tt>
169 internally (<tt>APFloat</tt> has the capability of holding floating point
170 constants of <em>A</em>rbitrary <em>P</em>recision). This code basically just
171 creates and returns a <tt>ConstantFP</tt>. Note that in the LLVM IR
172 that constants are all uniqued together and shared. For this reason, the API
173 uses the "foo::get(...)" idiom instead of "new foo(..)" or "foo::Create(..)".</p>
175 <div class="doc_code">
177 Value *VariableExprAST::Codegen() {
178 // Look this variable up in the function.
179 Value *V = NamedValues[Name];
180 return V ? V : ErrorV("Unknown variable name");
185 <p>References to variables are also quite simple using LLVM. In the simple version
186 of Kaleidoscope, we assume that the variable has already been emitted somewhere
187 and its value is available. In practice, the only values that can be in the
188 <tt>NamedValues</tt> map are function arguments. This
189 code simply checks to see that the specified name is in the map (if not, an
190 unknown variable is being referenced) and returns the value for it. In future
191 chapters, we'll add support for <a href="LangImpl5.html#for">loop induction
192 variables</a> in the symbol table, and for <a
193 href="LangImpl7.html#localvars">local variables</a>.</p>
195 <div class="doc_code">
197 Value *BinaryExprAST::Codegen() {
198 Value *L = LHS->Codegen();
199 Value *R = RHS->Codegen();
200 if (L == 0 || R == 0) return 0;
203 case '+': return Builder.CreateFAdd(L, R, "addtmp");
204 case '-': return Builder.CreateFSub(L, R, "subtmp");
205 case '*': return Builder.CreateFMul(L, R, "multmp");
207 L = Builder.CreateFCmpULT(L, R, "cmptmp");
208 // Convert bool 0/1 to double 0.0 or 1.0
209 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
211 default: return ErrorV("invalid binary operator");
217 <p>Binary operators start to get more interesting. The basic idea here is that
218 we recursively emit code for the left-hand side of the expression, then the
219 right-hand side, then we compute the result of the binary expression. In this
220 code, we do a simple switch on the opcode to create the right LLVM instruction.
223 <p>In the example above, the LLVM builder class is starting to show its value.
224 IRBuilder knows where to insert the newly created instruction, all you have to
225 do is specify what instruction to create (e.g. with <tt>CreateFAdd</tt>), which
226 operands to use (<tt>L</tt> and <tt>R</tt> here) and optionally provide a name
227 for the generated instruction.</p>
229 <p>One nice thing about LLVM is that the name is just a hint. For instance, if
230 the code above emits multiple "addtmp" variables, LLVM will automatically
231 provide each one with an increasing, unique numeric suffix. Local value names
232 for instructions are purely optional, but it makes it much easier to read the
235 <p><a href="../LangRef.html#instref">LLVM instructions</a> are constrained by
236 strict rules: for example, the Left and Right operators of
237 an <a href="../LangRef.html#i_add">add instruction</a> must have the same
238 type, and the result type of the add must match the operand types. Because
239 all values in Kaleidoscope are doubles, this makes for very simple code for add,
242 <p>On the other hand, LLVM specifies that the <a
243 href="../LangRef.html#i_fcmp">fcmp instruction</a> always returns an 'i1' value
244 (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
245 a <a href="../LangRef.html#i_uitofp">uitofp instruction</a>. This instruction
246 converts its input integer into a floating point value by treating the input
247 as an unsigned value. In contrast, if we used the <a
248 href="../LangRef.html#i_sitofp">sitofp instruction</a>, the Kaleidoscope '<'
249 operator would return 0.0 and -1.0, depending on the input value.</p>
251 <div class="doc_code">
253 Value *CallExprAST::Codegen() {
254 // Look up the name in the global module table.
255 Function *CalleeF = TheModule->getFunction(Callee);
257 return ErrorV("Unknown function referenced");
259 // If argument mismatch error.
260 if (CalleeF->arg_size() != Args.size())
261 return ErrorV("Incorrect # arguments passed");
263 std::vector<Value*> ArgsV;
264 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
265 ArgsV.push_back(Args[i]->Codegen());
266 if (ArgsV.back() == 0) return 0;
269 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
274 <p>Code generation for function calls is quite straightforward with LLVM. The
275 code above initially does a function name lookup in the LLVM Module's symbol
276 table. Recall that the LLVM Module is the container that holds all of the
277 functions we are JIT'ing. By giving each function the same name as what the
278 user specifies, we can use the LLVM symbol table to resolve function names for
281 <p>Once we have the function to call, we recursively codegen each argument that
282 is to be passed in, and create an LLVM <a href="../LangRef.html#i_call">call
283 instruction</a>. Note that LLVM uses the native C calling conventions by
284 default, allowing these calls to also call into standard library functions like
285 "sin" and "cos", with no additional effort.</p>
287 <p>This wraps up our handling of the four basic expressions that we have so far
288 in Kaleidoscope. Feel free to go in and add some more. For example, by
289 browsing the <a href="../LangRef.html">LLVM language reference</a> you'll find
290 several other interesting instructions that are really easy to plug into our
295 <!-- *********************************************************************** -->
296 <h2><a name="funcs">Function Code Generation</a></h2>
297 <!-- *********************************************************************** -->
301 <p>Code generation for prototypes and functions must handle a number of
302 details, which make their code less beautiful than expression code
303 generation, but allows us to illustrate some important points. First, lets
304 talk about code generation for prototypes: they are used both for function
305 bodies and external function declarations. The code starts with:</p>
307 <div class="doc_code">
309 Function *PrototypeAST::Codegen() {
310 // Make the function type: double(double,double) etc.
311 std::vector<const Type*> Doubles(Args.size(),
312 Type::getDoubleTy(getGlobalContext()));
313 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
316 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
320 <p>This code packs a lot of power into a few lines. Note first that this
321 function returns a "Function*" instead of a "Value*". Because a "prototype"
322 really talks about the external interface for a function (not the value computed
323 by an expression), it makes sense for it to return the LLVM Function it
324 corresponds to when codegen'd.</p>
326 <p>The call to <tt>FunctionType::get</tt> creates
327 the <tt>FunctionType</tt> that should be used for a given Prototype. Since all
328 function arguments in Kaleidoscope are of type double, the first line creates
329 a vector of "N" LLVM double types. It then uses the <tt>Functiontype::get</tt>
330 method to create a function type that takes "N" doubles as arguments, returns
331 one double as a result, and that is not vararg (the false parameter indicates
332 this). Note that Types in LLVM are uniqued just like Constants are, so you
333 don't "new" a type, you "get" it.</p>
335 <p>The final line above actually creates the function that the prototype will
336 correspond to. This indicates the type, linkage and name to use, as well as which
337 module to insert into. "<a href="../LangRef.html#linkage">external linkage</a>"
338 means that the function may be defined outside the current module and/or that it
339 is callable by functions outside the module. The Name passed in is the name the
340 user specified: since "<tt>TheModule</tt>" is specified, this name is registered
341 in "<tt>TheModule</tt>"s symbol table, which is used by the function call code
344 <div class="doc_code">
346 // If F conflicted, there was already something named 'Name'. If it has a
347 // body, don't allow redefinition or reextern.
348 if (F->getName() != Name) {
349 // Delete the one we just made and get the existing one.
350 F->eraseFromParent();
351 F = TheModule->getFunction(Name);
355 <p>The Module symbol table works just like the Function symbol table when it
356 comes to name conflicts: if a new function is created with a name that was previously
357 added to the symbol table, the new function will get implicitly renamed when added to the
358 Module. The code above exploits this fact to determine if there was a previous
359 definition of this function.</p>
361 <p>In Kaleidoscope, I choose to allow redefinitions of functions in two cases:
362 first, we want to allow 'extern'ing a function more than once, as long as the
363 prototypes for the externs match (since all arguments have the same type, we
364 just have to check that the number of arguments match). Second, we want to
365 allow 'extern'ing a function and then defining a body for it. This is useful
366 when defining mutually recursive functions.</p>
368 <p>In order to implement this, the code above first checks to see if there is
369 a collision on the name of the function. If so, it deletes the function we just
370 created (by calling <tt>eraseFromParent</tt>) and then calling
371 <tt>getFunction</tt> to get the existing function with the specified name. Note
372 that many APIs in LLVM have "erase" forms and "remove" forms. The "remove" form
373 unlinks the object from its parent (e.g. a Function from a Module) and returns
374 it. The "erase" form unlinks the object and then deletes it.</p>
376 <div class="doc_code">
378 // If F already has a body, reject this.
379 if (!F->empty()) {
380 ErrorF("redefinition of function");
384 // If F took a different number of args, reject.
385 if (F->arg_size() != Args.size()) {
386 ErrorF("redefinition of function with different # args");
393 <p>In order to verify the logic above, we first check to see if the pre-existing
394 function is "empty". In this case, empty means that it has no basic blocks in
395 it, which means it has no body. If it has no body, it is a forward
396 declaration. Since we don't allow anything after a full definition of the
397 function, the code rejects this case. If the previous reference to a function
398 was an 'extern', we simply verify that the number of arguments for that
399 definition and this one match up. If not, we emit an error.</p>
401 <div class="doc_code">
403 // Set names for all arguments.
405 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
407 AI->setName(Args[Idx]);
409 // Add arguments to variable symbol table.
410 NamedValues[Args[Idx]] = AI;
417 <p>The last bit of code for prototypes loops over all of the arguments in the
418 function, setting the name of the LLVM Argument objects to match, and registering
419 the arguments in the <tt>NamedValues</tt> map for future use by the
420 <tt>VariableExprAST</tt> AST node. Once this is set up, it returns the Function
421 object to the caller. Note that we don't check for conflicting
422 argument names here (e.g. "extern foo(a b a)"). Doing so would be very
423 straight-forward with the mechanics we have already used above.</p>
425 <div class="doc_code">
427 Function *FunctionAST::Codegen() {
430 Function *TheFunction = Proto->Codegen();
431 if (TheFunction == 0)
436 <p>Code generation for function definitions starts out simply enough: we just
437 codegen the prototype (Proto) and verify that it is ok. We then clear out the
438 <tt>NamedValues</tt> map to make sure that there isn't anything in it from the
439 last function we compiled. Code generation of the prototype ensures that there
440 is an LLVM Function object that is ready to go for us.</p>
442 <div class="doc_code">
444 // Create a new basic block to start insertion into.
445 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
446 Builder.SetInsertPoint(BB);
448 if (Value *RetVal = Body->Codegen()) {
452 <p>Now we get to the point where the <tt>Builder</tt> is set up. The first
453 line creates a new <a href="http://en.wikipedia.org/wiki/Basic_block">basic
454 block</a> (named "entry"), which is inserted into <tt>TheFunction</tt>. The
455 second line then tells the builder that new instructions should be inserted into
456 the end of the new basic block. Basic blocks in LLVM are an important part
457 of functions that define the <a
458 href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow Graph</a>.
459 Since we don't have any control flow, our functions will only contain one
460 block at this point. We'll fix this in <a href="LangImpl5.html">Chapter 5</a> :).</p>
462 <div class="doc_code">
464 if (Value *RetVal = Body->Codegen()) {
465 // Finish off the function.
466 Builder.CreateRet(RetVal);
468 // Validate the generated code, checking for consistency.
469 verifyFunction(*TheFunction);
476 <p>Once the insertion point is set up, we call the <tt>CodeGen()</tt> method for
477 the root expression of the function. If no error happens, this emits code to
478 compute the expression into the entry block and returns the value that was
479 computed. Assuming no error, we then create an LLVM <a
480 href="../LangRef.html#i_ret">ret instruction</a>, which completes the function.
481 Once the function is built, we call <tt>verifyFunction</tt>, which
482 is provided by LLVM. This function does a variety of consistency checks on the
483 generated code, to determine if our compiler is doing everything right. Using
484 this is important: it can catch a lot of bugs. Once the function is finished
485 and validated, we return it.</p>
487 <div class="doc_code">
489 // Error reading body, remove function.
490 TheFunction->eraseFromParent();
496 <p>The only piece left here is handling of the error case. For simplicity, we
497 handle this by merely deleting the function we produced with the
498 <tt>eraseFromParent</tt> method. This allows the user to redefine a function
499 that they incorrectly typed in before: if we didn't delete it, it would live in
500 the symbol table, with a body, preventing future redefinition.</p>
502 <p>This code does have a bug, though. Since the <tt>PrototypeAST::Codegen</tt>
503 can return a previously defined forward declaration, our code can actually delete
504 a forward declaration. There are a number of ways to fix this bug, see what you
505 can come up with! Here is a testcase:</p>
507 <div class="doc_code">
509 extern foo(a b); # ok, defines foo.
510 def foo(a b) c; # error, 'c' is invalid.
511 def bar() foo(1, 2); # error, unknown function "foo"
517 <!-- *********************************************************************** -->
518 <h2><a name="driver">Driver Changes and Closing Thoughts</a></h2>
519 <!-- *********************************************************************** -->
524 For now, code generation to LLVM doesn't really get us much, except that we can
525 look at the pretty IR calls. The sample code inserts calls to Codegen into the
526 "<tt>HandleDefinition</tt>", "<tt>HandleExtern</tt>" etc functions, and then
527 dumps out the LLVM IR. This gives a nice way to look at the LLVM IR for simple
528 functions. For example:
531 <div class="doc_code">
534 Read top-level expression:
535 define double @""() {
537 ret double 9.000000e+00
542 <p>Note how the parser turns the top-level expression into anonymous functions
543 for us. This will be handy when we add <a href="LangImpl4.html#jit">JIT
544 support</a> in the next chapter. Also note that the code is very literally
545 transcribed, no optimizations are being performed except simple constant
546 folding done by IRBuilder. We will
547 <a href="LangImpl4.html#trivialconstfold">add optimizations</a> explicitly in
548 the next chapter.</p>
550 <div class="doc_code">
552 ready> <b>def foo(a b) a*a + 2*a*b + b*b;</b>
553 Read function definition:
554 define double @foo(double %a, double %b) {
556 %multmp = fmul double %a, %a
557 %multmp1 = fmul double 2.000000e+00, %a
558 %multmp2 = fmul double %multmp1, %b
559 %addtmp = fadd double %multmp, %multmp2
560 %multmp3 = fmul double %b, %b
561 %addtmp4 = fadd double %addtmp, %multmp3
567 <p>This shows some simple arithmetic. Notice the striking similarity to the
568 LLVM builder calls that we use to create the instructions.</p>
570 <div class="doc_code">
572 ready> <b>def bar(a) foo(a, 4.0) + bar(31337);</b>
573 Read function definition:
574 define double @bar(double %a) {
576 %calltmp = call double @foo(double %a, double 4.000000e+00)
577 %calltmp1 = call double @bar(double 3.133700e+04)
578 %addtmp = fadd double %calltmp, %calltmp1
584 <p>This shows some function calls. Note that this function will take a long
585 time to execute if you call it. In the future we'll add conditional control
586 flow to actually make recursion useful :).</p>
588 <div class="doc_code">
590 ready> <b>extern cos(x);</b>
592 declare double @cos(double)
594 ready> <b>cos(1.234);</b>
595 Read top-level expression:
596 define double @""() {
598 %calltmp = call double @cos(double 1.234000e+00)
604 <p>This shows an extern for the libm "cos" function, and a call to it.</p>
607 <div class="doc_code">
610 ; ModuleID = 'my cool jit'
612 define double @""() {
614 %addtmp = fadd double 4.000000e+00, 5.000000e+00
618 define double @foo(double %a, double %b) {
620 %multmp = fmul double %a, %a
621 %multmp1 = fmul double 2.000000e+00, %a
622 %multmp2 = fmul double %multmp1, %b
623 %addtmp = fadd double %multmp, %multmp2
624 %multmp3 = fmul double %b, %b
625 %addtmp4 = fadd double %addtmp, %multmp3
629 define double @bar(double %a) {
631 %calltmp = call double @foo(double %a, double 4.000000e+00)
632 %calltmp1 = call double @bar(double 3.133700e+04)
633 %addtmp = fadd double %calltmp, %calltmp1
637 declare double @cos(double)
639 define double @""() {
641 %calltmp = call double @cos(double 1.234000e+00)
647 <p>When you quit the current demo, it dumps out the IR for the entire module
648 generated. Here you can see the big picture with all the functions referencing
651 <p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next, we'll
652 describe how to <a href="LangImpl4.html">add JIT codegen and optimizer
653 support</a> to this so we can actually start running code!</p>
658 <!-- *********************************************************************** -->
659 <h2><a name="code">Full Code Listing</a></h2>
660 <!-- *********************************************************************** -->
665 Here is the complete code listing for our running example, enhanced with the
666 LLVM code generator. Because this uses the LLVM libraries, we need to link
667 them in. To do this, we use the <a
668 href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
669 our makefile/command line about which options to use:</p>
671 <div class="doc_code">
674 g++ -g -O3 toy.cpp `llvm-config --cppflags --ldflags --libs core` -o toy
680 <p>Here is the code:</p>
682 <div class="doc_code">
685 // See example below.
687 #include "llvm/DerivedTypes.h"
688 #include "llvm/LLVMContext.h"
689 #include "llvm/Module.h"
690 #include "llvm/Analysis/Verifier.h"
691 #include "llvm/Support/IRBuilder.h"
692 #include <cstdio>
693 #include <string>
695 #include <vector>
696 using namespace llvm;
698 //===----------------------------------------------------------------------===//
700 //===----------------------------------------------------------------------===//
702 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
703 // of these for known things.
708 tok_def = -2, tok_extern = -3,
711 tok_identifier = -4, tok_number = -5
714 static std::string IdentifierStr; // Filled in if tok_identifier
715 static double NumVal; // Filled in if tok_number
717 /// gettok - Return the next token from standard input.
718 static int gettok() {
719 static int LastChar = ' ';
721 // Skip any whitespace.
722 while (isspace(LastChar))
723 LastChar = getchar();
725 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
726 IdentifierStr = LastChar;
727 while (isalnum((LastChar = getchar())))
728 IdentifierStr += LastChar;
730 if (IdentifierStr == "def") return tok_def;
731 if (IdentifierStr == "extern") return tok_extern;
732 return tok_identifier;
735 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
739 LastChar = getchar();
740 } while (isdigit(LastChar) || LastChar == '.');
742 NumVal = strtod(NumStr.c_str(), 0);
746 if (LastChar == '#') {
747 // Comment until end of line.
748 do LastChar = getchar();
749 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
755 // Check for end of file. Don't eat the EOF.
759 // Otherwise, just return the character as its ascii value.
760 int ThisChar = LastChar;
761 LastChar = getchar();
765 //===----------------------------------------------------------------------===//
766 // Abstract Syntax Tree (aka Parse Tree)
767 //===----------------------------------------------------------------------===//
769 /// ExprAST - Base class for all expression nodes.
772 virtual ~ExprAST() {}
773 virtual Value *Codegen() = 0;
776 /// NumberExprAST - Expression class for numeric literals like "1.0".
777 class NumberExprAST : public ExprAST {
780 NumberExprAST(double val) : Val(val) {}
781 virtual Value *Codegen();
784 /// VariableExprAST - Expression class for referencing a variable, like "a".
785 class VariableExprAST : public ExprAST {
788 VariableExprAST(const std::string &name) : Name(name) {}
789 virtual Value *Codegen();
792 /// BinaryExprAST - Expression class for a binary operator.
793 class BinaryExprAST : public ExprAST {
797 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
798 : Op(op), LHS(lhs), RHS(rhs) {}
799 virtual Value *Codegen();
802 /// CallExprAST - Expression class for function calls.
803 class CallExprAST : public ExprAST {
805 std::vector<ExprAST*> Args;
807 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
808 : Callee(callee), Args(args) {}
809 virtual Value *Codegen();
812 /// PrototypeAST - This class represents the "prototype" for a function,
813 /// which captures its name, and its argument names (thus implicitly the number
814 /// of arguments the function takes).
817 std::vector<std::string> Args;
819 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
820 : Name(name), Args(args) {}
825 /// FunctionAST - This class represents a function definition itself.
830 FunctionAST(PrototypeAST *proto, ExprAST *body)
831 : Proto(proto), Body(body) {}
836 //===----------------------------------------------------------------------===//
838 //===----------------------------------------------------------------------===//
840 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
841 /// token the parser is looking at. getNextToken reads another token from the
842 /// lexer and updates CurTok with its results.
844 static int getNextToken() {
845 return CurTok = gettok();
848 /// BinopPrecedence - This holds the precedence for each binary operator that is
850 static std::map<char, int> BinopPrecedence;
852 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
853 static int GetTokPrecedence() {
854 if (!isascii(CurTok))
857 // Make sure it's a declared binop.
858 int TokPrec = BinopPrecedence[CurTok];
859 if (TokPrec <= 0) return -1;
863 /// Error* - These are little helper functions for error handling.
864 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
865 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
866 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
868 static ExprAST *ParseExpression();
872 /// ::= identifier '(' expression* ')'
873 static ExprAST *ParseIdentifierExpr() {
874 std::string IdName = IdentifierStr;
876 getNextToken(); // eat identifier.
878 if (CurTok != '(') // Simple variable ref.
879 return new VariableExprAST(IdName);
882 getNextToken(); // eat (
883 std::vector<ExprAST*> Args;
886 ExprAST *Arg = ParseExpression();
890 if (CurTok == ')') break;
893 return Error("Expected ')' or ',' in argument list");
901 return new CallExprAST(IdName, Args);
904 /// numberexpr ::= number
905 static ExprAST *ParseNumberExpr() {
906 ExprAST *Result = new NumberExprAST(NumVal);
907 getNextToken(); // consume the number
911 /// parenexpr ::= '(' expression ')'
912 static ExprAST *ParseParenExpr() {
913 getNextToken(); // eat (.
914 ExprAST *V = ParseExpression();
918 return Error("expected ')'");
919 getNextToken(); // eat ).
924 /// ::= identifierexpr
927 static ExprAST *ParsePrimary() {
929 default: return Error("unknown token when expecting an expression");
930 case tok_identifier: return ParseIdentifierExpr();
931 case tok_number: return ParseNumberExpr();
932 case '(': return ParseParenExpr();
937 /// ::= ('+' primary)*
938 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
939 // If this is a binop, find its precedence.
941 int TokPrec = GetTokPrecedence();
943 // If this is a binop that binds at least as tightly as the current binop,
944 // consume it, otherwise we are done.
945 if (TokPrec < ExprPrec)
948 // Okay, we know this is a binop.
950 getNextToken(); // eat binop
952 // Parse the primary expression after the binary operator.
953 ExprAST *RHS = ParsePrimary();
956 // If BinOp binds less tightly with RHS than the operator after RHS, let
957 // the pending operator take RHS as its LHS.
958 int NextPrec = GetTokPrecedence();
959 if (TokPrec < NextPrec) {
960 RHS = ParseBinOpRHS(TokPrec+1, RHS);
961 if (RHS == 0) return 0;
965 LHS = new BinaryExprAST(BinOp, LHS, RHS);
970 /// ::= primary binoprhs
972 static ExprAST *ParseExpression() {
973 ExprAST *LHS = ParsePrimary();
976 return ParseBinOpRHS(0, LHS);
980 /// ::= id '(' id* ')'
981 static PrototypeAST *ParsePrototype() {
982 if (CurTok != tok_identifier)
983 return ErrorP("Expected function name in prototype");
985 std::string FnName = IdentifierStr;
989 return ErrorP("Expected '(' in prototype");
991 std::vector<std::string> ArgNames;
992 while (getNextToken() == tok_identifier)
993 ArgNames.push_back(IdentifierStr);
995 return ErrorP("Expected ')' in prototype");
998 getNextToken(); // eat ')'.
1000 return new PrototypeAST(FnName, ArgNames);
1003 /// definition ::= 'def' prototype expression
1004 static FunctionAST *ParseDefinition() {
1005 getNextToken(); // eat def.
1006 PrototypeAST *Proto = ParsePrototype();
1007 if (Proto == 0) return 0;
1009 if (ExprAST *E = ParseExpression())
1010 return new FunctionAST(Proto, E);
1014 /// toplevelexpr ::= expression
1015 static FunctionAST *ParseTopLevelExpr() {
1016 if (ExprAST *E = ParseExpression()) {
1017 // Make an anonymous proto.
1018 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
1019 return new FunctionAST(Proto, E);
1024 /// external ::= 'extern' prototype
1025 static PrototypeAST *ParseExtern() {
1026 getNextToken(); // eat extern.
1027 return ParsePrototype();
1030 //===----------------------------------------------------------------------===//
1032 //===----------------------------------------------------------------------===//
1034 static Module *TheModule;
1035 static IRBuilder<> Builder(getGlobalContext());
1036 static std::map<std::string, Value*> NamedValues;
1038 Value *ErrorV(const char *Str) { Error(Str); return 0; }
1040 Value *NumberExprAST::Codegen() {
1041 return ConstantFP::get(getGlobalContext(), APFloat(Val));
1044 Value *VariableExprAST::Codegen() {
1045 // Look this variable up in the function.
1046 Value *V = NamedValues[Name];
1047 return V ? V : ErrorV("Unknown variable name");
1050 Value *BinaryExprAST::Codegen() {
1051 Value *L = LHS->Codegen();
1052 Value *R = RHS->Codegen();
1053 if (L == 0 || R == 0) return 0;
1056 case '+': return Builder.CreateFAdd(L, R, "addtmp");
1057 case '-': return Builder.CreateFSub(L, R, "subtmp");
1058 case '*': return Builder.CreateFMul(L, R, "multmp");
1060 L = Builder.CreateFCmpULT(L, R, "cmptmp");
1061 // Convert bool 0/1 to double 0.0 or 1.0
1062 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
1064 default: return ErrorV("invalid binary operator");
1068 Value *CallExprAST::Codegen() {
1069 // Look up the name in the global module table.
1070 Function *CalleeF = TheModule->getFunction(Callee);
1072 return ErrorV("Unknown function referenced");
1074 // If argument mismatch error.
1075 if (CalleeF->arg_size() != Args.size())
1076 return ErrorV("Incorrect # arguments passed");
1078 std::vector<Value*> ArgsV;
1079 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1080 ArgsV.push_back(Args[i]->Codegen());
1081 if (ArgsV.back() == 0) return 0;
1084 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
1087 Function *PrototypeAST::Codegen() {
1088 // Make the function type: double(double,double) etc.
1089 std::vector<const Type*> Doubles(Args.size(),
1090 Type::getDoubleTy(getGlobalContext()));
1091 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1094 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1096 // If F conflicted, there was already something named 'Name'. If it has a
1097 // body, don't allow redefinition or reextern.
1098 if (F->getName() != Name) {
1099 // Delete the one we just made and get the existing one.
1100 F->eraseFromParent();
1101 F = TheModule->getFunction(Name);
1103 // If F already has a body, reject this.
1104 if (!F->empty()) {
1105 ErrorF("redefinition of function");
1109 // If F took a different number of args, reject.
1110 if (F->arg_size() != Args.size()) {
1111 ErrorF("redefinition of function with different # args");
1116 // Set names for all arguments.
1118 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1120 AI->setName(Args[Idx]);
1122 // Add arguments to variable symbol table.
1123 NamedValues[Args[Idx]] = AI;
1129 Function *FunctionAST::Codegen() {
1130 NamedValues.clear();
1132 Function *TheFunction = Proto->Codegen();
1133 if (TheFunction == 0)
1136 // Create a new basic block to start insertion into.
1137 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1138 Builder.SetInsertPoint(BB);
1140 if (Value *RetVal = Body->Codegen()) {
1141 // Finish off the function.
1142 Builder.CreateRet(RetVal);
1144 // Validate the generated code, checking for consistency.
1145 verifyFunction(*TheFunction);
1150 // Error reading body, remove function.
1151 TheFunction->eraseFromParent();
1155 //===----------------------------------------------------------------------===//
1156 // Top-Level parsing and JIT Driver
1157 //===----------------------------------------------------------------------===//
1159 static void HandleDefinition() {
1160 if (FunctionAST *F = ParseDefinition()) {
1161 if (Function *LF = F->Codegen()) {
1162 fprintf(stderr, "Read function definition:");
1166 // Skip token for error recovery.
1171 static void HandleExtern() {
1172 if (PrototypeAST *P = ParseExtern()) {
1173 if (Function *F = P->Codegen()) {
1174 fprintf(stderr, "Read extern: ");
1178 // Skip token for error recovery.
1183 static void HandleTopLevelExpression() {
1184 // Evaluate a top-level expression into an anonymous function.
1185 if (FunctionAST *F = ParseTopLevelExpr()) {
1186 if (Function *LF = F->Codegen()) {
1187 fprintf(stderr, "Read top-level expression:");
1191 // Skip token for error recovery.
1196 /// top ::= definition | external | expression | ';'
1197 static void MainLoop() {
1199 fprintf(stderr, "ready> ");
1201 case tok_eof: return;
1202 case ';': getNextToken(); break; // ignore top-level semicolons.
1203 case tok_def: HandleDefinition(); break;
1204 case tok_extern: HandleExtern(); break;
1205 default: HandleTopLevelExpression(); break;
1210 //===----------------------------------------------------------------------===//
1211 // "Library" functions that can be "extern'd" from user code.
1212 //===----------------------------------------------------------------------===//
1214 /// putchard - putchar that takes a double and returns 0.
1216 double putchard(double X) {
1221 //===----------------------------------------------------------------------===//
1222 // Main driver code.
1223 //===----------------------------------------------------------------------===//
1226 LLVMContext &Context = getGlobalContext();
1228 // Install standard binary operators.
1229 // 1 is lowest precedence.
1230 BinopPrecedence['<'] = 10;
1231 BinopPrecedence['+'] = 20;
1232 BinopPrecedence['-'] = 20;
1233 BinopPrecedence['*'] = 40; // highest.
1235 // Prime the first token.
1236 fprintf(stderr, "ready> ");
1239 // Make the module, which holds all the code.
1240 TheModule = new Module("my cool jit", Context);
1242 // Run the main "interpreter loop" now.
1245 // Print out all of the generated code.
1246 TheModule->dump();
1252 <a href="LangImpl4.html">Next: Adding JIT and Optimizer Support</a>
1255 <!-- *********************************************************************** -->
1258 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1259 src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1260 <a href="http://validator.w3.org/check/referer"><img
1261 src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1263 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1264 <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
1265 Last modified: $Date$