Install the PNG file as well. PR4780.
[oota-llvm.git] / docs / tutorial / LangImpl7.html
index 9aa65d3b6e126bf74905ad9289961c9801883596..29b920c13bcd4c8f4d8cca84f76853f8c543f5e5 100644 (file)
@@ -12,7 +12,7 @@
 
 <body>
 
-<div class="doc_title">Kaleidoscope: Extending the Language: Mutable Variables</div>
+<h1>Kaleidoscope: Extending the Language: Mutable Variables</h1>
 
 <ul>
 <li><a href="index.html">Up to Tutorial Index</a></li>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="intro">Chapter 7 Introduction</a></div>
+<h2><a name="intro">Chapter 7 Introduction</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>Welcome to Chapter 7 of the "<a href="index.html">Implementing a language
 with LLVM</a>" tutorial.  In chapters 1 through 6, we've built a very
@@ -49,11 +49,11 @@ respectable, albeit simple, <a
 href="http://en.wikipedia.org/wiki/Functional_programming">functional
 programming language</a>.  In our journey, we learned some parsing techniques,
 how to build and represent an AST, how to build LLVM IR, and how to optimize
-the resultant code and JIT compile it.</p>
+the resultant code as well as JIT compile it.</p>
 
-<p>While Kaleidoscope is interesting as a functional language, this makes it 
-"too easy" to generate LLVM IR for it.  In particular, a functional language
-makes it very easy to build LLVM IR directly in <a 
+<p>While Kaleidoscope is interesting as a functional language, the fact that it
+is functional makes it "too easy" to generate LLVM IR for it.  In particular, a 
+functional language makes it very easy to build LLVM IR directly in <a 
 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">SSA form</a>.
 Since LLVM requires that the input code be in SSA form, this is a very nice
 property and it is often unclear to newcomers how to generate code for an
@@ -66,10 +66,10 @@ support for this, though the way it works is a bit unexpected for some.</p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="why">Why is this a hard problem?</a></div>
+<h2><a name="why">Why is this a hard problem?</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>
 To understand why mutable variables cause complexities in SSA construction, 
@@ -102,19 +102,19 @@ The LLVM IR that we want for this example looks like this:</p>
 
 define i32 @test(i1 %Condition) {
 entry:
-       br i1 %Condition, label %cond_true, label %cond_false
+  br i1 %Condition, label %cond_true, label %cond_false
 
 cond_true:
-       %X.0 = load i32* @G
-       br label %cond_next
+  %X.0 = load i32* @G
+  br label %cond_next
 
 cond_false:
-       %X.1 = load i32* @H
-       br label %cond_next
+  %X.1 = load i32* @H
+  br label %cond_next
 
 cond_next:
-       %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
-       ret i32 %X.2
+  %X.2 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+  ret i32 %X.2
 }
 </pre>
 </div>
@@ -124,13 +124,13 @@ the LLVM IR, and they live in the then/else branches of the if statement
 (cond_true/cond_false).  In order to merge the incoming values, the X.2 phi node
 in the cond_next block selects the right value to use based on where control 
 flow is coming from: if control flow comes from the cond_false block, X.2 gets
-the value of X.1.  Alternatively, if control flow comes from cond_tree, it gets
+the value of X.1.  Alternatively, if control flow comes from cond_true, it gets
 the value of X.0.  The intent of this chapter is not to explain the details of
 SSA form.  For more information, see one of the many <a 
 href="http://en.wikipedia.org/wiki/Static_single_assignment_form">online 
 references</a>.</p>
 
-<p>The question for this article is "who places phi nodes when lowering 
+<p>The question for this article is "who places the phi nodes when lowering 
 assignments to mutable variables?".  The issue here is that LLVM 
 <em>requires</em> that its IR be in SSA form: there is no "non-ssa" mode for it.
 However, SSA construction requires non-trivial algorithms and data structures,
@@ -140,10 +140,10 @@ logic.</p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="memory">Memory in LLVM</a></div>
+<h2><a name="memory">Memory in LLVM</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>The 'trick' here is that while LLVM does require all register values to be
 in SSA form, it does not require (or permit) memory objects to be in SSA form.
@@ -162,24 +162,24 @@ represents stack variables.
 </p>
 
 <p>In LLVM, all memory accesses are explicit with load/store instructions, and
-it is carefully designed to not have (or need) an "address-of" operator.  Notice
+it is carefully designed not to have (or need) an "address-of" operator.  Notice
 how the type of the @G/@H global variables is actually "i32*" even though the 
 variable is defined as "i32".  What this means is that @G defines <em>space</em>
 for an i32 in the global data area, but its <em>name</em> actually refers to the
-address for that space.  Stack variables work the same way, but instead of being
-declared with global variable definitions, they are declared with the 
+address for that space.  Stack variables work the same way, except that instead of 
+being declared with global variable definitions, they are declared with the 
 <a href="../LangRef.html#i_alloca">LLVM alloca instruction</a>:</p>
 
 <div class="doc_code">
 <pre>
-define i32 @test(i1 %Condition) {
+define i32 @example() {
 entry:
-       %X = alloca i32           ; type of %X is i32*.
-       ...
-       %tmp = load i32* %X       ; load the stack value %X from the stack.
-       %tmp2 = add i32 %tmp, 1   ; increment it
-       store i32 %tmp2, i32* %X  ; store it back
-       ...
+  %X = alloca i32           ; type of %X is i32*.
+  ...
+  %tmp = load i32* %X       ; load the stack value %X from the stack.
+  %tmp2 = add i32 %tmp, 1   ; increment it
+  store i32 %tmp2, i32* %X  ; store it back
+  ...
 </pre>
 </div>
 
@@ -196,22 +196,22 @@ example to use the alloca technique to avoid using a PHI node:</p>
 
 define i32 @test(i1 %Condition) {
 entry:
-       %X = alloca i32           ; type of %X is i32*.
-       br i1 %Condition, label %cond_true, label %cond_false
+  %X = alloca i32           ; type of %X is i32*.
+  br i1 %Condition, label %cond_true, label %cond_false
 
 cond_true:
-       %X.0 = load i32* @G
-        store i32 %X.0, i32* %X   ; Update X
-       br label %cond_next
+  %X.0 = load i32* @G
+  store i32 %X.0, i32* %X   ; Update X
+  br label %cond_next
 
 cond_false:
-       %X.1 = load i32* @H
-        store i32 %X.1, i32* %X   ; Update X
-       br label %cond_next
+  %X.1 = load i32* @H
+  store i32 %X.1, i32* %X   ; Update X
+  br label %cond_next
 
 cond_next:
-       %X.2 = load i32* %X       ; Read X
-       ret i32 %X.2
+  %X.2 = load i32* %X       ; Read X
+  ret i32 %X.2
 }
 </pre>
 </div>
@@ -242,27 +242,27 @@ $ <b>llvm-as &lt; example.ll | opt -mem2reg | llvm-dis</b>
 
 define i32 @test(i1 %Condition) {
 entry:
-       br i1 %Condition, label %cond_true, label %cond_false
+  br i1 %Condition, label %cond_true, label %cond_false
 
 cond_true:
-       %X.0 = load i32* @G
-       br label %cond_next
+  %X.0 = load i32* @G
+  br label %cond_next
 
 cond_false:
-       %X.1 = load i32* @H
-       br label %cond_next
+  %X.1 = load i32* @H
+  br label %cond_next
 
 cond_next:
-       %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
-       ret i32 %X.01
+  %X.01 = phi i32 [ %X.1, %cond_false ], [ %X.0, %cond_true ]
+  ret i32 %X.01
 }
 </pre>
 </div>
 
-<p>The mem2reg pass implements the standard "iterated dominator frontier"
+<p>The mem2reg pass implements the standard "iterated dominance frontier"
 algorithm for constructing SSA form and has a number of optimizations that speed
-up very common degenerate cases.  mem2reg really is the answer for dealing with
-mutable variables, and we highly recommend that you depend on it.  Note that
+up (very common) degenerate cases. The mem2reg optimization pass is the answer to dealing 
+with mutable variables, and we highly recommend that you depend on it.  Note that
 mem2reg only works on variables in certain circumstances:</p>
 
 <ol>
@@ -288,10 +288,10 @@ more powerful and can promote structs, "unions", and arrays in many cases.</li>
 
 <p>
 All of these properties are easy to satisfy for most imperative languages, and
-we'll illustrate this below with Kaleidoscope.  The final question you may be
+we'll illustrate it below with Kaleidoscope.  The final question you may be
 asking is: should I bother with this nonsense for my front-end?  Wouldn't it be
 better if I just did SSA construction directly, avoiding use of the mem2reg
-optimization pass?  In short, we strongly recommend that use you this technique
+optimization pass?  In short, we strongly recommend that you use this technique
 for building SSA form, unless there is an extremely good reason not to.  Using
 this technique is:</p>
 
@@ -309,8 +309,8 @@ assignment point, good heuristics to avoid insertion of unneeded phi nodes, etc.
 
 <li>Needed for debug info generation: <a href="../SourceLevelDebugging.html">
 Debug information in LLVM</a> relies on having the address of the variable
-exposed to attach debug info to it.  This technique dovetails very naturally 
-with this style of debug info.</li>
+exposed so that debug info can be attached to it.  This technique dovetails 
+very naturally with this style of debug info.</li>
 </ul>
 
 <p>If nothing else, this makes it much easier to get your front-end up and 
@@ -321,11 +321,10 @@ variables now!
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="kalvars">Mutable Variables in 
-Kaleidoscope</a></div>
+<h2><a name="kalvars">Mutable Variables in Kaleidoscope</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>Now that we know the sort of problem we want to tackle, lets see what this
 looks like in the context of our little Kaleidoscope language.  We're going to
@@ -337,7 +336,7 @@ add two features:</p>
 </ol>
 
 <p>While the first item is really what this is about, we only have variables
-for incoming arguments and for induction variables, and redefining them only
+for incoming arguments as well as for induction variables, and redefining those only
 goes so far :).  Also, the ability to define new variables is a
 useful thing regardless of whether you will be mutating them.  Here's a
 motivating example that shows how we could use these:</p>
@@ -358,7 +357,7 @@ def fib(x)
 # Iterative fib.
 def fibi(x)
   <b>var a = 1, b = 1, c in</b>
-  (for i = 3, i &;t; x in 
+  (for i = 3, i &lt; x in 
      <b>c = a + b</b> :
      <b>a = b</b> :
      <b>b = c</b>) :
@@ -378,11 +377,10 @@ Kaleidoscope to support new variable definitions.
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="adjustments">Adjusting Existing Variables for
-Mutation</a></div>
+<h2><a name="adjustments">Adjusting Existing Variables for Mutation</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>
 The symbol table in Kaleidoscope is managed at code generation time by the 
@@ -403,8 +401,8 @@ locations.
 </p>
 
 <p>To start our transformation of Kaleidoscope, we'll change the NamedValues
-map to map to AllocaInst* instead of Value*.  Once we do this, the C++ compiler
-will tell use what parts of the code we need to update:</p>
+map so that it maps to AllocaInst* instead of Value*.  Once we do this, the C++ 
+compiler will tell us what parts of the code we need to update:</p>
 
 <div class="doc_code">
 <pre>
@@ -422,14 +420,15 @@ function:</p>
 /// the function.  This is used for mutable variables etc.
 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
                                           const std::string &amp;VarName) {
-  LLVMBuilder TmpB(&amp;TheFunction-&gt;getEntryBlock(),
-                   TheFunction-&gt;getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
+  IRBuilder&lt;&gt; TmpB(&amp;TheFunction-&gt;getEntryBlock(),
+                 TheFunction-&gt;getEntryBlock().begin());
+  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+                           VarName.c_str());
 }
 </pre>
 </div>
 
-<p>This funny looking code creates an LLVMBuilder object that is pointing at
+<p>This funny looking code creates an IRBuilder object that is pointing at
 the first instruction (.begin()) of the entry block.  It then creates an alloca
 with the expected name and returns it.  Because all values in Kaleidoscope are
 doubles, there is no need to pass in a type to use.</p>
@@ -446,13 +445,13 @@ Value *VariableExprAST::Codegen() {
   Value *V = NamedValues[Name];
   if (V == 0) return ErrorV("Unknown variable name");
 
-  // Load the value.
-  return Builder.CreateLoad(V, Name.c_str());
+  <b>// Load the value.
+  return Builder.CreateLoad(V, Name.c_str());</b>
 }
 </pre>
 </div>
 
-<p>As you can see, this is pretty straight-forward.  Next we need to update the
+<p>As you can see, this is pretty straightforward.  Now we need to update the
 things that define the variables to set up the alloca.  We'll start with 
 <tt>ForExprAST::Codegen</tt> (see the <a href="#code">full code listing</a> for
 the unabridged code):</p>
@@ -479,7 +478,7 @@ the unabridged code):</p>
   <b>// Reload, increment, and restore the alloca.  This handles the case where
   // the body of the loop mutates the variable.
   Value *CurVar = Builder.CreateLoad(Alloca);
-  Value *NextVar = Builder.CreateAdd(CurVar, StepVal, "nextvar");
+  Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
   Builder.CreateStore(NextVar, Alloca);</b>
   ...
 </pre>
@@ -518,7 +517,7 @@ into the alloca, and register the alloca as the memory location for the
 argument.  This method gets invoked by <tt>FunctionAST::Codegen</tt> right after
 it sets up the entry block for the function.</p>
 
-<p>The final missing piece is adding the 'mem2reg' pass, which allows us to get
+<p>The final missing piece is adding the mem2reg pass, which allows us to get
 good codegen once again:</p>
 
 <div class="doc_code">
@@ -537,36 +536,36 @@ good codegen once again:</p>
 
 <p>It is interesting to see what the code looks like before and after the
 mem2reg optimization runs.  For example, this is the before/after code for our
-recursive fib.  Before the optimization:</p>
+recursive fib function.  Before the optimization:</p>
 
 <div class="doc_code">
 <pre>
 define double @fib(double %x) {
 entry:
-       <b>%x1 = alloca double
-       store double %x, double* %x1
-       %x2 = load double* %x1</b>
-       %cmptmp = fcmp ult double %x2, 3.000000e+00
-       %booltmp = uitofp i1 %cmptmp to double
-       %ifcond = fcmp one double %booltmp, 0.000000e+00
-       br i1 %ifcond, label %then, label %else
+  <b>%x1 = alloca double
+  store double %x, double* %x1
+  %x2 = load double* %x1</b>
+  %cmptmp = fcmp ult double %x2, 3.000000e+00
+  %booltmp = uitofp i1 %cmptmp to double
+  %ifcond = fcmp one double %booltmp, 0.000000e+00
+  br i1 %ifcond, label %then, label %else
 
 then:          ; preds = %entry
-       br label %ifcont
+  br label %ifcont
 
 else:          ; preds = %entry
-       <b>%x3 = load double* %x1</b>
-       %subtmp = sub double %x3, 1.000000e+00
-       %calltmp = call double @fib( double %subtmp )
-       <b>%x4 = load double* %x1</b>
-       %subtmp5 = sub double %x4, 2.000000e+00
-       %calltmp6 = call double @fib( double %subtmp5 )
-       %addtmp = add double %calltmp, %calltmp6
-       br label %ifcont
+  <b>%x3 = load double* %x1</b>
+  %subtmp = fsub double %x3, 1.000000e+00
+  %calltmp = call double @fib(double %subtmp)
+  <b>%x4 = load double* %x1</b>
+  %subtmp5 = fsub double %x4, 2.000000e+00
+  %calltmp6 = call double @fib(double %subtmp5)
+  %addtmp = fadd double %calltmp, %calltmp6
+  br label %ifcont
 
 ifcont:                ; preds = %else, %then
-       %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
-       ret double %iftmp
+  %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+  ret double %iftmp
 }
 </pre>
 </div>
@@ -585,25 +584,25 @@ PHI node for it, so we still just make the PHI.</p>
 <pre>
 define double @fib(double %x) {
 entry:
-       %cmptmp = fcmp ult double <b>%x</b>, 3.000000e+00
-       %booltmp = uitofp i1 %cmptmp to double
-       %ifcond = fcmp one double %booltmp, 0.000000e+00
-       br i1 %ifcond, label %then, label %else
+  %cmptmp = fcmp ult double <b>%x</b>, 3.000000e+00
+  %booltmp = uitofp i1 %cmptmp to double
+  %ifcond = fcmp one double %booltmp, 0.000000e+00
+  br i1 %ifcond, label %then, label %else
 
 then:
-       br label %ifcont
+  br label %ifcont
 
 else:
-       %subtmp = sub double <b>%x</b>, 1.000000e+00
-       %calltmp = call double @fib( double %subtmp )
-       %subtmp5 = sub double <b>%x</b>, 2.000000e+00
-       %calltmp6 = call double @fib( double %subtmp5 )
-       %addtmp = add double %calltmp, %calltmp6
-       br label %ifcont
+  %subtmp = fsub double <b>%x</b>, 1.000000e+00
+  %calltmp = call double @fib(double %subtmp)
+  %subtmp5 = fsub double <b>%x</b>, 2.000000e+00
+  %calltmp6 = call double @fib(double %subtmp5)
+  %addtmp = fadd double %calltmp, %calltmp6
+  br label %ifcont
 
 ifcont:                ; preds = %else, %then
-       %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
-       ret double %iftmp
+  %iftmp = phi double [ 1.000000e+00, %then ], [ %addtmp, %else ]
+  ret double %iftmp
 }
 </pre>
 </div>
@@ -618,21 +617,21 @@ such blatent inefficiencies :).</p>
 <pre>
 define double @fib(double %x) {
 entry:
-       %cmptmp = fcmp ult double %x, 3.000000e+00
-       %booltmp = uitofp i1 %cmptmp to double
-       %ifcond = fcmp ueq double %booltmp, 0.000000e+00
-       br i1 %ifcond, label %else, label %ifcont
+  %cmptmp = fcmp ult double %x, 3.000000e+00
+  %booltmp = uitofp i1 %cmptmp to double
+  %ifcond = fcmp ueq double %booltmp, 0.000000e+00
+  br i1 %ifcond, label %else, label %ifcont
 
 else:
-       %subtmp = sub double %x, 1.000000e+00
-       %calltmp = call double @fib( double %subtmp )
-       %subtmp5 = sub double %x, 2.000000e+00
-       %calltmp6 = call double @fib( double %subtmp5 )
-       %addtmp = add double %calltmp, %calltmp6
-       ret double %addtmp
+  %subtmp = fsub double %x, 1.000000e+00
+  %calltmp = call double @fib(double %subtmp)
+  %subtmp5 = fsub double %x, 2.000000e+00
+  %calltmp6 = call double @fib(double %subtmp5)
+  %addtmp = fadd double %calltmp, %calltmp6
+  ret double %addtmp
 
 ifcont:
-       ret double 1.000000e+00
+  ret double 1.000000e+00
 }
 </pre>
 </div>
@@ -647,10 +646,10 @@ we'll add the assignment operator.</p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="assignment">New Assignment Operator</a></div>
+<h2><a name="assignment">New Assignment Operator</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>With our current framework, adding a new assignment operator is really
 simple.  We will parse it just like any other binary operator, but handle it
@@ -688,7 +687,8 @@ Value *BinaryExprAST::Codegen() {
 <p>Unlike the rest of the binary operators, our assignment operator doesn't
 follow the "emit LHS, emit RHS, do computation" model.  As such, it is handled
 as a special case before the other binary operators are handled.  The other 
-strange thing about it is that it requires the LHS to be a variable directly.
+strange thing is that it requires the LHS to be a variable.  It is invalid to
+have "(x+1) = expr" - only things like "x = expr" are allowed.
 </p>
 
 <div class="doc_code">
@@ -708,7 +708,7 @@ strange thing about it is that it requires the LHS to be a variable directly.
 </pre>
 </div>
 
-<p>Once it has the variable, codegen'ing the assignment is straight-forward:
+<p>Once we have the variable, codegen'ing the assignment is straightforward:
 we emit the RHS of the assignment, create a store, and return the computed
 value.  Returning a value allows for chained assignments like "X = (Y = Z)".</p>
 
@@ -743,11 +743,10 @@ add this next!
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="localvars">User-defined Local 
-Variables</a></div>
+<h2><a name="localvars">User-defined Local Variables</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>Adding var/in is just like any other other extensions we made to 
 Kaleidoscope: we extend the lexer, the parser, the AST and the code generator.
@@ -775,7 +774,7 @@ static int gettok() {
 </div>
 
 <p>The next step is to define the AST node that we will construct.  For var/in,
-it will look like this:</p>
+it looks like this:</p>
 
 <div class="doc_code">
 <pre>
@@ -796,9 +795,9 @@ public:
 <p>var/in allows a list of names to be defined all at once, and each name can
 optionally have an initializer value.  As such, we capture this information in
 the VarNames vector.  Also, var/in has a body, this body is allowed to access
-the variables defined by the let/in.</p>
+the variables defined by the var/in.</p>
 
-<p>With this ready, we can define the parser pieces.  First thing we do is add
+<p>With this in place, we can define the parser pieces.  The first thing we do is add
 it as a primary expression:</p>
 
 <div class="doc_code">
@@ -922,7 +921,7 @@ that we replace in OldBindings.</p>
       InitVal = Init-&gt;Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(Type::DoubleTy, APFloat(0.0));
+      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
     }
     
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -971,16 +970,16 @@ definitions, and we even (trivially) allow mutation of them :).</p>
 <p>With this, we completed what we set out to do.  Our nice iterative fib
 example from the intro compiles and runs just fine.  The mem2reg pass optimizes
 all of our stack variables into SSA registers, inserting PHI nodes where needed,
-and our front-end remains simple: no iterated dominator frontier computation
+and our front-end remains simple: no "iterated dominance frontier" computation
 anywhere in sight.</p>
 
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="code">Full Code Listing</a></div>
+<h2><a name="code">Full Code Listing</a></h2>
 <!-- *********************************************************************** -->
 
-<div class="doc_text">
+<div>
 
 <p>
 Here is the complete code listing for our running example, enhanced with mutable
@@ -989,10 +988,10 @@ variables and var/in support.  To build this example, use:
 
 <div class="doc_code">
 <pre>
-   # Compile
-   g++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
-   # Run
-   ./toy
+# Compile
+clang++ -g toy.cpp `llvm-config --cppflags --ldflags --libs core jit native` -O3 -o toy
+# Run
+./toy
 </pre>
 </div>
 
@@ -1002,13 +1001,16 @@ variables and var/in support.  To build this example, use:
 <pre>
 #include "llvm/DerivedTypes.h"
 #include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
-#include "llvm/ModuleProvider.h"
 #include "llvm/PassManager.h"
 #include "llvm/Analysis/Verifier.h"
+#include "llvm/Analysis/Passes.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Transforms/Scalar.h"
-#include "llvm/Support/LLVMBuilder.h"
+#include "llvm/Support/IRBuilder.h"
+#include "llvm/Support/TargetSelect.h"
 #include &lt;cstdio&gt;
 #include &lt;string&gt;
 #include &lt;map&gt;
@@ -1084,7 +1086,7 @@ static int gettok() {
   if (LastChar == '#') {
     // Comment until end of line.
     do LastChar = getchar();
-    while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp; LastChar != '\r');
+    while (LastChar != EOF &amp;&amp; LastChar != '\n' &amp;&amp; LastChar != '\r');
     
     if (LastChar != EOF)
       return gettok();
@@ -1191,7 +1193,8 @@ public:
 };
 
 /// PrototypeAST - This class represents the "prototype" for a function,
-/// which captures its argument names as well as if it is an operator.
+/// which captures its name, and its argument names (thus implicitly the number
+/// of arguments the function takes), as well as if it is an operator.
 class PrototypeAST {
   std::string Name;
   std::vector&lt;std::string&gt; Args;
@@ -1233,7 +1236,7 @@ public:
 //===----------------------------------------------------------------------===//
 
 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
-/// token the parser it looking at.  getNextToken reads another token from the
+/// token the parser is looking at.  getNextToken reads another token from the
 /// lexer and updates CurTok with its results.
 static int CurTok;
 static int getNextToken() {
@@ -1281,11 +1284,11 @@ static ExprAST *ParseIdentifierExpr() {
       ExprAST *Arg = ParseExpression();
       if (!Arg) return 0;
       Args.push_back(Arg);
-      
+
       if (CurTok == ')') break;
-      
+
       if (CurTok != ',')
-        return Error("Expected ')'");
+        return Error("Expected ')' or ',' in argument list");
       getNextToken();
     }
   }
@@ -1428,7 +1431,6 @@ static ExprAST *ParseVarExpr() {
   return new VarExprAST(VarNames, Body);
 }
 
-
 /// primary
 ///   ::= identifierexpr
 ///   ::= numberexpr
@@ -1514,7 +1516,7 @@ static ExprAST *ParseExpression() {
 static PrototypeAST *ParsePrototype() {
   std::string FnName;
   
-  int Kind = 0;  // 0 = identifier, 1 = unary, 2 = binary.
+  unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
   unsigned BinaryPrecedence = 30;
   
   switch (CurTok) {
@@ -1604,7 +1606,7 @@ static PrototypeAST *ParseExtern() {
 //===----------------------------------------------------------------------===//
 
 static Module *TheModule;
-static LLVMFoldingBuilder Builder;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
 static std::map&lt;std::string, AllocaInst*&gt; NamedValues;
 static FunctionPassManager *TheFPM;
 
@@ -1614,14 +1616,14 @@ Value *ErrorV(const char *Str) { Error(Str); return 0; }
 /// the function.  This is used for mutable variables etc.
 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
                                           const std::string &amp;VarName) {
-  LLVMBuilder TmpB(&amp;TheFunction-&gt;getEntryBlock(),
-                   TheFunction-&gt;getEntryBlock().begin());
-  return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
+  IRBuilder&lt;&gt; TmpB(&amp;TheFunction-&gt;getEntryBlock(),
+                 TheFunction-&gt;getEntryBlock().begin());
+  return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
+                           VarName.c_str());
 }
 
-
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(Type::DoubleTy, APFloat(Val));
+  return ConstantFP::get(getGlobalContext(), APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -1644,7 +1646,6 @@ Value *UnaryExprAST::Codegen() {
   return Builder.CreateCall(F, OperandV, "unop");
 }
 
-
 Value *BinaryExprAST::Codegen() {
   // Special case '=' because we don't want to emit the LHS as an expression.
   if (Op == '=') {
@@ -1664,19 +1665,19 @@ Value *BinaryExprAST::Codegen() {
     return Val;
   }
   
-  
   Value *L = LHS-&gt;Codegen();
   Value *R = RHS-&gt;Codegen();
   if (L == 0 || R == 0) return 0;
   
   switch (Op) {
-  case '+': return Builder.CreateAdd(L, R, "addtmp");
-  case '-': return Builder.CreateSub(L, R, "subtmp");
-  case '*': return Builder.CreateMul(L, R, "multmp");
+  case '+': return Builder.CreateFAdd(L, R, "addtmp");
+  case '-': return Builder.CreateFSub(L, R, "subtmp");
+  case '*': return Builder.CreateFMul(L, R, "multmp");
   case '&lt;':
     L = Builder.CreateFCmpULT(L, R, "cmptmp");
     // Convert bool 0/1 to double 0.0 or 1.0
-    return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
+    return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
+                                "booltmp");
   default: break;
   }
   
@@ -1685,8 +1686,8 @@ Value *BinaryExprAST::Codegen() {
   Function *F = TheModule-&gt;getFunction(std::string("binary")+Op);
   assert(F &amp;&amp; "binary operator not found!");
   
-  Value *Ops[] = { L, R };
-  return Builder.CreateCall(F, Ops, Ops+2, "binop");
+  Value *Ops[2] = { L, R };
+  return Builder.CreateCall(F, Ops, "binop");
 }
 
 Value *CallExprAST::Codegen() {
@@ -1705,7 +1706,7 @@ Value *CallExprAST::Codegen() {
     if (ArgsV.back() == 0) return 0;
   }
   
-  return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
+  return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
 }
 
 Value *IfExprAST::Codegen() {
@@ -1714,16 +1715,16 @@ Value *IfExprAST::Codegen() {
   
   // Convert condition to a bool by comparing equal to 0.0.
   CondV = Builder.CreateFCmpONE(CondV, 
-                                ConstantFP::get(Type::DoubleTy, APFloat(0.0)),
+                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
                                 "ifcond");
   
   Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
   
   // Create blocks for the then and else cases.  Insert the 'then' block at the
   // end of the function.
-  BasicBlock *ThenBB = new BasicBlock("then", TheFunction);
-  BasicBlock *ElseBB = new BasicBlock("else");
-  BasicBlock *MergeBB = new BasicBlock("ifcont");
+  BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
+  BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
+  BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
   
   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
   
@@ -1751,7 +1752,8 @@ Value *IfExprAST::Codegen() {
   // Emit merge block.
   TheFunction-&gt;getBasicBlockList().push_back(MergeBB);
   Builder.SetInsertPoint(MergeBB);
-  PHINode *PN = Builder.CreatePHI(Type::DoubleTy, "iftmp");
+  PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
+                                  "iftmp");
   
   PN-&gt;addIncoming(ThenV, ThenBB);
   PN-&gt;addIncoming(ElseV, ElseBB);
@@ -1793,8 +1795,7 @@ Value *ForExprAST::Codegen() {
   
   // Make the new basic block for the loop header, inserting after current
   // block.
-  BasicBlock *PreheaderBB = Builder.GetInsertBlock();
-  BasicBlock *LoopBB = new BasicBlock("loop", TheFunction);
+  BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
   
   // Insert an explicit fall through from the current block to the LoopBB.
   Builder.CreateBr(LoopBB);
@@ -1820,7 +1821,7 @@ Value *ForExprAST::Codegen() {
     if (StepVal == 0) return 0;
   } else {
     // If not specified, use 1.0.
-    StepVal = ConstantFP::get(Type::DoubleTy, APFloat(1.0));
+    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
   }
   
   // Compute the end condition.
@@ -1830,17 +1831,16 @@ Value *ForExprAST::Codegen() {
   // Reload, increment, and restore the alloca.  This handles the case where
   // the body of the loop mutates the variable.
   Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
-  Value *NextVar = Builder.CreateAdd(CurVar, StepVal, "nextvar");
+  Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
   Builder.CreateStore(NextVar, Alloca);
   
   // Convert condition to a bool by comparing equal to 0.0.
   EndCond = Builder.CreateFCmpONE(EndCond, 
-                                  ConstantFP::get(Type::DoubleTy, APFloat(0.0)),
+                              ConstantFP::get(getGlobalContext(), APFloat(0.0)),
                                   "loopcond");
   
   // Create the "after loop" block and insert it.
-  BasicBlock *LoopEndBB = Builder.GetInsertBlock();
-  BasicBlock *AfterBB = new BasicBlock("afterloop", TheFunction);
+  BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
   
   // Insert the conditional branch into the end of LoopEndBB.
   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@@ -1856,7 +1856,7 @@ Value *ForExprAST::Codegen() {
 
   
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::DoubleTy);
+  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
 }
 
 Value *VarExprAST::Codegen() {
@@ -1879,7 +1879,7 @@ Value *VarExprAST::Codegen() {
       InitVal = Init-&gt;Codegen();
       if (InitVal == 0) return 0;
     } else { // If not specified, use 0.0.
-      InitVal = ConstantFP::get(Type::DoubleTy, APFloat(0.0));
+      InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
     }
     
     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
@@ -1905,13 +1905,14 @@ Value *VarExprAST::Codegen() {
   return BodyVal;
 }
 
-
 Function *PrototypeAST::Codegen() {
   // Make the function type:  double(double,double) etc.
-  std::vector&lt;const Type*&gt; Doubles(Args.size(), Type::DoubleTy);
-  FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
+  std::vector&lt;Type*&gt; Doubles(Args.size(),
+                             Type::getDoubleTy(getGlobalContext()));
+  FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
+                                       Doubles, false);
   
-  Function *F = new Function(FT, Function::ExternalLinkage, Name, TheModule);
+  Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
   
   // If F conflicted, there was already something named 'Name'.  If it has a
   // body, don't allow redefinition or reextern.
@@ -1958,7 +1959,6 @@ void PrototypeAST::CreateArgumentAllocas(Function *F) {
   }
 }
 
-
 Function *FunctionAST::Codegen() {
   NamedValues.clear();
   
@@ -1971,12 +1971,12 @@ Function *FunctionAST::Codegen() {
     BinopPrecedence[Proto-&gt;getOperatorName()] = Proto-&gt;getBinaryPrecedence();
   
   // Create a new basic block to start insertion into.
-  BasicBlock *BB = new BasicBlock("entry", TheFunction);
+  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
   Builder.SetInsertPoint(BB);
   
   // Add all arguments to the symbol table and create their allocas.
   Proto-&gt;CreateArgumentAllocas(TheFunction);
-  
+
   if (Value *RetVal = Body-&gt;Codegen()) {
     // Finish off the function.
     Builder.CreateRet(RetVal);
@@ -2029,7 +2029,7 @@ static void HandleExtern() {
 }
 
 static void HandleTopLevelExpression() {
-  // Evaluate a top level expression into an anonymous function.
+  // Evaluate a top-level expression into an anonymous function.
   if (FunctionAST *F = ParseTopLevelExpr()) {
     if (Function *LF = F-&gt;Codegen()) {
       // JIT the function, returning a function pointer.
@@ -2037,7 +2037,7 @@ static void HandleTopLevelExpression() {
       
       // Cast it to the right type (takes no arguments, returns a double) so we
       // can call it as a native function.
-      double (*FP)() = (double (*)())FPtr;
+      double (*FP)() = (double (*)())(intptr_t)FPtr;
       fprintf(stderr, "Evaluated to %f\n", FP());
     }
   } else {
@@ -2052,7 +2052,7 @@ static void MainLoop() {
     fprintf(stderr, "ready&gt; ");
     switch (CurTok) {
     case tok_eof:    return;
-    case ';':        getNextToken(); break;  // ignore top level semicolons.
+    case ';':        getNextToken(); break;  // ignore top-level semicolons.
     case tok_def:    HandleDefinition(); break;
     case tok_extern: HandleExtern(); break;
     default:         HandleTopLevelExpression(); break;
@@ -2060,8 +2060,6 @@ static void MainLoop() {
   }
 }
 
-
-
 //===----------------------------------------------------------------------===//
 // "Library" functions that can be "extern'd" from user code.
 //===----------------------------------------------------------------------===//
@@ -2085,6 +2083,9 @@ double printd(double X) {
 //===----------------------------------------------------------------------===//
 
 int main() {
+  InitializeNativeTarget();
+  LLVMContext &amp;Context = getGlobalContext();
+
   // Install standard binary operators.
   // 1 is lowest precedence.
   BinopPrecedence['='] = 2;
@@ -2098,46 +2099,53 @@ int main() {
   getNextToken();
 
   // Make the module, which holds all the code.
-  TheModule = new Module("my cool jit");
-  
-  // Create the JIT.
-  TheExecutionEngine = ExecutionEngine::create(TheModule);
+  TheModule = new Module("my cool jit", Context);
+
+  // Create the JIT.  This takes ownership of the module.
+  std::string ErrStr;
+  TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&amp;ErrStr).create();
+  if (!TheExecutionEngine) {
+    fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+    exit(1);
+  }
 
-  {
-    ExistingModuleProvider OurModuleProvider(TheModule);
-    FunctionPassManager OurFPM(&amp;OurModuleProvider);
-      
-    // Set up the optimizer pipeline.  Start with registering info about how the
-    // target lays out data structures.
-    OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
-    // Promote allocas to registers.
-    OurFPM.add(createPromoteMemoryToRegisterPass());
-    // Do simple "peephole" optimizations and bit-twiddling optzns.
-    OurFPM.add(createInstructionCombiningPass());
-    // Reassociate expressions.
-    OurFPM.add(createReassociatePass());
-    // Eliminate Common SubExpressions.
-    OurFPM.add(createGVNPass());
-    // Simplify the control flow graph (deleting unreachable blocks, etc).
-    OurFPM.add(createCFGSimplificationPass());
+  FunctionPassManager OurFPM(TheModule);
 
-    // Set the global so the code gen can use this.
-    TheFPM = &amp;OurFPM;
+  // Set up the optimizer pipeline.  Start with registering info about how the
+  // target lays out data structures.
+  OurFPM.add(new TargetData(*TheExecutionEngine-&gt;getTargetData()));
+  // Provide basic AliasAnalysis support for GVN.
+  OurFPM.add(createBasicAliasAnalysisPass());
+  // Promote allocas to registers.
+  OurFPM.add(createPromoteMemoryToRegisterPass());
+  // Do simple "peephole" optimizations and bit-twiddling optzns.
+  OurFPM.add(createInstructionCombiningPass());
+  // Reassociate expressions.
+  OurFPM.add(createReassociatePass());
+  // Eliminate Common SubExpressions.
+  OurFPM.add(createGVNPass());
+  // Simplify the control flow graph (deleting unreachable blocks, etc).
+  OurFPM.add(createCFGSimplificationPass());
+
+  OurFPM.doInitialization();
+
+  // Set the global so the code gen can use this.
+  TheFPM = &amp;OurFPM;
+
+  // Run the main "interpreter loop" now.
+  MainLoop();
+
+  TheFPM = 0;
 
-    // Run the main "interpreter loop" now.
-    MainLoop();
-    
-    TheFPM = 0;
-  }  // Free module provider and pass manager.
-                                   
-                                   
   // Print out all of the generated code.
   TheModule-&gt;dump();
+
   return 0;
 }
 </pre>
 </div>
 
+<a href="LangImpl8.html">Next: Conclusion and other useful LLVM tidbits</a>
 </div>
 
 <!-- *********************************************************************** -->
@@ -2149,8 +2157,8 @@ int main() {
   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
 
   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
-  <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
-  Last modified: $Date: 2007-10-17 11:05:13 -0700 (Wed, 17 Oct 2007) $
+  <a href="http://llvm.org/">The LLVM Compiler Infrastructure</a><br>
+  Last modified: $Date$
 </address>
 </body>
 </html>