Remove PHINode::reserveOperandSpace(). Instead, add a parameter to
[oota-llvm.git] / docs / tutorial / LangImpl6.html
index 5a184c2c1817d466de465af432bf12dc3bc9faa0..3e83cf664e5b781fac9b3b3199423d111d1ae601 100644 (file)
 
 <div class="doc_title">Kaleidoscope: Extending the Language: User-defined Operators</div>
 
+<ul>
+<li><a href="index.html">Up to Tutorial Index</a></li>
+<li>Chapter 6
+  <ol>
+    <li><a href="#intro">Chapter 6 Introduction</a></li>
+    <li><a href="#idea">User-defined Operators: the Idea</a></li>
+    <li><a href="#binary">User-defined Binary Operators</a></li>
+    <li><a href="#unary">User-defined Unary Operators</a></li>
+    <li><a href="#example">Kicking the Tires</a></li>
+    <li><a href="#code">Full Code Listing</a></li>
+  </ol>
+</li>
+<li><a href="LangImpl7.html">Chapter 7</a>: Extending the Language: Mutable
+Variables / SSA Construction</li>
+</ul>
+
 <div class="doc_author">
   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></p>
 </div>
 
 <!-- *********************************************************************** -->
-<div class="doc_section"><a name="intro">Part 6 Introduction</a></div>
+<div class="doc_section"><a name="intro">Chapter 6 Introduction</a></div>
 <!-- *********************************************************************** -->
 
 <div class="doc_text">
 
-<p>Welcome to Part 6 of the "<a href="index.html">Implementing a language with
-LLVM</a>" tutorial.  At this point in our tutorial, we now have a fully
-functional language that is fairly minimal, but also useful.  One big problem
-with it though is that it doesn't have many useful operators (like division,
-logical negation, or even any comparisons other than less-than.</p>
+<p>Welcome to Chapter 6 of the "<a href="index.html">Implementing a language
+with LLVM</a>" tutorial.  At this point in our tutorial, we now have a fully
+functional language that is fairly minimal, but also useful.  There
+is still one big problem with it, however. Our language doesn't have many 
+useful operators (like division, logical negation, or even any comparisons 
+besides less-than).</p>
 
 <p>This chapter of the tutorial takes a wild digression into adding user-defined
-operators to the simple and beautiful Kaleidoscope language, giving us a 
-simple and ugly language in some ways, but also a powerful one at the same time.
+operators to the simple and beautiful Kaleidoscope language. This digression now gives 
+us a simple and ugly language in some ways, but also a powerful one at the same time.
 One of the great things about creating your own language is that you get to
-decide what is good or bad.  In this tutorial we'll assume that it is okay and
+decide what is good or bad.  In this tutorial we'll assume that it is okay to
 use this as a way to show some interesting parsing techniques.</p>
 
-<p>At the end of this tutorial, we'll <a href="#example">run through a nice
-little example</a> that shows an example application that you can build with
-Kaleidoscope and the feature set it now has.</p>
+<p>At the end of this tutorial, we'll run through an example Kaleidoscope 
+application that <a href="#example">renders the Mandelbrot set</a>.  This gives 
+an example of what you can build with Kaleidoscope and its feature set.</p>
 
 </div>
 
@@ -53,12 +70,12 @@ The "operator overloading" that we will add to Kaleidoscope is more general than
 languages like C++.  In C++, you are only allowed to redefine existing
 operators: you can't programatically change the grammar, introduce new
 operators, change precedence levels, etc.  In this chapter, we will add this
-capability to Kaleidoscope, which will allow us to round out the set of
-operators that are supported, culminating in a more interesting example app.</p>
+capability to Kaleidoscope, which will let the user round out the set of
+operators that are supported.</p>
 
 <p>The point of going into user-defined operators in a tutorial like this is to
-show the power and flexibility of using a hand-written parser.  The parser we
-are using so far is using recursive descent for most parts of the grammar, and 
+show the power and flexibility of using a hand-written parser.  Thus far, the parser
+we have been implementing uses recursive descent for most parts of the grammar and 
 operator precedence parsing for the expressions.  See <a 
 href="LangImpl2.html">Chapter 2</a> for details.  Without using operator
 precedence parsing, it would be very difficult to allow the programmer to
@@ -80,7 +97,7 @@ def unary!(v)
 
 # Define &gt; with the same precedence as &lt;.
 def binary&gt; 10 (LHS RHS)
-  !(LHS &lt; RHS);     # alternatively, could just use "RHS &lt; LHS"
+  RHS &lt; LHS;
 
 # Binary "logical or", (note that it does not "short circuit")
 def binary| 5 (LHS RHS)
@@ -136,12 +153,12 @@ static int gettok() {
 
 <p>This just adds lexer support for the unary and binary keywords, like we
 did in <a href="LangImpl5.html#iflexer">previous chapters</a>.  One nice thing
-about our current AST is that we represent binary operators fully generally
-with their ASCII code as the opcode.  For our extended operators, we'll use the
+about our current AST, is that we represent binary operators with full generalisation
+by using their ASCII code as the opcode.  For our extended operators, we'll use this
 same representation, so we don't need any new AST or parser support.</p>
 
 <p>On the other hand, we have to be able to represent the definitions of these
-new operators, in the "def binary| 5" part of the function definition.  In the
+new operators, in the "def binary| 5" part of the function definition.  In our
 grammar so far, the "name" for the function definition is parsed as the
 "prototype" production and into the <tt>PrototypeAST</tt> AST node.  To
 represent our new user-defined operators as prototypes, we have to extend
@@ -190,7 +207,7 @@ the prototype for a user-defined operator, we need to parse it:</p>
 static PrototypeAST *ParsePrototype() {
   std::string FnName;
   
-  <b>int Kind = 0;  // 0 = identifier, 1 = unary, 2 = binary.
+  <b>unsigned Kind = 0;  // 0 = identifier, 1 = unary, 2 = binary.
   unsigned BinaryPrecedence = 30;</b>
   
   switch (CurTok) {
@@ -241,14 +258,14 @@ static PrototypeAST *ParsePrototype() {
 </pre>
 </div>
 
-<p>This is all fairly straight-forward parsing code, and we have already seen
-a lot of similar code in the past.  One interesting piece of this is the part
-that sets up <tt>FnName</tt> for binary operators.  This builds names like
-"binary@" for a newly defined "@" operator.  This takes advantage of the fact
-that symbol names in the LLVM symbol table are allowed to have any character in
-them, inluding embedded nul characters.</p>
+<p>This is all fairly straightforward parsing code, and we have already seen
+a lot of similar code in the past.  One interesting part about the code above is 
+the couple lines that set up <tt>FnName</tt> for binary operators.  This builds names 
+like "binary@" for a newly defined "@" operator.  This then takes advantage of the 
+fact that symbol names in the LLVM symbol table are allowed to have any character in
+them, including embedded nul characters.</p>
 
-<p>The next interesting piece is codegen support for these binary operators.
+<p>The next interesting thing to add, is codegen support for these binary operators.
 Given our current structure, this is a simple addition of a default case for our
 existing binary operator node:</p>
 
@@ -260,13 +277,14 @@ Value *BinaryExprAST::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, "multmp");
+    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");
   <b>default: break;</b>
   }
   
@@ -285,10 +303,10 @@ Value *BinaryExprAST::Codegen() {
 <p>As you can see above, the new code is actually really simple.  It just does
 a lookup for the appropriate operator in the symbol table and generates a 
 function call to it.  Since user-defined operators are just built as normal
-functions (because the "prototype" boils down into a function with the right
+functions (because the "prototype" boils down to a function with the right
 name) everything falls into place.</p>
 
-<p>The final missing piece is a bit of top level magic, here:</p>
+<p>The final piece of code we are missing, is a bit of top-level magic:</p>
 
 <div class="doc_code">
 <pre>
@@ -304,7 +322,7 @@ Function *FunctionAST::Codegen() {
     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();</b>
   
   // 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);
   
   if (Value *RetVal = Body-&gt;Codegen()) {
@@ -314,12 +332,11 @@ Function *FunctionAST::Codegen() {
 
 <p>Basically, before codegening a function, if it is a user-defined operator, we
 register it in the precedence table.  This allows the binary operator parsing
-logic we already have to handle it.  Since it is a fully-general operator
-precedence parser, this is all we need to do to "extend the grammar".</p>
+logic we already have in place to handle it.  Since we are working on a fully-general operator precedence parser, this is all we need to do to "extend the grammar".</p>
 
-<p>With that, we have useful user-defined binary operators.  This builds a lot
+<p>Now we have useful user-defined binary operators.  This builds a lot
 on the previous framework we built for other operators.  Adding unary operators
-is a bit more challenging, because we don't have any framework for it yet, lets
+is a bit more challenging, because we don't have any framework for it yet - lets
 see what it takes.</p>
 
 </div>
@@ -331,7 +348,7 @@ see what it takes.</p>
 <div class="doc_text">
 
 <p>Since we don't currently support unary operators in the Kaleidoscope
-langugage, we'll need to add everything for them.  Above, we added simple
+language, we'll need to add everything to support them.  Above, we added simple
 support for the 'unary' keyword to the lexer.  In addition to that, we need an
 AST node:</p>
 
@@ -374,14 +391,14 @@ static ExprAST *ParseUnary() {
 </pre>
 </div>
 
-<p>The grammar we add is pretty straight-forward here.  If we see a unary
+<p>The grammar we add is pretty straightforward here.  If we see a unary
 operator when parsing a primary operator, we eat the operator as a prefix and
 parse the remaining piece as another unary operator.  This allows us to handle
 multiple unary operators (e.g. "!!x").  Note that unary operators can't have 
 ambiguous parses like binary operators can, so there is no need for precedence
 information.</p>
 
-<p>The problem with the above is that we need to call ParseUnary from somewhere.
+<p>The problem with this function, is that we need to call ParseUnary from somewhere.
 To do this, we change previous callers of ParsePrimary to call ParseUnary
 instead:</p>
 
@@ -408,7 +425,7 @@ static ExprAST *ParseExpression() {
 </pre>
 </div>
 
-<p>With these two simple changes, we now parse unary operators and build the
+<p>With these two simple changes, we are now able to parse unary operators and build the
 AST for them.  Next up, we need to add parser support for prototypes, to parse
 the unary operator prototype.  We extend the binary operator code above 
 with:</p>
@@ -422,7 +439,7 @@ with:</p>
 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) {
@@ -514,10 +531,9 @@ def unary!(v)
 def unary-(v)
   0-v;
 
-# Define &gt; with the same precedence as &gt;.  We could also easily define
-# &lt;= etc.
+# Define &gt; with the same precedence as &lt;.
 def binary&gt; 10 (LHS RHS)
-  !(LHS &lt; RHS);
+  RHS &lt; LHS;
 
 # Binary logical or, which does not short circuit. 
 def binary| 5 (LHS RHS)
@@ -572,7 +588,7 @@ Evaluated to 0.000000
 
 <p>Based on these simple primitive operations, we can start to define more
 interesting things.  For example, here's a little function that solves for the
-number of iterations it takes for a function in the complex plane to
+number of iterations it takes a function in the complex plane to
 converge:</p>
 
 <div class="doc_code">
@@ -599,13 +615,13 @@ href="http://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot Set</a>.  Our
 <tt>mandelconverge</tt> function returns the number of iterations that it takes
 for a complex orbit to escape, saturating to 255.  This is not a very useful
 function by itself, but if you plot its value over a two-dimensional plane,
-you can see the mandelbrot set.  Given that we are limited to using putchard
+you can see the Mandelbrot set.  Given that we are limited to using putchard
 here, our amazing graphical output is limited, but we can whip together
 something using the density plotter above:</p>
 
 <div class="doc_code">
 <pre>
-# compute and plot the mandlebrot set with the specified 2 dimentional range
+# compute and plot the mandlebrot set with the specified 2 dimensional range
 # info.
 def mandelhelp(xmin xmax xstep   ymin ymax ystep)
   for y = ymin, y &lt; ymax, ystep in (
@@ -615,7 +631,7 @@ def mandelhelp(xmin xmax xstep   ymin ymax ystep)
   )
  
 # mandel - This is a convenient helper function for ploting the mandelbrot set
-# from the specified position with the specified magnification.
+# from the specified position with the specified Magnification.
 def mandel(realstart imagstart realmag imagmag) 
   mandelhelp(realstart, realstart+realmag*78, realmag,
              imagstart, imagstart+imagmag*40, imagmag);
@@ -764,22 +780,21 @@ and powerful language.  It may not be self-similar :), but it can be used to
 plot things that are!</p>
 
 <p>With this, we conclude the "adding user-defined operators" chapter of the
-tutorial.  We successfully extended our language with the ability to extend the
-language in the library, and showed how this can be used to build a simple but
-interesting end user application in Kaleidoscope.  At this point, Kaleidoscope
+tutorial.  We have successfully augmented our language, adding the ability to extend the
+language in the library, and we have shown how this can be used to build a simple but
+interesting end-user application in Kaleidoscope.  At this point, Kaleidoscope
 can build a variety of applications that are functional and can call functions
 with side-effects, but it can't actually define and mutate a variable itself.
 </p>
 
-<p>Strikingly, lack of this feature is an important limitation for some
+<p>Strikingly, variable mutation is an important feature of some
 languages, and it is not at all obvious how to <a href="LangImpl7.html">add
 support for mutable variables</a> without having to add an "SSA construction"
 phase to your front-end.  In the next chapter, we will describe how you can
-add this without building SSA in your front-end.</p>
+add variable mutation without building SSA in your front-end.</p>
 
 </div>
 
-
 <!-- *********************************************************************** -->
 <div class="doc_section"><a name="code">Full Code Listing</a></div>
 <!-- *********************************************************************** -->
@@ -806,13 +821,16 @@ if/then/else and for expressions..  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/Target/TargetSelect.h"
 #include "llvm/Transforms/Scalar.h"
-#include "llvm/Support/LLVMBuilder.h"
+#include "llvm/Support/IRBuilder.h"
 #include &lt;cstdio&gt;
 #include &lt;string&gt;
 #include &lt;map&gt;
@@ -884,7 +902,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();
@@ -978,7 +996,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;
@@ -1018,7 +1037,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() {
@@ -1066,11 +1085,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();
     }
   }
@@ -1168,7 +1187,6 @@ static ExprAST *ParseForExpr() {
   return new ForExprAST(IdName, Start, End, Step, Body);
 }
 
-
 /// primary
 ///   ::= identifierexpr
 ///   ::= numberexpr
@@ -1252,7 +1270,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) {
@@ -1342,14 +1360,14 @@ static PrototypeAST *ParseExtern() {
 //===----------------------------------------------------------------------===//
 
 static Module *TheModule;
-static LLVMFoldingBuilder Builder;
+static IRBuilder&lt;&gt; Builder(getGlobalContext());
 static std::map&lt;std::string, Value*&gt; NamedValues;
 static FunctionPassManager *TheFPM;
 
 Value *ErrorV(const char *Str) { Error(Str); return 0; }
 
 Value *NumberExprAST::Codegen() {
-  return ConstantFP::get(Type::DoubleTy, APFloat(Val));
+  return ConstantFP::get(getGlobalContext(), APFloat(Val));
 }
 
 Value *VariableExprAST::Codegen() {
@@ -1369,20 +1387,20 @@ Value *UnaryExprAST::Codegen() {
   return Builder.CreateCall(F, OperandV, "unop");
 }
 
-
 Value *BinaryExprAST::Codegen() {
   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, "multmp");
+    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;
   }
   
@@ -1420,16 +1438,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);
   
@@ -1457,7 +1475,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);
@@ -1489,7 +1508,7 @@ Value *ForExprAST::Codegen() {
   // block.
   Function *TheFunction = Builder.GetInsertBlock()-&gt;getParent();
   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);
@@ -1498,7 +1517,7 @@ Value *ForExprAST::Codegen() {
   Builder.SetInsertPoint(LoopBB);
   
   // Start the PHI node with an entry for Start.
-  PHINode *Variable = Builder.CreatePHI(Type::DoubleTy, VarName.c_str());
+  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
   Variable-&gt;addIncoming(StartVal, PreheaderBB);
   
   // Within the loop, the variable is defined equal to the PHI node.  If it
@@ -1519,10 +1538,10 @@ 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));
   }
   
-  Value *NextVar = Builder.CreateAdd(Variable, StepVal, "nextvar");
+  Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
 
   // Compute the end condition.
   Value *EndCond = End-&gt;Codegen();
@@ -1530,12 +1549,12 @@ Value *ForExprAST::Codegen() {
   
   // 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);
@@ -1554,15 +1573,17 @@ Value *ForExprAST::Codegen() {
 
   
   // for expr always returns 0.0.
-  return Constant::getNullValue(Type::DoubleTy);
+  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
 }
 
 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;const 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.
@@ -1609,7 +1630,7 @@ 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);
   
   if (Value *RetVal = Body-&gt;Codegen()) {
@@ -1664,7 +1685,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.
@@ -1672,7 +1693,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 {
@@ -1687,7 +1708,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;
@@ -1695,8 +1716,6 @@ static void MainLoop() {
   }
 }
 
-
-
 //===----------------------------------------------------------------------===//
 // "Library" functions that can be "extern'd" from user code.
 //===----------------------------------------------------------------------===//
@@ -1720,6 +1739,9 @@ double printd(double X) {
 //===----------------------------------------------------------------------===//
 
 int main() {
+  InitializeNativeTarget();
+  LLVMContext &amp;Context = getGlobalContext();
+
   // Install standard binary operators.
   // 1 is lowest precedence.
   BinopPrecedence['&lt;'] = 10;
@@ -1732,43 +1754,51 @@ 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(&ErrStr).create();
+  if (!TheExecutionEngine) {
+    fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
+    exit(1);
+  }
+
+  FunctionPassManager OurFPM(TheModule);
+
+  // 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());
+  // 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;
 
-  {
-    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()));
-    // 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());
-    // Set the global so the code gen can use this.
-    TheFPM = &amp;OurFPM;
-
-    // Run the main "interpreter loop" now.
-    MainLoop();
-    
-    TheFPM = 0;
-  }  // Free module provider and pass manager.
-                                   
-                                   
   // Print out all of the generated code.
-  TheModule->dump();
+  TheModule-&gt;dump();
+
   return 0;
 }
 </pre>
 </div>
 
+<a href="LangImpl7.html">Next: Extending the language: mutable variables / SSA construction</a>
 </div>
 
 <!-- *********************************************************************** -->
@@ -1781,7 +1811,7 @@ int main() {
 
   <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) $
+  Last modified: $Date$
 </address>
 </body>
 </html>