Home | History | Annotate | Download | only in cached
      1 #define MINIMAL_STDERR_OUTPUT
      2 
      3 #include "llvm/Analysis/Passes.h"
      4 #include "llvm/Analysis/Verifier.h"
      5 #include "llvm/ExecutionEngine/ExecutionEngine.h"
      6 #include "llvm/ExecutionEngine/MCJIT.h"
      7 #include "llvm/ExecutionEngine/ObjectCache.h"
      8 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
      9 #include "llvm/IR/DataLayout.h"
     10 #include "llvm/IR/DerivedTypes.h"
     11 #include "llvm/IR/IRBuilder.h"
     12 #include "llvm/IR/LLVMContext.h"
     13 #include "llvm/IR/Module.h"
     14 #include "llvm/IRReader/IRReader.h"
     15 #include "llvm/PassManager.h"
     16 #include "llvm/Support/CommandLine.h"
     17 #include "llvm/Support/FileSystem.h"
     18 #include "llvm/Support/Path.h"
     19 #include "llvm/Support/raw_ostream.h"
     20 #include "llvm/Support/SourceMgr.h"
     21 #include "llvm/Support/TargetSelect.h"
     22 #include "llvm/Transforms/Scalar.h"
     23 #include <cstdio>
     24 #include <map>
     25 #include <string>
     26 #include <vector>
     27 using namespace llvm;
     28 
     29 //===----------------------------------------------------------------------===//
     30 // Command-line options
     31 //===----------------------------------------------------------------------===//
     32 
     33 cl::opt<std::string>
     34 InputIR("input-IR",
     35         cl::desc("Specify the name of an IR file to load for function definitions"),
     36         cl::value_desc("input IR file name"));
     37 
     38 cl::opt<bool>
     39 UseObjectCache("use-object-cache",
     40                cl::desc("Enable use of the MCJIT object caching"),
     41                cl::init(false));
     42 
     43 //===----------------------------------------------------------------------===//
     44 // Lexer
     45 //===----------------------------------------------------------------------===//
     46 
     47 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
     48 // of these for known things.
     49 enum Token {
     50   tok_eof = -1,
     51 
     52   // commands
     53   tok_def = -2, tok_extern = -3,
     54 
     55   // primary
     56   tok_identifier = -4, tok_number = -5,
     57 
     58   // control
     59   tok_if = -6, tok_then = -7, tok_else = -8,
     60   tok_for = -9, tok_in = -10,
     61 
     62   // operators
     63   tok_binary = -11, tok_unary = -12,
     64 
     65   // var definition
     66   tok_var = -13
     67 };
     68 
     69 static std::string IdentifierStr;  // Filled in if tok_identifier
     70 static double NumVal;              // Filled in if tok_number
     71 
     72 /// gettok - Return the next token from standard input.
     73 static int gettok() {
     74   static int LastChar = ' ';
     75 
     76   // Skip any whitespace.
     77   while (isspace(LastChar))
     78     LastChar = getchar();
     79 
     80   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
     81     IdentifierStr = LastChar;
     82     while (isalnum((LastChar = getchar())))
     83       IdentifierStr += LastChar;
     84 
     85     if (IdentifierStr == "def") return tok_def;
     86     if (IdentifierStr == "extern") return tok_extern;
     87     if (IdentifierStr == "if") return tok_if;
     88     if (IdentifierStr == "then") return tok_then;
     89     if (IdentifierStr == "else") return tok_else;
     90     if (IdentifierStr == "for") return tok_for;
     91     if (IdentifierStr == "in") return tok_in;
     92     if (IdentifierStr == "binary") return tok_binary;
     93     if (IdentifierStr == "unary") return tok_unary;
     94     if (IdentifierStr == "var") return tok_var;
     95     return tok_identifier;
     96   }
     97 
     98   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
     99     std::string NumStr;
    100     do {
    101       NumStr += LastChar;
    102       LastChar = getchar();
    103     } while (isdigit(LastChar) || LastChar == '.');
    104 
    105     NumVal = strtod(NumStr.c_str(), 0);
    106     return tok_number;
    107   }
    108 
    109   if (LastChar == '#') {
    110     // Comment until end of line.
    111     do LastChar = getchar();
    112     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
    113 
    114     if (LastChar != EOF)
    115       return gettok();
    116   }
    117 
    118   // Check for end of file.  Don't eat the EOF.
    119   if (LastChar == EOF)
    120     return tok_eof;
    121 
    122   // Otherwise, just return the character as its ascii value.
    123   int ThisChar = LastChar;
    124   LastChar = getchar();
    125   return ThisChar;
    126 }
    127 
    128 //===----------------------------------------------------------------------===//
    129 // Abstract Syntax Tree (aka Parse Tree)
    130 //===----------------------------------------------------------------------===//
    131 
    132 /// ExprAST - Base class for all expression nodes.
    133 class ExprAST {
    134 public:
    135   virtual ~ExprAST() {}
    136   virtual Value *Codegen() = 0;
    137 };
    138 
    139 /// NumberExprAST - Expression class for numeric literals like "1.0".
    140 class NumberExprAST : public ExprAST {
    141   double Val;
    142 public:
    143   NumberExprAST(double val) : Val(val) {}
    144   virtual Value *Codegen();
    145 };
    146 
    147 /// VariableExprAST - Expression class for referencing a variable, like "a".
    148 class VariableExprAST : public ExprAST {
    149   std::string Name;
    150 public:
    151   VariableExprAST(const std::string &name) : Name(name) {}
    152   const std::string &getName() const { return Name; }
    153   virtual Value *Codegen();
    154 };
    155 
    156 /// UnaryExprAST - Expression class for a unary operator.
    157 class UnaryExprAST : public ExprAST {
    158   char Opcode;
    159   ExprAST *Operand;
    160 public:
    161   UnaryExprAST(char opcode, ExprAST *operand)
    162     : Opcode(opcode), Operand(operand) {}
    163   virtual Value *Codegen();
    164 };
    165 
    166 /// BinaryExprAST - Expression class for a binary operator.
    167 class BinaryExprAST : public ExprAST {
    168   char Op;
    169   ExprAST *LHS, *RHS;
    170 public:
    171   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
    172     : Op(op), LHS(lhs), RHS(rhs) {}
    173   virtual Value *Codegen();
    174 };
    175 
    176 /// CallExprAST - Expression class for function calls.
    177 class CallExprAST : public ExprAST {
    178   std::string Callee;
    179   std::vector<ExprAST*> Args;
    180 public:
    181   CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
    182     : Callee(callee), Args(args) {}
    183   virtual Value *Codegen();
    184 };
    185 
    186 /// IfExprAST - Expression class for if/then/else.
    187 class IfExprAST : public ExprAST {
    188   ExprAST *Cond, *Then, *Else;
    189 public:
    190   IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
    191   : Cond(cond), Then(then), Else(_else) {}
    192   virtual Value *Codegen();
    193 };
    194 
    195 /// ForExprAST - Expression class for for/in.
    196 class ForExprAST : public ExprAST {
    197   std::string VarName;
    198   ExprAST *Start, *End, *Step, *Body;
    199 public:
    200   ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
    201              ExprAST *step, ExprAST *body)
    202     : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
    203   virtual Value *Codegen();
    204 };
    205 
    206 /// VarExprAST - Expression class for var/in
    207 class VarExprAST : public ExprAST {
    208   std::vector<std::pair<std::string, ExprAST*> > VarNames;
    209   ExprAST *Body;
    210 public:
    211   VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
    212              ExprAST *body)
    213   : VarNames(varnames), Body(body) {}
    214 
    215   virtual Value *Codegen();
    216 };
    217 
    218 /// PrototypeAST - This class represents the "prototype" for a function,
    219 /// which captures its argument names as well as if it is an operator.
    220 class PrototypeAST {
    221   std::string Name;
    222   std::vector<std::string> Args;
    223   bool isOperator;
    224   unsigned Precedence;  // Precedence if a binary op.
    225 public:
    226   PrototypeAST(const std::string &name, const std::vector<std::string> &args,
    227                bool isoperator = false, unsigned prec = 0)
    228   : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
    229 
    230   bool isUnaryOp() const { return isOperator && Args.size() == 1; }
    231   bool isBinaryOp() const { return isOperator && Args.size() == 2; }
    232 
    233   char getOperatorName() const {
    234     assert(isUnaryOp() || isBinaryOp());
    235     return Name[Name.size()-1];
    236   }
    237 
    238   unsigned getBinaryPrecedence() const { return Precedence; }
    239 
    240   Function *Codegen();
    241 
    242   void CreateArgumentAllocas(Function *F);
    243 };
    244 
    245 /// FunctionAST - This class represents a function definition itself.
    246 class FunctionAST {
    247   PrototypeAST *Proto;
    248   ExprAST *Body;
    249 public:
    250   FunctionAST(PrototypeAST *proto, ExprAST *body)
    251     : Proto(proto), Body(body) {}
    252 
    253   Function *Codegen();
    254 };
    255 
    256 //===----------------------------------------------------------------------===//
    257 // Parser
    258 //===----------------------------------------------------------------------===//
    259 
    260 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
    261 /// token the parser is looking at.  getNextToken reads another token from the
    262 /// lexer and updates CurTok with its results.
    263 static int CurTok;
    264 static int getNextToken() {
    265   return CurTok = gettok();
    266 }
    267 
    268 /// BinopPrecedence - This holds the precedence for each binary operator that is
    269 /// defined.
    270 static std::map<char, int> BinopPrecedence;
    271 
    272 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
    273 static int GetTokPrecedence() {
    274   if (!isascii(CurTok))
    275     return -1;
    276 
    277   // Make sure it's a declared binop.
    278   int TokPrec = BinopPrecedence[CurTok];
    279   if (TokPrec <= 0) return -1;
    280   return TokPrec;
    281 }
    282 
    283 /// Error* - These are little helper functions for error handling.
    284 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
    285 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
    286 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
    287 
    288 static ExprAST *ParseExpression();
    289 
    290 /// identifierexpr
    291 ///   ::= identifier
    292 ///   ::= identifier '(' expression* ')'
    293 static ExprAST *ParseIdentifierExpr() {
    294   std::string IdName = IdentifierStr;
    295 
    296   getNextToken();  // eat identifier.
    297 
    298   if (CurTok != '(') // Simple variable ref.
    299     return new VariableExprAST(IdName);
    300 
    301   // Call.
    302   getNextToken();  // eat (
    303   std::vector<ExprAST*> Args;
    304   if (CurTok != ')') {
    305     while (1) {
    306       ExprAST *Arg = ParseExpression();
    307       if (!Arg) return 0;
    308       Args.push_back(Arg);
    309 
    310       if (CurTok == ')') break;
    311 
    312       if (CurTok != ',')
    313         return Error("Expected ')' or ',' in argument list");
    314       getNextToken();
    315     }
    316   }
    317 
    318   // Eat the ')'.
    319   getNextToken();
    320 
    321   return new CallExprAST(IdName, Args);
    322 }
    323 
    324 /// numberexpr ::= number
    325 static ExprAST *ParseNumberExpr() {
    326   ExprAST *Result = new NumberExprAST(NumVal);
    327   getNextToken(); // consume the number
    328   return Result;
    329 }
    330 
    331 /// parenexpr ::= '(' expression ')'
    332 static ExprAST *ParseParenExpr() {
    333   getNextToken();  // eat (.
    334   ExprAST *V = ParseExpression();
    335   if (!V) return 0;
    336 
    337   if (CurTok != ')')
    338     return Error("expected ')'");
    339   getNextToken();  // eat ).
    340   return V;
    341 }
    342 
    343 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
    344 static ExprAST *ParseIfExpr() {
    345   getNextToken();  // eat the if.
    346 
    347   // condition.
    348   ExprAST *Cond = ParseExpression();
    349   if (!Cond) return 0;
    350 
    351   if (CurTok != tok_then)
    352     return Error("expected then");
    353   getNextToken();  // eat the then
    354 
    355   ExprAST *Then = ParseExpression();
    356   if (Then == 0) return 0;
    357 
    358   if (CurTok != tok_else)
    359     return Error("expected else");
    360 
    361   getNextToken();
    362 
    363   ExprAST *Else = ParseExpression();
    364   if (!Else) return 0;
    365 
    366   return new IfExprAST(Cond, Then, Else);
    367 }
    368 
    369 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
    370 static ExprAST *ParseForExpr() {
    371   getNextToken();  // eat the for.
    372 
    373   if (CurTok != tok_identifier)
    374     return Error("expected identifier after for");
    375 
    376   std::string IdName = IdentifierStr;
    377   getNextToken();  // eat identifier.
    378 
    379   if (CurTok != '=')
    380     return Error("expected '=' after for");
    381   getNextToken();  // eat '='.
    382 
    383 
    384   ExprAST *Start = ParseExpression();
    385   if (Start == 0) return 0;
    386   if (CurTok != ',')
    387     return Error("expected ',' after for start value");
    388   getNextToken();
    389 
    390   ExprAST *End = ParseExpression();
    391   if (End == 0) return 0;
    392 
    393   // The step value is optional.
    394   ExprAST *Step = 0;
    395   if (CurTok == ',') {
    396     getNextToken();
    397     Step = ParseExpression();
    398     if (Step == 0) return 0;
    399   }
    400 
    401   if (CurTok != tok_in)
    402     return Error("expected 'in' after for");
    403   getNextToken();  // eat 'in'.
    404 
    405   ExprAST *Body = ParseExpression();
    406   if (Body == 0) return 0;
    407 
    408   return new ForExprAST(IdName, Start, End, Step, Body);
    409 }
    410 
    411 /// varexpr ::= 'var' identifier ('=' expression)?
    412 //                    (',' identifier ('=' expression)?)* 'in' expression
    413 static ExprAST *ParseVarExpr() {
    414   getNextToken();  // eat the var.
    415 
    416   std::vector<std::pair<std::string, ExprAST*> > VarNames;
    417 
    418   // At least one variable name is required.
    419   if (CurTok != tok_identifier)
    420     return Error("expected identifier after var");
    421 
    422   while (1) {
    423     std::string Name = IdentifierStr;
    424     getNextToken();  // eat identifier.
    425 
    426     // Read the optional initializer.
    427     ExprAST *Init = 0;
    428     if (CurTok == '=') {
    429       getNextToken(); // eat the '='.
    430 
    431       Init = ParseExpression();
    432       if (Init == 0) return 0;
    433     }
    434 
    435     VarNames.push_back(std::make_pair(Name, Init));
    436 
    437     // End of var list, exit loop.
    438     if (CurTok != ',') break;
    439     getNextToken(); // eat the ','.
    440 
    441     if (CurTok != tok_identifier)
    442       return Error("expected identifier list after var");
    443   }
    444 
    445   // At this point, we have to have 'in'.
    446   if (CurTok != tok_in)
    447     return Error("expected 'in' keyword after 'var'");
    448   getNextToken();  // eat 'in'.
    449 
    450   ExprAST *Body = ParseExpression();
    451   if (Body == 0) return 0;
    452 
    453   return new VarExprAST(VarNames, Body);
    454 }
    455 
    456 /// primary
    457 ///   ::= identifierexpr
    458 ///   ::= numberexpr
    459 ///   ::= parenexpr
    460 ///   ::= ifexpr
    461 ///   ::= forexpr
    462 ///   ::= varexpr
    463 static ExprAST *ParsePrimary() {
    464   switch (CurTok) {
    465   default: return Error("unknown token when expecting an expression");
    466   case tok_identifier: return ParseIdentifierExpr();
    467   case tok_number:     return ParseNumberExpr();
    468   case '(':            return ParseParenExpr();
    469   case tok_if:         return ParseIfExpr();
    470   case tok_for:        return ParseForExpr();
    471   case tok_var:        return ParseVarExpr();
    472   }
    473 }
    474 
    475 /// unary
    476 ///   ::= primary
    477 ///   ::= '!' unary
    478 static ExprAST *ParseUnary() {
    479   // If the current token is not an operator, it must be a primary expr.
    480   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
    481     return ParsePrimary();
    482 
    483   // If this is a unary operator, read it.
    484   int Opc = CurTok;
    485   getNextToken();
    486   if (ExprAST *Operand = ParseUnary())
    487     return new UnaryExprAST(Opc, Operand);
    488   return 0;
    489 }
    490 
    491 /// binoprhs
    492 ///   ::= ('+' unary)*
    493 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
    494   // If this is a binop, find its precedence.
    495   while (1) {
    496     int TokPrec = GetTokPrecedence();
    497 
    498     // If this is a binop that binds at least as tightly as the current binop,
    499     // consume it, otherwise we are done.
    500     if (TokPrec < ExprPrec)
    501       return LHS;
    502 
    503     // Okay, we know this is a binop.
    504     int BinOp = CurTok;
    505     getNextToken();  // eat binop
    506 
    507     // Parse the unary expression after the binary operator.
    508     ExprAST *RHS = ParseUnary();
    509     if (!RHS) return 0;
    510 
    511     // If BinOp binds less tightly with RHS than the operator after RHS, let
    512     // the pending operator take RHS as its LHS.
    513     int NextPrec = GetTokPrecedence();
    514     if (TokPrec < NextPrec) {
    515       RHS = ParseBinOpRHS(TokPrec+1, RHS);
    516       if (RHS == 0) return 0;
    517     }
    518 
    519     // Merge LHS/RHS.
    520     LHS = new BinaryExprAST(BinOp, LHS, RHS);
    521   }
    522 }
    523 
    524 /// expression
    525 ///   ::= unary binoprhs
    526 ///
    527 static ExprAST *ParseExpression() {
    528   ExprAST *LHS = ParseUnary();
    529   if (!LHS) return 0;
    530 
    531   return ParseBinOpRHS(0, LHS);
    532 }
    533 
    534 /// prototype
    535 ///   ::= id '(' id* ')'
    536 ///   ::= binary LETTER number? (id, id)
    537 ///   ::= unary LETTER (id)
    538 static PrototypeAST *ParsePrototype() {
    539   std::string FnName;
    540 
    541   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
    542   unsigned BinaryPrecedence = 30;
    543 
    544   switch (CurTok) {
    545   default:
    546     return ErrorP("Expected function name in prototype");
    547   case tok_identifier:
    548     FnName = IdentifierStr;
    549     Kind = 0;
    550     getNextToken();
    551     break;
    552   case tok_unary:
    553     getNextToken();
    554     if (!isascii(CurTok))
    555       return ErrorP("Expected unary operator");
    556     FnName = "unary";
    557     FnName += (char)CurTok;
    558     Kind = 1;
    559     getNextToken();
    560     break;
    561   case tok_binary:
    562     getNextToken();
    563     if (!isascii(CurTok))
    564       return ErrorP("Expected binary operator");
    565     FnName = "binary";
    566     FnName += (char)CurTok;
    567     Kind = 2;
    568     getNextToken();
    569 
    570     // Read the precedence if present.
    571     if (CurTok == tok_number) {
    572       if (NumVal < 1 || NumVal > 100)
    573         return ErrorP("Invalid precedecnce: must be 1..100");
    574       BinaryPrecedence = (unsigned)NumVal;
    575       getNextToken();
    576     }
    577     break;
    578   }
    579 
    580   if (CurTok != '(')
    581     return ErrorP("Expected '(' in prototype");
    582 
    583   std::vector<std::string> ArgNames;
    584   while (getNextToken() == tok_identifier)
    585     ArgNames.push_back(IdentifierStr);
    586   if (CurTok != ')')
    587     return ErrorP("Expected ')' in prototype");
    588 
    589   // success.
    590   getNextToken();  // eat ')'.
    591 
    592   // Verify right number of names for operator.
    593   if (Kind && ArgNames.size() != Kind)
    594     return ErrorP("Invalid number of operands for operator");
    595 
    596   return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
    597 }
    598 
    599 /// definition ::= 'def' prototype expression
    600 static FunctionAST *ParseDefinition() {
    601   getNextToken();  // eat def.
    602   PrototypeAST *Proto = ParsePrototype();
    603   if (Proto == 0) return 0;
    604 
    605   if (ExprAST *E = ParseExpression())
    606     return new FunctionAST(Proto, E);
    607   return 0;
    608 }
    609 
    610 /// toplevelexpr ::= expression
    611 static FunctionAST *ParseTopLevelExpr() {
    612   if (ExprAST *E = ParseExpression()) {
    613     // Make an anonymous proto.
    614     PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
    615     return new FunctionAST(Proto, E);
    616   }
    617   return 0;
    618 }
    619 
    620 /// external ::= 'extern' prototype
    621 static PrototypeAST *ParseExtern() {
    622   getNextToken();  // eat extern.
    623   return ParsePrototype();
    624 }
    625 
    626 //===----------------------------------------------------------------------===//
    627 // Quick and dirty hack
    628 //===----------------------------------------------------------------------===//
    629 
    630 // FIXME: Obviously we can do better than this
    631 std::string GenerateUniqueName(const char *root)
    632 {
    633   static int i = 0;
    634   char s[16];
    635   sprintf(s, "%s%d", root, i++);
    636   std::string S = s;
    637   return S;
    638 }
    639 
    640 std::string MakeLegalFunctionName(std::string Name)
    641 {
    642   std::string NewName;
    643   if (!Name.length())
    644       return GenerateUniqueName("anon_func_");
    645 
    646   // Start with what we have
    647   NewName = Name;
    648 
    649   // Look for a numberic first character
    650   if (NewName.find_first_of("0123456789") == 0) {
    651     NewName.insert(0, 1, 'n');
    652   }
    653 
    654   // Replace illegal characters with their ASCII equivalent
    655   std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    656   size_t pos;
    657   while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
    658     char old_c = NewName.at(pos);
    659     char new_str[16];
    660     sprintf(new_str, "%d", (int)old_c);
    661     NewName = NewName.replace(pos, 1, new_str);
    662   }
    663 
    664   return NewName;
    665 }
    666 
    667 //===----------------------------------------------------------------------===//
    668 // MCJIT object cache class
    669 //===----------------------------------------------------------------------===//
    670 
    671 class MCJITObjectCache : public ObjectCache {
    672 public:
    673   MCJITObjectCache() {
    674     // Set IR cache directory
    675     sys::fs::current_path(CacheDir);
    676     sys::path::append(CacheDir, "toy_object_cache");
    677   }
    678 
    679   virtual ~MCJITObjectCache() {
    680   }
    681 
    682   virtual void notifyObjectCompiled(const Module *M, const MemoryBuffer *Obj) {
    683     // Get the ModuleID
    684     const std::string ModuleID = M->getModuleIdentifier();
    685 
    686     // If we've flagged this as an IR file, cache it
    687     if (0 == ModuleID.compare(0, 3, "IR:")) {
    688       std::string IRFileName = ModuleID.substr(3);
    689       SmallString<128>IRCacheFile = CacheDir;
    690       sys::path::append(IRCacheFile, IRFileName);
    691       if (!sys::fs::exists(CacheDir.str()) && sys::fs::create_directory(CacheDir.str())) {
    692         fprintf(stderr, "Unable to create cache directory\n");
    693         return;
    694       }
    695       std::string ErrStr;
    696       raw_fd_ostream IRObjectFile(IRCacheFile.c_str(), ErrStr, raw_fd_ostream::F_Binary);
    697       IRObjectFile << Obj->getBuffer();
    698     }
    699   }
    700 
    701   // MCJIT will call this function before compiling any module
    702   // MCJIT takes ownership of both the MemoryBuffer object and the memory
    703   // to which it refers.
    704   virtual MemoryBuffer* getObject(const Module* M) {
    705     // Get the ModuleID
    706     const std::string ModuleID = M->getModuleIdentifier();
    707 
    708     // If we've flagged this as an IR file, cache it
    709     if (0 == ModuleID.compare(0, 3, "IR:")) {
    710       std::string IRFileName = ModuleID.substr(3);
    711       SmallString<128> IRCacheFile = CacheDir;
    712       sys::path::append(IRCacheFile, IRFileName);
    713       if (!sys::fs::exists(IRCacheFile.str())) {
    714         // This file isn't in our cache
    715         return NULL;
    716       }
    717       OwningPtr<MemoryBuffer> IRObjectBuffer;
    718       MemoryBuffer::getFile(IRCacheFile.c_str(), IRObjectBuffer, -1, false);
    719       // MCJIT will want to write into this buffer, and we don't want that
    720       // because the file has probably just been mmapped.  Instead we make
    721       // a copy.  The filed-based buffer will be released when it goes
    722       // out of scope.
    723       return MemoryBuffer::getMemBufferCopy(IRObjectBuffer->getBuffer());
    724     }
    725 
    726     return NULL;
    727   }
    728 
    729 private:
    730   SmallString<128> CacheDir;
    731 };
    732 
    733 //===----------------------------------------------------------------------===//
    734 // MCJIT helper class
    735 //===----------------------------------------------------------------------===//
    736 
    737 class MCJITHelper
    738 {
    739 public:
    740   MCJITHelper(LLVMContext& C) : Context(C), OpenModule(NULL) {}
    741   ~MCJITHelper();
    742 
    743   Function *getFunction(const std::string FnName);
    744   Module *getModuleForNewFunction();
    745   void *getPointerToFunction(Function* F);
    746   void *getPointerToNamedFunction(const std::string &Name);
    747   ExecutionEngine *compileModule(Module *M);
    748   void closeCurrentModule();
    749   void addModule(Module *M);
    750   void dump();
    751 
    752 private:
    753   typedef std::vector<Module*> ModuleVector;
    754 
    755   LLVMContext  &Context;
    756   Module       *OpenModule;
    757   ModuleVector  Modules;
    758   std::map<Module *, ExecutionEngine *> EngineMap;
    759   MCJITObjectCache OurObjectCache;
    760 };
    761 
    762 class HelpingMemoryManager : public SectionMemoryManager
    763 {
    764   HelpingMemoryManager(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION;
    765   void operator=(const HelpingMemoryManager&) LLVM_DELETED_FUNCTION;
    766 
    767 public:
    768   HelpingMemoryManager(MCJITHelper *Helper) : MasterHelper(Helper) {}
    769   virtual ~HelpingMemoryManager() {}
    770 
    771   /// This method returns the address of the specified function.
    772   /// Our implementation will attempt to find functions in other
    773   /// modules associated with the MCJITHelper to cross link functions
    774   /// from one generated module to another.
    775   ///
    776   /// If \p AbortOnFailure is false and no function with the given name is
    777   /// found, this function returns a null pointer. Otherwise, it prints a
    778   /// message to stderr and aborts.
    779   virtual void *getPointerToNamedFunction(const std::string &Name,
    780                                           bool AbortOnFailure = true);
    781 private:
    782   MCJITHelper *MasterHelper;
    783 };
    784 
    785 void *HelpingMemoryManager::getPointerToNamedFunction(const std::string &Name,
    786                                         bool AbortOnFailure)
    787 {
    788   // Try the standard symbol resolution first, but ask it not to abort.
    789   void *pfn = SectionMemoryManager::getPointerToNamedFunction(Name, false);
    790   if (pfn)
    791     return pfn;
    792 
    793   pfn = MasterHelper->getPointerToNamedFunction(Name);
    794   if (!pfn && AbortOnFailure)
    795     report_fatal_error("Program used external function '" + Name +
    796                         "' which could not be resolved!");
    797   return pfn;
    798 }
    799 
    800 MCJITHelper::~MCJITHelper()
    801 {
    802   // Walk the vector of modules.
    803   ModuleVector::iterator it, end;
    804   for (it = Modules.begin(), end = Modules.end();
    805        it != end; ++it) {
    806     // See if we have an execution engine for this module.
    807     std::map<Module*, ExecutionEngine*>::iterator mapIt = EngineMap.find(*it);
    808     // If we have an EE, the EE owns the module so just delete the EE.
    809     if (mapIt != EngineMap.end()) {
    810       delete mapIt->second;
    811     } else {
    812       // Otherwise, we still own the module.  Delete it now.
    813       delete *it;
    814     }
    815   }
    816 }
    817 
    818 Function *MCJITHelper::getFunction(const std::string FnName) {
    819   ModuleVector::iterator begin = Modules.begin();
    820   ModuleVector::iterator end = Modules.end();
    821   ModuleVector::iterator it;
    822   for (it = begin; it != end; ++it) {
    823     Function *F = (*it)->getFunction(FnName);
    824     if (F) {
    825       if (*it == OpenModule)
    826           return F;
    827 
    828       assert(OpenModule != NULL);
    829 
    830       // This function is in a module that has already been JITed.
    831       // We need to generate a new prototype for external linkage.
    832       Function *PF = OpenModule->getFunction(FnName);
    833       if (PF && !PF->empty()) {
    834         ErrorF("redefinition of function across modules");
    835         return 0;
    836       }
    837 
    838       // If we don't have a prototype yet, create one.
    839       if (!PF)
    840         PF = Function::Create(F->getFunctionType(),
    841                                       Function::ExternalLinkage,
    842                                       FnName,
    843                                       OpenModule);
    844       return PF;
    845     }
    846   }
    847   return NULL;
    848 }
    849 
    850 Module *MCJITHelper::getModuleForNewFunction() {
    851   // If we have a Module that hasn't been JITed, use that.
    852   if (OpenModule)
    853     return OpenModule;
    854 
    855   // Otherwise create a new Module.
    856   std::string ModName = GenerateUniqueName("mcjit_module_");
    857   Module *M = new Module(ModName, Context);
    858   Modules.push_back(M);
    859   OpenModule = M;
    860   return M;
    861 }
    862 
    863 void *MCJITHelper::getPointerToFunction(Function* F) {
    864   // Look for this function in an existing module
    865   ModuleVector::iterator begin = Modules.begin();
    866   ModuleVector::iterator end = Modules.end();
    867   ModuleVector::iterator it;
    868   std::string FnName = F->getName();
    869   for (it = begin; it != end; ++it) {
    870     Function *MF = (*it)->getFunction(FnName);
    871     if (MF == F) {
    872       std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
    873       if (eeIt != EngineMap.end()) {
    874         void *P = eeIt->second->getPointerToFunction(F);
    875         if (P)
    876           return P;
    877       } else {
    878         ExecutionEngine *EE = compileModule(*it);
    879         void *P = EE->getPointerToFunction(F);
    880         if (P)
    881           return P;
    882       }
    883     }
    884   }
    885   return NULL;
    886 }
    887 
    888 void MCJITHelper::closeCurrentModule() {
    889   OpenModule = NULL;
    890 }
    891 
    892 ExecutionEngine *MCJITHelper::compileModule(Module *M) {
    893   if (M == OpenModule)
    894     closeCurrentModule();
    895 
    896   std::string ErrStr;
    897   ExecutionEngine *NewEngine = EngineBuilder(M)
    898                                             .setErrorStr(&ErrStr)
    899                                             .setUseMCJIT(true)
    900                                             .setMCJITMemoryManager(new HelpingMemoryManager(this))
    901                                             .create();
    902   if (!NewEngine) {
    903     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
    904     exit(1);
    905   }
    906 
    907   if (UseObjectCache)
    908     NewEngine->setObjectCache(&OurObjectCache);
    909 
    910   // Get the ModuleID so we can identify IR input files
    911   const std::string ModuleID = M->getModuleIdentifier();
    912 
    913   // If we've flagged this as an IR file, it doesn't need function passes run.
    914   if (0 != ModuleID.compare(0, 3, "IR:")) {
    915     // Create a function pass manager for this engine
    916     FunctionPassManager *FPM = new FunctionPassManager(M);
    917 
    918     // Set up the optimizer pipeline.  Start with registering info about how the
    919     // target lays out data structures.
    920     FPM->add(new DataLayout(*NewEngine->getDataLayout()));
    921     // Provide basic AliasAnalysis support for GVN.
    922     FPM->add(createBasicAliasAnalysisPass());
    923     // Promote allocas to registers.
    924     FPM->add(createPromoteMemoryToRegisterPass());
    925     // Do simple "peephole" optimizations and bit-twiddling optzns.
    926     FPM->add(createInstructionCombiningPass());
    927     // Reassociate expressions.
    928     FPM->add(createReassociatePass());
    929     // Eliminate Common SubExpressions.
    930     FPM->add(createGVNPass());
    931     // Simplify the control flow graph (deleting unreachable blocks, etc).
    932     FPM->add(createCFGSimplificationPass());
    933     FPM->doInitialization();
    934 
    935     // For each function in the module
    936     Module::iterator it;
    937     Module::iterator end = M->end();
    938     for (it = M->begin(); it != end; ++it) {
    939       // Run the FPM on this function
    940       FPM->run(*it);
    941     }
    942 
    943     // We don't need this anymore
    944     delete FPM;
    945   }
    946 
    947   // Store this engine
    948   EngineMap[M] = NewEngine;
    949   NewEngine->finalizeObject();
    950 
    951   return NewEngine;
    952 }
    953 
    954 void *MCJITHelper::getPointerToNamedFunction(const std::string &Name)
    955 {
    956   // Look for the functions in our modules, compiling only as necessary
    957   ModuleVector::iterator begin = Modules.begin();
    958   ModuleVector::iterator end = Modules.end();
    959   ModuleVector::iterator it;
    960   for (it = begin; it != end; ++it) {
    961     Function *F = (*it)->getFunction(Name);
    962     if (F && !F->empty()) {
    963       std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
    964       if (eeIt != EngineMap.end()) {
    965         void *P = eeIt->second->getPointerToFunction(F);
    966         if (P)
    967           return P;
    968       } else {
    969         ExecutionEngine *EE = compileModule(*it);
    970         void *P = EE->getPointerToFunction(F);
    971         if (P)
    972           return P;
    973       }
    974     }
    975   }
    976   return NULL;
    977 }
    978 
    979 void MCJITHelper::addModule(Module* M) {
    980   Modules.push_back(M);
    981 }
    982 
    983 void MCJITHelper::dump()
    984 {
    985   ModuleVector::iterator begin = Modules.begin();
    986   ModuleVector::iterator end = Modules.end();
    987   ModuleVector::iterator it;
    988   for (it = begin; it != end; ++it)
    989     (*it)->dump();
    990 }
    991 
    992 //===----------------------------------------------------------------------===//
    993 // Code Generation
    994 //===----------------------------------------------------------------------===//
    995 
    996 static MCJITHelper *TheHelper;
    997 static IRBuilder<> Builder(getGlobalContext());
    998 static std::map<std::string, AllocaInst*> NamedValues;
    999 
   1000 Value *ErrorV(const char *Str) { Error(Str); return 0; }
   1001 
   1002 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
   1003 /// the function.  This is used for mutable variables etc.
   1004 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
   1005                                           const std::string &VarName) {
   1006   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
   1007                  TheFunction->getEntryBlock().begin());
   1008   return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
   1009                            VarName.c_str());
   1010 }
   1011 
   1012 Value *NumberExprAST::Codegen() {
   1013   return ConstantFP::get(getGlobalContext(), APFloat(Val));
   1014 }
   1015 
   1016 Value *VariableExprAST::Codegen() {
   1017   // Look this variable up in the function.
   1018   Value *V = NamedValues[Name];
   1019   char ErrStr[256];
   1020   sprintf(ErrStr, "Unknown variable name %s", Name.c_str());
   1021   if (V == 0) return ErrorV(ErrStr);
   1022 
   1023   // Load the value.
   1024   return Builder.CreateLoad(V, Name.c_str());
   1025 }
   1026 
   1027 Value *UnaryExprAST::Codegen() {
   1028   Value *OperandV = Operand->Codegen();
   1029   if (OperandV == 0) return 0;
   1030 
   1031   Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode));
   1032   if (F == 0)
   1033     return ErrorV("Unknown unary operator");
   1034 
   1035   return Builder.CreateCall(F, OperandV, "unop");
   1036 }
   1037 
   1038 Value *BinaryExprAST::Codegen() {
   1039   // Special case '=' because we don't want to emit the LHS as an expression.
   1040   if (Op == '=') {
   1041     // Assignment requires the LHS to be an identifier.
   1042     VariableExprAST *LHSE = reinterpret_cast<VariableExprAST*>(LHS);
   1043     if (!LHSE)
   1044       return ErrorV("destination of '=' must be a variable");
   1045     // Codegen the RHS.
   1046     Value *Val = RHS->Codegen();
   1047     if (Val == 0) return 0;
   1048 
   1049     // Look up the name.
   1050     Value *Variable = NamedValues[LHSE->getName()];
   1051     if (Variable == 0) return ErrorV("Unknown variable name");
   1052 
   1053     Builder.CreateStore(Val, Variable);
   1054     return Val;
   1055   }
   1056 
   1057   Value *L = LHS->Codegen();
   1058   Value *R = RHS->Codegen();
   1059   if (L == 0 || R == 0) return 0;
   1060 
   1061   switch (Op) {
   1062   case '+': return Builder.CreateFAdd(L, R, "addtmp");
   1063   case '-': return Builder.CreateFSub(L, R, "subtmp");
   1064   case '*': return Builder.CreateFMul(L, R, "multmp");
   1065   case '/': return Builder.CreateFDiv(L, R, "divtmp");
   1066   case '<':
   1067     L = Builder.CreateFCmpULT(L, R, "cmptmp");
   1068     // Convert bool 0/1 to double 0.0 or 1.0
   1069     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
   1070                                 "booltmp");
   1071   default: break;
   1072   }
   1073 
   1074   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
   1075   // a call to it.
   1076   Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("binary")+Op));
   1077   assert(F && "binary operator not found!");
   1078 
   1079   Value *Ops[] = { L, R };
   1080   return Builder.CreateCall(F, Ops, "binop");
   1081 }
   1082 
   1083 Value *CallExprAST::Codegen() {
   1084   // Look up the name in the global module table.
   1085   Function *CalleeF = TheHelper->getFunction(Callee);
   1086   if (CalleeF == 0)
   1087     return ErrorV("Unknown function referenced");
   1088 
   1089   // If argument mismatch error.
   1090   if (CalleeF->arg_size() != Args.size())
   1091     return ErrorV("Incorrect # arguments passed");
   1092 
   1093   std::vector<Value*> ArgsV;
   1094   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
   1095     ArgsV.push_back(Args[i]->Codegen());
   1096     if (ArgsV.back() == 0) return 0;
   1097   }
   1098 
   1099   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
   1100 }
   1101 
   1102 Value *IfExprAST::Codegen() {
   1103   Value *CondV = Cond->Codegen();
   1104   if (CondV == 0) return 0;
   1105 
   1106   // Convert condition to a bool by comparing equal to 0.0.
   1107   CondV = Builder.CreateFCmpONE(CondV,
   1108                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
   1109                                 "ifcond");
   1110 
   1111   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   1112 
   1113   // Create blocks for the then and else cases.  Insert the 'then' block at the
   1114   // end of the function.
   1115   BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
   1116   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
   1117   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
   1118 
   1119   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
   1120 
   1121   // Emit then value.
   1122   Builder.SetInsertPoint(ThenBB);
   1123 
   1124   Value *ThenV = Then->Codegen();
   1125   if (ThenV == 0) return 0;
   1126 
   1127   Builder.CreateBr(MergeBB);
   1128   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
   1129   ThenBB = Builder.GetInsertBlock();
   1130 
   1131   // Emit else block.
   1132   TheFunction->getBasicBlockList().push_back(ElseBB);
   1133   Builder.SetInsertPoint(ElseBB);
   1134 
   1135   Value *ElseV = Else->Codegen();
   1136   if (ElseV == 0) return 0;
   1137 
   1138   Builder.CreateBr(MergeBB);
   1139   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
   1140   ElseBB = Builder.GetInsertBlock();
   1141 
   1142   // Emit merge block.
   1143   TheFunction->getBasicBlockList().push_back(MergeBB);
   1144   Builder.SetInsertPoint(MergeBB);
   1145   PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
   1146                                   "iftmp");
   1147 
   1148   PN->addIncoming(ThenV, ThenBB);
   1149   PN->addIncoming(ElseV, ElseBB);
   1150   return PN;
   1151 }
   1152 
   1153 Value *ForExprAST::Codegen() {
   1154   // Output this as:
   1155   //   var = alloca double
   1156   //   ...
   1157   //   start = startexpr
   1158   //   store start -> var
   1159   //   goto loop
   1160   // loop:
   1161   //   ...
   1162   //   bodyexpr
   1163   //   ...
   1164   // loopend:
   1165   //   step = stepexpr
   1166   //   endcond = endexpr
   1167   //
   1168   //   curvar = load var
   1169   //   nextvar = curvar + step
   1170   //   store nextvar -> var
   1171   //   br endcond, loop, endloop
   1172   // outloop:
   1173 
   1174   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   1175 
   1176   // Create an alloca for the variable in the entry block.
   1177   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
   1178 
   1179   // Emit the start code first, without 'variable' in scope.
   1180   Value *StartVal = Start->Codegen();
   1181   if (StartVal == 0) return 0;
   1182 
   1183   // Store the value into the alloca.
   1184   Builder.CreateStore(StartVal, Alloca);
   1185 
   1186   // Make the new basic block for the loop header, inserting after current
   1187   // block.
   1188   BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
   1189 
   1190   // Insert an explicit fall through from the current block to the LoopBB.
   1191   Builder.CreateBr(LoopBB);
   1192 
   1193   // Start insertion in LoopBB.
   1194   Builder.SetInsertPoint(LoopBB);
   1195 
   1196   // Within the loop, the variable is defined equal to the PHI node.  If it
   1197   // shadows an existing variable, we have to restore it, so save it now.
   1198   AllocaInst *OldVal = NamedValues[VarName];
   1199   NamedValues[VarName] = Alloca;
   1200 
   1201   // Emit the body of the loop.  This, like any other expr, can change the
   1202   // current BB.  Note that we ignore the value computed by the body, but don't
   1203   // allow an error.
   1204   if (Body->Codegen() == 0)
   1205     return 0;
   1206 
   1207   // Emit the step value.
   1208   Value *StepVal;
   1209   if (Step) {
   1210     StepVal = Step->Codegen();
   1211     if (StepVal == 0) return 0;
   1212   } else {
   1213     // If not specified, use 1.0.
   1214     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
   1215   }
   1216 
   1217   // Compute the end condition.
   1218   Value *EndCond = End->Codegen();
   1219   if (EndCond == 0) return EndCond;
   1220 
   1221   // Reload, increment, and restore the alloca.  This handles the case where
   1222   // the body of the loop mutates the variable.
   1223   Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
   1224   Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
   1225   Builder.CreateStore(NextVar, Alloca);
   1226 
   1227   // Convert condition to a bool by comparing equal to 0.0.
   1228   EndCond = Builder.CreateFCmpONE(EndCond,
   1229                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
   1230                                   "loopcond");
   1231 
   1232   // Create the "after loop" block and insert it.
   1233   BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
   1234 
   1235   // Insert the conditional branch into the end of LoopEndBB.
   1236   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
   1237 
   1238   // Any new code will be inserted in AfterBB.
   1239   Builder.SetInsertPoint(AfterBB);
   1240 
   1241   // Restore the unshadowed variable.
   1242   if (OldVal)
   1243     NamedValues[VarName] = OldVal;
   1244   else
   1245     NamedValues.erase(VarName);
   1246 
   1247 
   1248   // for expr always returns 0.0.
   1249   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
   1250 }
   1251 
   1252 Value *VarExprAST::Codegen() {
   1253   std::vector<AllocaInst *> OldBindings;
   1254 
   1255   Function *TheFunction = Builder.GetInsertBlock()->getParent();
   1256 
   1257   // Register all variables and emit their initializer.
   1258   for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
   1259     const std::string &VarName = VarNames[i].first;
   1260     ExprAST *Init = VarNames[i].second;
   1261 
   1262     // Emit the initializer before adding the variable to scope, this prevents
   1263     // the initializer from referencing the variable itself, and permits stuff
   1264     // like this:
   1265     //  var a = 1 in
   1266     //    var a = a in ...   # refers to outer 'a'.
   1267     Value *InitVal;
   1268     if (Init) {
   1269       InitVal = Init->Codegen();
   1270       if (InitVal == 0) return 0;
   1271     } else { // If not specified, use 0.0.
   1272       InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
   1273     }
   1274 
   1275     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
   1276     Builder.CreateStore(InitVal, Alloca);
   1277 
   1278     // Remember the old variable binding so that we can restore the binding when
   1279     // we unrecurse.
   1280     OldBindings.push_back(NamedValues[VarName]);
   1281 
   1282     // Remember this binding.
   1283     NamedValues[VarName] = Alloca;
   1284   }
   1285 
   1286   // Codegen the body, now that all vars are in scope.
   1287   Value *BodyVal = Body->Codegen();
   1288   if (BodyVal == 0) return 0;
   1289 
   1290   // Pop all our variables from scope.
   1291   for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
   1292     NamedValues[VarNames[i].first] = OldBindings[i];
   1293 
   1294   // Return the body computation.
   1295   return BodyVal;
   1296 }
   1297 
   1298 Function *PrototypeAST::Codegen() {
   1299   // Make the function type:  double(double,double) etc.
   1300   std::vector<Type*> Doubles(Args.size(),
   1301                              Type::getDoubleTy(getGlobalContext()));
   1302   FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
   1303                                        Doubles, false);
   1304 
   1305   std::string FnName = MakeLegalFunctionName(Name);
   1306 
   1307   Module* M = TheHelper->getModuleForNewFunction();
   1308 
   1309   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName, M);
   1310 
   1311   // If F conflicted, there was already something named 'FnName'.  If it has a
   1312   // body, don't allow redefinition or reextern.
   1313   if (F->getName() != FnName) {
   1314     // Delete the one we just made and get the existing one.
   1315     F->eraseFromParent();
   1316     F = M->getFunction(Name);
   1317 
   1318     // If F already has a body, reject this.
   1319     if (!F->empty()) {
   1320       ErrorF("redefinition of function");
   1321       return 0;
   1322     }
   1323 
   1324     // If F took a different number of args, reject.
   1325     if (F->arg_size() != Args.size()) {
   1326       ErrorF("redefinition of function with different # args");
   1327       return 0;
   1328     }
   1329   }
   1330 
   1331   // Set names for all arguments.
   1332   unsigned Idx = 0;
   1333   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
   1334        ++AI, ++Idx)
   1335     AI->setName(Args[Idx]);
   1336 
   1337   return F;
   1338 }
   1339 
   1340 /// CreateArgumentAllocas - Create an alloca for each argument and register the
   1341 /// argument in the symbol table so that references to it will succeed.
   1342 void PrototypeAST::CreateArgumentAllocas(Function *F) {
   1343   Function::arg_iterator AI = F->arg_begin();
   1344   for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
   1345     // Create an alloca for this variable.
   1346     AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
   1347 
   1348     // Store the initial value into the alloca.
   1349     Builder.CreateStore(AI, Alloca);
   1350 
   1351     // Add arguments to variable symbol table.
   1352     NamedValues[Args[Idx]] = Alloca;
   1353   }
   1354 }
   1355 
   1356 Function *FunctionAST::Codegen() {
   1357   NamedValues.clear();
   1358 
   1359   Function *TheFunction = Proto->Codegen();
   1360   if (TheFunction == 0)
   1361     return 0;
   1362 
   1363   // If this is an operator, install it.
   1364   if (Proto->isBinaryOp())
   1365     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
   1366 
   1367   // Create a new basic block to start insertion into.
   1368   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
   1369   Builder.SetInsertPoint(BB);
   1370 
   1371   // Add all arguments to the symbol table and create their allocas.
   1372   Proto->CreateArgumentAllocas(TheFunction);
   1373 
   1374   if (Value *RetVal = Body->Codegen()) {
   1375     // Finish off the function.
   1376     Builder.CreateRet(RetVal);
   1377 
   1378     // Validate the generated code, checking for consistency.
   1379     verifyFunction(*TheFunction);
   1380 
   1381     return TheFunction;
   1382   }
   1383 
   1384   // Error reading body, remove function.
   1385   TheFunction->eraseFromParent();
   1386 
   1387   if (Proto->isBinaryOp())
   1388     BinopPrecedence.erase(Proto->getOperatorName());
   1389   return 0;
   1390 }
   1391 
   1392 //===----------------------------------------------------------------------===//
   1393 // Top-Level parsing and JIT Driver
   1394 //===----------------------------------------------------------------------===//
   1395 
   1396 static void HandleDefinition() {
   1397   if (FunctionAST *F = ParseDefinition()) {
   1398     TheHelper->closeCurrentModule();
   1399     if (Function *LF = F->Codegen()) {
   1400 #ifndef MINIMAL_STDERR_OUTPUT
   1401       fprintf(stderr, "Read function definition:");
   1402       LF->dump();
   1403 #endif
   1404     }
   1405   } else {
   1406     // Skip token for error recovery.
   1407     getNextToken();
   1408   }
   1409 }
   1410 
   1411 static void HandleExtern() {
   1412   if (PrototypeAST *P = ParseExtern()) {
   1413     if (Function *F = P->Codegen()) {
   1414 #ifndef MINIMAL_STDERR_OUTPUT
   1415       fprintf(stderr, "Read extern: ");
   1416       F->dump();
   1417 #endif
   1418     }
   1419   } else {
   1420     // Skip token for error recovery.
   1421     getNextToken();
   1422   }
   1423 }
   1424 
   1425 static void HandleTopLevelExpression() {
   1426   // Evaluate a top-level expression into an anonymous function.
   1427   if (FunctionAST *F = ParseTopLevelExpr()) {
   1428     if (Function *LF = F->Codegen()) {
   1429       // JIT the function, returning a function pointer.
   1430       void *FPtr = TheHelper->getPointerToFunction(LF);
   1431 
   1432       // Cast it to the right type (takes no arguments, returns a double) so we
   1433       // can call it as a native function.
   1434       double (*FP)() = (double (*)())(intptr_t)FPtr;
   1435 #ifdef MINIMAL_STDERR_OUTPUT
   1436       FP();
   1437 #else
   1438       fprintf(stderr, "Evaluated to %f\n", FP());
   1439 #endif
   1440     }
   1441   } else {
   1442     // Skip token for error recovery.
   1443     getNextToken();
   1444   }
   1445 }
   1446 
   1447 /// top ::= definition | external | expression | ';'
   1448 static void MainLoop() {
   1449   while (1) {
   1450 #ifndef MINIMAL_STDERR_OUTPUT
   1451     fprintf(stderr, "ready> ");
   1452 #endif
   1453     switch (CurTok) {
   1454     case tok_eof:    return;
   1455     case ';':        getNextToken(); break;  // ignore top-level semicolons.
   1456     case tok_def:    HandleDefinition(); break;
   1457     case tok_extern: HandleExtern(); break;
   1458     default:         HandleTopLevelExpression(); break;
   1459     }
   1460   }
   1461 }
   1462 
   1463 //===----------------------------------------------------------------------===//
   1464 // "Library" functions that can be "extern'd" from user code.
   1465 //===----------------------------------------------------------------------===//
   1466 
   1467 /// putchard - putchar that takes a double and returns 0.
   1468 extern "C"
   1469 double putchard(double X) {
   1470   putchar((char)X);
   1471   return 0;
   1472 }
   1473 
   1474 /// printd - printf that takes a double prints it as "%f\n", returning 0.
   1475 extern "C"
   1476 double printd(double X) {
   1477   printf("%f", X);
   1478   return 0;
   1479 }
   1480 
   1481 extern "C"
   1482 double printlf() {
   1483   printf("\n");
   1484   return 0;
   1485 }
   1486 
   1487 //===----------------------------------------------------------------------===//
   1488 // Command line input file handler
   1489 //===----------------------------------------------------------------------===//
   1490 
   1491 Module* parseInputIR(std::string InputFile) {
   1492   SMDiagnostic Err;
   1493   Module *M = ParseIRFile(InputFile, Err, getGlobalContext());
   1494   if (!M) {
   1495     Err.print("IR parsing failed: ", errs());
   1496     return NULL;
   1497   }
   1498 
   1499   char ModID[256];
   1500   sprintf(ModID, "IR:%s", InputFile.c_str());
   1501   M->setModuleIdentifier(ModID);
   1502 
   1503   TheHelper->addModule(M);
   1504   return M;
   1505 }
   1506 
   1507 //===----------------------------------------------------------------------===//
   1508 // Main driver code.
   1509 //===----------------------------------------------------------------------===//
   1510 
   1511 int main(int argc, char **argv) {
   1512   InitializeNativeTarget();
   1513   InitializeNativeTargetAsmPrinter();
   1514   InitializeNativeTargetAsmParser();
   1515   LLVMContext &Context = getGlobalContext();
   1516 
   1517   cl::ParseCommandLineOptions(argc, argv,
   1518                               "Kaleidoscope example program\n");
   1519 
   1520   // Install standard binary operators.
   1521   // 1 is lowest precedence.
   1522   BinopPrecedence['='] = 2;
   1523   BinopPrecedence['<'] = 10;
   1524   BinopPrecedence['+'] = 20;
   1525   BinopPrecedence['-'] = 20;
   1526   BinopPrecedence['/'] = 40;
   1527   BinopPrecedence['*'] = 40;  // highest.
   1528 
   1529   // Prime the first token.
   1530 #ifndef MINIMAL_STDERR_OUTPUT
   1531   fprintf(stderr, "ready> ");
   1532 #endif
   1533   getNextToken();
   1534 
   1535   // Make the helper, which holds all the code.
   1536   TheHelper = new MCJITHelper(Context);
   1537 
   1538   if (!InputIR.empty()) {
   1539     parseInputIR(InputIR);
   1540   }
   1541 
   1542   // Run the main "interpreter loop" now.
   1543   MainLoop();
   1544 
   1545 #ifndef MINIMAL_STDERR_OUTPUT
   1546   // Print out all of the generated code.
   1547   TheHelper->dump();
   1548 #endif
   1549 
   1550   return 0;
   1551 }
   1552