Fix the JIT code for the Kaleidoscope tutorial.
[oota-llvm.git] / examples / Kaleidoscope / Chapter7 / toy.cpp
1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/MCJIT.h"
4 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/IR/Verifier.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Support/TargetSelect.h"
13 #include "llvm/Transforms/Scalar.h"
14 #include <cctype>
15 #include <cstdio>
16 #include <map>
17 #include <string>
18 #include <vector>
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // Lexer
23 //===----------------------------------------------------------------------===//
24
25 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26 // of these for known things.
27 enum Token {
28   tok_eof = -1,
29
30   // commands
31   tok_def = -2, tok_extern = -3,
32
33   // primary
34   tok_identifier = -4, tok_number = -5,
35   
36   // control
37   tok_if = -6, tok_then = -7, tok_else = -8,
38   tok_for = -9, tok_in = -10,
39   
40   // operators
41   tok_binary = -11, tok_unary = -12,
42   
43   // var definition
44   tok_var = -13
45 };
46
47 static std::string IdentifierStr;  // Filled in if tok_identifier
48 static double NumVal;              // Filled in if tok_number
49
50 /// gettok - Return the next token from standard input.
51 static int gettok() {
52   static int LastChar = ' ';
53
54   // Skip any whitespace.
55   while (isspace(LastChar))
56     LastChar = getchar();
57
58   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
59     IdentifierStr = LastChar;
60     while (isalnum((LastChar = getchar())))
61       IdentifierStr += LastChar;
62
63     if (IdentifierStr == "def") return tok_def;
64     if (IdentifierStr == "extern") return tok_extern;
65     if (IdentifierStr == "if") return tok_if;
66     if (IdentifierStr == "then") return tok_then;
67     if (IdentifierStr == "else") return tok_else;
68     if (IdentifierStr == "for") return tok_for;
69     if (IdentifierStr == "in") return tok_in;
70     if (IdentifierStr == "binary") return tok_binary;
71     if (IdentifierStr == "unary") return tok_unary;
72     if (IdentifierStr == "var") return tok_var;
73     return tok_identifier;
74   }
75
76   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
77     std::string NumStr;
78     do {
79       NumStr += LastChar;
80       LastChar = getchar();
81     } while (isdigit(LastChar) || LastChar == '.');
82
83     NumVal = strtod(NumStr.c_str(), 0);
84     return tok_number;
85   }
86
87   if (LastChar == '#') {
88     // Comment until end of line.
89     do LastChar = getchar();
90     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
91     
92     if (LastChar != EOF)
93       return gettok();
94   }
95   
96   // Check for end of file.  Don't eat the EOF.
97   if (LastChar == EOF)
98     return tok_eof;
99
100   // Otherwise, just return the character as its ascii value.
101   int ThisChar = LastChar;
102   LastChar = getchar();
103   return ThisChar;
104 }
105
106 //===----------------------------------------------------------------------===//
107 // Abstract Syntax Tree (aka Parse Tree)
108 //===----------------------------------------------------------------------===//
109 namespace {
110 /// ExprAST - Base class for all expression nodes.
111 class ExprAST {
112 public:
113   virtual ~ExprAST() {}
114   virtual Value *Codegen() = 0;
115 };
116
117 /// NumberExprAST - Expression class for numeric literals like "1.0".
118 class NumberExprAST : public ExprAST {
119   double Val;
120 public:
121   NumberExprAST(double val) : Val(val) {}
122   virtual Value *Codegen();
123 };
124
125 /// VariableExprAST - Expression class for referencing a variable, like "a".
126 class VariableExprAST : public ExprAST {
127   std::string Name;
128 public:
129   VariableExprAST(const std::string &name) : Name(name) {}
130   const std::string &getName() const { return Name; }
131   virtual Value *Codegen();
132 };
133
134 /// UnaryExprAST - Expression class for a unary operator.
135 class UnaryExprAST : public ExprAST {
136   char Opcode;
137   ExprAST *Operand;
138 public:
139   UnaryExprAST(char opcode, ExprAST *operand) 
140     : Opcode(opcode), Operand(operand) {}
141   virtual Value *Codegen();
142 };
143
144 /// BinaryExprAST - Expression class for a binary operator.
145 class BinaryExprAST : public ExprAST {
146   char Op;
147   ExprAST *LHS, *RHS;
148 public:
149   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 
150     : Op(op), LHS(lhs), RHS(rhs) {}
151   virtual Value *Codegen();
152 };
153
154 /// CallExprAST - Expression class for function calls.
155 class CallExprAST : public ExprAST {
156   std::string Callee;
157   std::vector<ExprAST*> Args;
158 public:
159   CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
160     : Callee(callee), Args(args) {}
161   virtual Value *Codegen();
162 };
163
164 /// IfExprAST - Expression class for if/then/else.
165 class IfExprAST : public ExprAST {
166   ExprAST *Cond, *Then, *Else;
167 public:
168   IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
169   : Cond(cond), Then(then), Else(_else) {}
170   virtual Value *Codegen();
171 };
172
173 /// ForExprAST - Expression class for for/in.
174 class ForExprAST : public ExprAST {
175   std::string VarName;
176   ExprAST *Start, *End, *Step, *Body;
177 public:
178   ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
179              ExprAST *step, ExprAST *body)
180     : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
181   virtual Value *Codegen();
182 };
183
184 /// VarExprAST - Expression class for var/in
185 class VarExprAST : public ExprAST {
186   std::vector<std::pair<std::string, ExprAST*> > VarNames;
187   ExprAST *Body;
188 public:
189   VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
190              ExprAST *body)
191   : VarNames(varnames), Body(body) {}
192   
193   virtual Value *Codegen();
194 };
195
196 /// PrototypeAST - This class represents the "prototype" for a function,
197 /// which captures its argument names as well as if it is an operator.
198 class PrototypeAST {
199   std::string Name;
200   std::vector<std::string> Args;
201   bool isOperator;
202   unsigned Precedence;  // Precedence if a binary op.
203 public:
204   PrototypeAST(const std::string &name, const std::vector<std::string> &args,
205                bool isoperator = false, unsigned prec = 0)
206   : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
207   
208   bool isUnaryOp() const { return isOperator && Args.size() == 1; }
209   bool isBinaryOp() const { return isOperator && Args.size() == 2; }
210   
211   char getOperatorName() const {
212     assert(isUnaryOp() || isBinaryOp());
213     return Name[Name.size()-1];
214   }
215   
216   unsigned getBinaryPrecedence() const { return Precedence; }
217   
218   Function *Codegen();
219   
220   void CreateArgumentAllocas(Function *F);
221 };
222
223 /// FunctionAST - This class represents a function definition itself.
224 class FunctionAST {
225   PrototypeAST *Proto;
226   ExprAST *Body;
227 public:
228   FunctionAST(PrototypeAST *proto, ExprAST *body)
229     : Proto(proto), Body(body) {}
230   
231   Function *Codegen();
232 };
233 } // end anonymous namespace
234
235 //===----------------------------------------------------------------------===//
236 // Parser
237 //===----------------------------------------------------------------------===//
238
239 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
240 /// token the parser is looking at.  getNextToken reads another token from the
241 /// lexer and updates CurTok with its results.
242 static int CurTok;
243 static int getNextToken() {
244   return CurTok = gettok();
245 }
246
247 /// BinopPrecedence - This holds the precedence for each binary operator that is
248 /// defined.
249 static std::map<char, int> BinopPrecedence;
250
251 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
252 static int GetTokPrecedence() {
253   if (!isascii(CurTok))
254     return -1;
255   
256   // Make sure it's a declared binop.
257   int TokPrec = BinopPrecedence[CurTok];
258   if (TokPrec <= 0) return -1;
259   return TokPrec;
260 }
261
262 /// Error* - These are little helper functions for error handling.
263 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
264 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
265 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
266
267 static ExprAST *ParseExpression();
268
269 /// identifierexpr
270 ///   ::= identifier
271 ///   ::= identifier '(' expression* ')'
272 static ExprAST *ParseIdentifierExpr() {
273   std::string IdName = IdentifierStr;
274   
275   getNextToken();  // eat identifier.
276   
277   if (CurTok != '(') // Simple variable ref.
278     return new VariableExprAST(IdName);
279   
280   // Call.
281   getNextToken();  // eat (
282   std::vector<ExprAST*> Args;
283   if (CurTok != ')') {
284     while (1) {
285       ExprAST *Arg = ParseExpression();
286       if (!Arg) return 0;
287       Args.push_back(Arg);
288
289       if (CurTok == ')') break;
290
291       if (CurTok != ',')
292         return Error("Expected ')' or ',' in argument list");
293       getNextToken();
294     }
295   }
296
297   // Eat the ')'.
298   getNextToken();
299   
300   return new CallExprAST(IdName, Args);
301 }
302
303 /// numberexpr ::= number
304 static ExprAST *ParseNumberExpr() {
305   ExprAST *Result = new NumberExprAST(NumVal);
306   getNextToken(); // consume the number
307   return Result;
308 }
309
310 /// parenexpr ::= '(' expression ')'
311 static ExprAST *ParseParenExpr() {
312   getNextToken();  // eat (.
313   ExprAST *V = ParseExpression();
314   if (!V) return 0;
315   
316   if (CurTok != ')')
317     return Error("expected ')'");
318   getNextToken();  // eat ).
319   return V;
320 }
321
322 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
323 static ExprAST *ParseIfExpr() {
324   getNextToken();  // eat the if.
325   
326   // condition.
327   ExprAST *Cond = ParseExpression();
328   if (!Cond) return 0;
329   
330   if (CurTok != tok_then)
331     return Error("expected then");
332   getNextToken();  // eat the then
333   
334   ExprAST *Then = ParseExpression();
335   if (Then == 0) return 0;
336   
337   if (CurTok != tok_else)
338     return Error("expected else");
339   
340   getNextToken();
341   
342   ExprAST *Else = ParseExpression();
343   if (!Else) return 0;
344   
345   return new IfExprAST(Cond, Then, Else);
346 }
347
348 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
349 static ExprAST *ParseForExpr() {
350   getNextToken();  // eat the for.
351
352   if (CurTok != tok_identifier)
353     return Error("expected identifier after for");
354   
355   std::string IdName = IdentifierStr;
356   getNextToken();  // eat identifier.
357   
358   if (CurTok != '=')
359     return Error("expected '=' after for");
360   getNextToken();  // eat '='.
361   
362   
363   ExprAST *Start = ParseExpression();
364   if (Start == 0) return 0;
365   if (CurTok != ',')
366     return Error("expected ',' after for start value");
367   getNextToken();
368   
369   ExprAST *End = ParseExpression();
370   if (End == 0) return 0;
371   
372   // The step value is optional.
373   ExprAST *Step = 0;
374   if (CurTok == ',') {
375     getNextToken();
376     Step = ParseExpression();
377     if (Step == 0) return 0;
378   }
379   
380   if (CurTok != tok_in)
381     return Error("expected 'in' after for");
382   getNextToken();  // eat 'in'.
383   
384   ExprAST *Body = ParseExpression();
385   if (Body == 0) return 0;
386
387   return new ForExprAST(IdName, Start, End, Step, Body);
388 }
389
390 /// varexpr ::= 'var' identifier ('=' expression)? 
391 //                    (',' identifier ('=' expression)?)* 'in' expression
392 static ExprAST *ParseVarExpr() {
393   getNextToken();  // eat the var.
394
395   std::vector<std::pair<std::string, ExprAST*> > VarNames;
396
397   // At least one variable name is required.
398   if (CurTok != tok_identifier)
399     return Error("expected identifier after var");
400   
401   while (1) {
402     std::string Name = IdentifierStr;
403     getNextToken();  // eat identifier.
404
405     // Read the optional initializer.
406     ExprAST *Init = 0;
407     if (CurTok == '=') {
408       getNextToken(); // eat the '='.
409       
410       Init = ParseExpression();
411       if (Init == 0) return 0;
412     }
413     
414     VarNames.push_back(std::make_pair(Name, Init));
415     
416     // End of var list, exit loop.
417     if (CurTok != ',') break;
418     getNextToken(); // eat the ','.
419     
420     if (CurTok != tok_identifier)
421       return Error("expected identifier list after var");
422   }
423   
424   // At this point, we have to have 'in'.
425   if (CurTok != tok_in)
426     return Error("expected 'in' keyword after 'var'");
427   getNextToken();  // eat 'in'.
428   
429   ExprAST *Body = ParseExpression();
430   if (Body == 0) return 0;
431   
432   return new VarExprAST(VarNames, Body);
433 }
434
435 /// primary
436 ///   ::= identifierexpr
437 ///   ::= numberexpr
438 ///   ::= parenexpr
439 ///   ::= ifexpr
440 ///   ::= forexpr
441 ///   ::= varexpr
442 static ExprAST *ParsePrimary() {
443   switch (CurTok) {
444   default: return Error("unknown token when expecting an expression");
445   case tok_identifier: return ParseIdentifierExpr();
446   case tok_number:     return ParseNumberExpr();
447   case '(':            return ParseParenExpr();
448   case tok_if:         return ParseIfExpr();
449   case tok_for:        return ParseForExpr();
450   case tok_var:        return ParseVarExpr();
451   }
452 }
453
454 /// unary
455 ///   ::= primary
456 ///   ::= '!' unary
457 static ExprAST *ParseUnary() {
458   // If the current token is not an operator, it must be a primary expr.
459   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
460     return ParsePrimary();
461   
462   // If this is a unary operator, read it.
463   int Opc = CurTok;
464   getNextToken();
465   if (ExprAST *Operand = ParseUnary())
466     return new UnaryExprAST(Opc, Operand);
467   return 0;
468 }
469
470 /// binoprhs
471 ///   ::= ('+' unary)*
472 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
473   // If this is a binop, find its precedence.
474   while (1) {
475     int TokPrec = GetTokPrecedence();
476     
477     // If this is a binop that binds at least as tightly as the current binop,
478     // consume it, otherwise we are done.
479     if (TokPrec < ExprPrec)
480       return LHS;
481     
482     // Okay, we know this is a binop.
483     int BinOp = CurTok;
484     getNextToken();  // eat binop
485     
486     // Parse the unary expression after the binary operator.
487     ExprAST *RHS = ParseUnary();
488     if (!RHS) return 0;
489     
490     // If BinOp binds less tightly with RHS than the operator after RHS, let
491     // the pending operator take RHS as its LHS.
492     int NextPrec = GetTokPrecedence();
493     if (TokPrec < NextPrec) {
494       RHS = ParseBinOpRHS(TokPrec+1, RHS);
495       if (RHS == 0) return 0;
496     }
497     
498     // Merge LHS/RHS.
499     LHS = new BinaryExprAST(BinOp, LHS, RHS);
500   }
501 }
502
503 /// expression
504 ///   ::= unary binoprhs
505 ///
506 static ExprAST *ParseExpression() {
507   ExprAST *LHS = ParseUnary();
508   if (!LHS) return 0;
509   
510   return ParseBinOpRHS(0, LHS);
511 }
512
513 /// prototype
514 ///   ::= id '(' id* ')'
515 ///   ::= binary LETTER number? (id, id)
516 ///   ::= unary LETTER (id)
517 static PrototypeAST *ParsePrototype() {
518   std::string FnName;
519   
520   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
521   unsigned BinaryPrecedence = 30;
522   
523   switch (CurTok) {
524   default:
525     return ErrorP("Expected function name in prototype");
526   case tok_identifier:
527     FnName = IdentifierStr;
528     Kind = 0;
529     getNextToken();
530     break;
531   case tok_unary:
532     getNextToken();
533     if (!isascii(CurTok))
534       return ErrorP("Expected unary operator");
535     FnName = "unary";
536     FnName += (char)CurTok;
537     Kind = 1;
538     getNextToken();
539     break;
540   case tok_binary:
541     getNextToken();
542     if (!isascii(CurTok))
543       return ErrorP("Expected binary operator");
544     FnName = "binary";
545     FnName += (char)CurTok;
546     Kind = 2;
547     getNextToken();
548     
549     // Read the precedence if present.
550     if (CurTok == tok_number) {
551       if (NumVal < 1 || NumVal > 100)
552         return ErrorP("Invalid precedecnce: must be 1..100");
553       BinaryPrecedence = (unsigned)NumVal;
554       getNextToken();
555     }
556     break;
557   }
558   
559   if (CurTok != '(')
560     return ErrorP("Expected '(' in prototype");
561   
562   std::vector<std::string> ArgNames;
563   while (getNextToken() == tok_identifier)
564     ArgNames.push_back(IdentifierStr);
565   if (CurTok != ')')
566     return ErrorP("Expected ')' in prototype");
567   
568   // success.
569   getNextToken();  // eat ')'.
570   
571   // Verify right number of names for operator.
572   if (Kind && ArgNames.size() != Kind)
573     return ErrorP("Invalid number of operands for operator");
574   
575   return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
576 }
577
578 /// definition ::= 'def' prototype expression
579 static FunctionAST *ParseDefinition() {
580   getNextToken();  // eat def.
581   PrototypeAST *Proto = ParsePrototype();
582   if (Proto == 0) return 0;
583
584   if (ExprAST *E = ParseExpression())
585     return new FunctionAST(Proto, E);
586   return 0;
587 }
588
589 /// toplevelexpr ::= expression
590 static FunctionAST *ParseTopLevelExpr() {
591   if (ExprAST *E = ParseExpression()) {
592     // Make an anonymous proto.
593     PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
594     return new FunctionAST(Proto, E);
595   }
596   return 0;
597 }
598
599 /// external ::= 'extern' prototype
600 static PrototypeAST *ParseExtern() {
601   getNextToken();  // eat extern.
602   return ParsePrototype();
603 }
604
605 //===----------------------------------------------------------------------===//
606 // Code Generation
607 //===----------------------------------------------------------------------===//
608
609 static Module *TheModule;
610 static IRBuilder<> Builder(getGlobalContext());
611 static std::map<std::string, AllocaInst*> NamedValues;
612 static FunctionPassManager *TheFPM;
613
614 Value *ErrorV(const char *Str) { Error(Str); return 0; }
615
616 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
617 /// the function.  This is used for mutable variables etc.
618 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
619                                           const std::string &VarName) {
620   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
621                  TheFunction->getEntryBlock().begin());
622   return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
623                            VarName.c_str());
624 }
625
626 Value *NumberExprAST::Codegen() {
627   return ConstantFP::get(getGlobalContext(), APFloat(Val));
628 }
629
630 Value *VariableExprAST::Codegen() {
631   // Look this variable up in the function.
632   Value *V = NamedValues[Name];
633   if (V == 0) return ErrorV("Unknown variable name");
634
635   // Load the value.
636   return Builder.CreateLoad(V, Name.c_str());
637 }
638
639 Value *UnaryExprAST::Codegen() {
640   Value *OperandV = Operand->Codegen();
641   if (OperandV == 0) return 0;
642   
643   Function *F = TheModule->getFunction(std::string("unary")+Opcode);
644   if (F == 0)
645     return ErrorV("Unknown unary operator");
646   
647   return Builder.CreateCall(F, OperandV, "unop");
648 }
649
650 Value *BinaryExprAST::Codegen() {
651   // Special case '=' because we don't want to emit the LHS as an expression.
652   if (Op == '=') {
653     // Assignment requires the LHS to be an identifier.
654     VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
655     if (!LHSE)
656       return ErrorV("destination of '=' must be a variable");
657     // Codegen the RHS.
658     Value *Val = RHS->Codegen();
659     if (Val == 0) return 0;
660
661     // Look up the name.
662     Value *Variable = NamedValues[LHSE->getName()];
663     if (Variable == 0) return ErrorV("Unknown variable name");
664
665     Builder.CreateStore(Val, Variable);
666     return Val;
667   }
668   
669   Value *L = LHS->Codegen();
670   Value *R = RHS->Codegen();
671   if (L == 0 || R == 0) return 0;
672   
673   switch (Op) {
674   case '+': return Builder.CreateFAdd(L, R, "addtmp");
675   case '-': return Builder.CreateFSub(L, R, "subtmp");
676   case '*': return Builder.CreateFMul(L, R, "multmp");    
677   case '<':
678     L = Builder.CreateFCmpULT(L, R, "cmptmp");
679     // Convert bool 0/1 to double 0.0 or 1.0
680     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
681                                 "booltmp");
682   default: break;
683   }
684   
685   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
686   // a call to it.
687   Function *F = TheModule->getFunction(std::string("binary")+Op);
688   assert(F && "binary operator not found!");
689   
690   Value *Ops[] = { L, R };
691   return Builder.CreateCall(F, Ops, "binop");
692 }
693
694 Value *CallExprAST::Codegen() {
695   // Look up the name in the global module table.
696   Function *CalleeF = TheModule->getFunction(Callee);
697   if (CalleeF == 0)
698     return ErrorV("Unknown function referenced");
699   
700   // If argument mismatch error.
701   if (CalleeF->arg_size() != Args.size())
702     return ErrorV("Incorrect # arguments passed");
703
704   std::vector<Value*> ArgsV;
705   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
706     ArgsV.push_back(Args[i]->Codegen());
707     if (ArgsV.back() == 0) return 0;
708   }
709   
710   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
711 }
712
713 Value *IfExprAST::Codegen() {
714   Value *CondV = Cond->Codegen();
715   if (CondV == 0) return 0;
716   
717   // Convert condition to a bool by comparing equal to 0.0.
718   CondV = Builder.CreateFCmpONE(CondV, 
719                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
720                                 "ifcond");
721   
722   Function *TheFunction = Builder.GetInsertBlock()->getParent();
723   
724   // Create blocks for the then and else cases.  Insert the 'then' block at the
725   // end of the function.
726   BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
727   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
728   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
729   
730   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
731   
732   // Emit then value.
733   Builder.SetInsertPoint(ThenBB);
734   
735   Value *ThenV = Then->Codegen();
736   if (ThenV == 0) return 0;
737   
738   Builder.CreateBr(MergeBB);
739   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
740   ThenBB = Builder.GetInsertBlock();
741   
742   // Emit else block.
743   TheFunction->getBasicBlockList().push_back(ElseBB);
744   Builder.SetInsertPoint(ElseBB);
745   
746   Value *ElseV = Else->Codegen();
747   if (ElseV == 0) return 0;
748   
749   Builder.CreateBr(MergeBB);
750   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
751   ElseBB = Builder.GetInsertBlock();
752   
753   // Emit merge block.
754   TheFunction->getBasicBlockList().push_back(MergeBB);
755   Builder.SetInsertPoint(MergeBB);
756   PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
757                                   "iftmp");
758   
759   PN->addIncoming(ThenV, ThenBB);
760   PN->addIncoming(ElseV, ElseBB);
761   return PN;
762 }
763
764 Value *ForExprAST::Codegen() {
765   // Output this as:
766   //   var = alloca double
767   //   ...
768   //   start = startexpr
769   //   store start -> var
770   //   goto loop
771   // loop: 
772   //   ...
773   //   bodyexpr
774   //   ...
775   // loopend:
776   //   step = stepexpr
777   //   endcond = endexpr
778   //
779   //   curvar = load var
780   //   nextvar = curvar + step
781   //   store nextvar -> var
782   //   br endcond, loop, endloop
783   // outloop:
784   
785   Function *TheFunction = Builder.GetInsertBlock()->getParent();
786
787   // Create an alloca for the variable in the entry block.
788   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
789   
790   // Emit the start code first, without 'variable' in scope.
791   Value *StartVal = Start->Codegen();
792   if (StartVal == 0) return 0;
793   
794   // Store the value into the alloca.
795   Builder.CreateStore(StartVal, Alloca);
796   
797   // Make the new basic block for the loop header, inserting after current
798   // block.
799   BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
800   
801   // Insert an explicit fall through from the current block to the LoopBB.
802   Builder.CreateBr(LoopBB);
803
804   // Start insertion in LoopBB.
805   Builder.SetInsertPoint(LoopBB);
806   
807   // Within the loop, the variable is defined equal to the PHI node.  If it
808   // shadows an existing variable, we have to restore it, so save it now.
809   AllocaInst *OldVal = NamedValues[VarName];
810   NamedValues[VarName] = Alloca;
811   
812   // Emit the body of the loop.  This, like any other expr, can change the
813   // current BB.  Note that we ignore the value computed by the body, but don't
814   // allow an error.
815   if (Body->Codegen() == 0)
816     return 0;
817   
818   // Emit the step value.
819   Value *StepVal;
820   if (Step) {
821     StepVal = Step->Codegen();
822     if (StepVal == 0) return 0;
823   } else {
824     // If not specified, use 1.0.
825     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
826   }
827   
828   // Compute the end condition.
829   Value *EndCond = End->Codegen();
830   if (EndCond == 0) return EndCond;
831   
832   // Reload, increment, and restore the alloca.  This handles the case where
833   // the body of the loop mutates the variable.
834   Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
835   Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
836   Builder.CreateStore(NextVar, Alloca);
837   
838   // Convert condition to a bool by comparing equal to 0.0.
839   EndCond = Builder.CreateFCmpONE(EndCond, 
840                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
841                                   "loopcond");
842   
843   // Create the "after loop" block and insert it.
844   BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
845   
846   // Insert the conditional branch into the end of LoopEndBB.
847   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
848   
849   // Any new code will be inserted in AfterBB.
850   Builder.SetInsertPoint(AfterBB);
851   
852   // Restore the unshadowed variable.
853   if (OldVal)
854     NamedValues[VarName] = OldVal;
855   else
856     NamedValues.erase(VarName);
857
858   
859   // for expr always returns 0.0.
860   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
861 }
862
863 Value *VarExprAST::Codegen() {
864   std::vector<AllocaInst *> OldBindings;
865   
866   Function *TheFunction = Builder.GetInsertBlock()->getParent();
867
868   // Register all variables and emit their initializer.
869   for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
870     const std::string &VarName = VarNames[i].first;
871     ExprAST *Init = VarNames[i].second;
872     
873     // Emit the initializer before adding the variable to scope, this prevents
874     // the initializer from referencing the variable itself, and permits stuff
875     // like this:
876     //  var a = 1 in
877     //    var a = a in ...   # refers to outer 'a'.
878     Value *InitVal;
879     if (Init) {
880       InitVal = Init->Codegen();
881       if (InitVal == 0) return 0;
882     } else { // If not specified, use 0.0.
883       InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
884     }
885     
886     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
887     Builder.CreateStore(InitVal, Alloca);
888
889     // Remember the old variable binding so that we can restore the binding when
890     // we unrecurse.
891     OldBindings.push_back(NamedValues[VarName]);
892     
893     // Remember this binding.
894     NamedValues[VarName] = Alloca;
895   }
896   
897   // Codegen the body, now that all vars are in scope.
898   Value *BodyVal = Body->Codegen();
899   if (BodyVal == 0) return 0;
900   
901   // Pop all our variables from scope.
902   for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
903     NamedValues[VarNames[i].first] = OldBindings[i];
904
905   // Return the body computation.
906   return BodyVal;
907 }
908
909 Function *PrototypeAST::Codegen() {
910   // Make the function type:  double(double,double) etc.
911   std::vector<Type*> Doubles(Args.size(), 
912                              Type::getDoubleTy(getGlobalContext()));
913   FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
914                                        Doubles, false);
915   
916   Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
917   
918   // If F conflicted, there was already something named 'Name'.  If it has a
919   // body, don't allow redefinition or reextern.
920   if (F->getName() != Name) {
921     // Delete the one we just made and get the existing one.
922     F->eraseFromParent();
923     F = TheModule->getFunction(Name);
924     
925     // If F already has a body, reject this.
926     if (!F->empty()) {
927       ErrorF("redefinition of function");
928       return 0;
929     }
930     
931     // If F took a different number of args, reject.
932     if (F->arg_size() != Args.size()) {
933       ErrorF("redefinition of function with different # args");
934       return 0;
935     }
936   }
937   
938   // Set names for all arguments.
939   unsigned Idx = 0;
940   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
941        ++AI, ++Idx)
942     AI->setName(Args[Idx]);
943     
944   return F;
945 }
946
947 /// CreateArgumentAllocas - Create an alloca for each argument and register the
948 /// argument in the symbol table so that references to it will succeed.
949 void PrototypeAST::CreateArgumentAllocas(Function *F) {
950   Function::arg_iterator AI = F->arg_begin();
951   for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
952     // Create an alloca for this variable.
953     AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
954
955     // Store the initial value into the alloca.
956     Builder.CreateStore(AI, Alloca);
957
958     // Add arguments to variable symbol table.
959     NamedValues[Args[Idx]] = Alloca;
960   }
961 }
962
963 Function *FunctionAST::Codegen() {
964   NamedValues.clear();
965   
966   Function *TheFunction = Proto->Codegen();
967   if (TheFunction == 0)
968     return 0;
969   
970   // If this is an operator, install it.
971   if (Proto->isBinaryOp())
972     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
973   
974   // Create a new basic block to start insertion into.
975   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
976   Builder.SetInsertPoint(BB);
977   
978   // Add all arguments to the symbol table and create their allocas.
979   Proto->CreateArgumentAllocas(TheFunction);
980
981   if (Value *RetVal = Body->Codegen()) {
982     // Finish off the function.
983     Builder.CreateRet(RetVal);
984
985     // Validate the generated code, checking for consistency.
986     verifyFunction(*TheFunction);
987
988     // Optimize the function.
989     TheFPM->run(*TheFunction);
990     
991     return TheFunction;
992   }
993   
994   // Error reading body, remove function.
995   TheFunction->eraseFromParent();
996
997   if (Proto->isBinaryOp())
998     BinopPrecedence.erase(Proto->getOperatorName());
999   return 0;
1000 }
1001
1002 //===----------------------------------------------------------------------===//
1003 // Top-Level parsing and JIT Driver
1004 //===----------------------------------------------------------------------===//
1005
1006 static ExecutionEngine *TheExecutionEngine;
1007
1008 static void HandleDefinition() {
1009   if (FunctionAST *F = ParseDefinition()) {
1010     if (Function *LF = F->Codegen()) {
1011       fprintf(stderr, "Read function definition:");
1012       LF->dump();
1013     }
1014   } else {
1015     // Skip token for error recovery.
1016     getNextToken();
1017   }
1018 }
1019
1020 static void HandleExtern() {
1021   if (PrototypeAST *P = ParseExtern()) {
1022     if (Function *F = P->Codegen()) {
1023       fprintf(stderr, "Read extern: ");
1024       F->dump();
1025     }
1026   } else {
1027     // Skip token for error recovery.
1028     getNextToken();
1029   }
1030 }
1031
1032 static void HandleTopLevelExpression() {
1033   // Evaluate a top-level expression into an anonymous function.
1034   if (FunctionAST *F = ParseTopLevelExpr()) {
1035     if (Function *LF = F->Codegen()) {
1036       TheExecutionEngine->finalizeObject();
1037       // JIT the function, returning a function pointer.
1038       void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1039       
1040       // Cast it to the right type (takes no arguments, returns a double) so we
1041       // can call it as a native function.
1042       double (*FP)() = (double (*)())(intptr_t)FPtr;
1043       fprintf(stderr, "Evaluated to %f\n", FP());
1044     }
1045   } else {
1046     // Skip token for error recovery.
1047     getNextToken();
1048   }
1049 }
1050
1051 /// top ::= definition | external | expression | ';'
1052 static void MainLoop() {
1053   while (1) {
1054     fprintf(stderr, "ready> ");
1055     switch (CurTok) {
1056     case tok_eof:    return;
1057     case ';':        getNextToken(); break;  // ignore top-level semicolons.
1058     case tok_def:    HandleDefinition(); break;
1059     case tok_extern: HandleExtern(); break;
1060     default:         HandleTopLevelExpression(); break;
1061     }
1062   }
1063 }
1064
1065 //===----------------------------------------------------------------------===//
1066 // "Library" functions that can be "extern'd" from user code.
1067 //===----------------------------------------------------------------------===//
1068
1069 /// putchard - putchar that takes a double and returns 0.
1070 extern "C" 
1071 double putchard(double X) {
1072   putchar((char)X);
1073   return 0;
1074 }
1075
1076 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1077 extern "C" 
1078 double printd(double X) {
1079   printf("%f\n", X);
1080   return 0;
1081 }
1082
1083 //===----------------------------------------------------------------------===//
1084 // Main driver code.
1085 //===----------------------------------------------------------------------===//
1086
1087 int main() {
1088   InitializeNativeTarget();
1089   InitializeNativeTargetAsmPrinter();
1090   InitializeNativeTargetAsmParser();
1091   LLVMContext &Context = getGlobalContext();
1092
1093   // Install standard binary operators.
1094   // 1 is lowest precedence.
1095   BinopPrecedence['='] = 2;
1096   BinopPrecedence['<'] = 10;
1097   BinopPrecedence['+'] = 20;
1098   BinopPrecedence['-'] = 20;
1099   BinopPrecedence['*'] = 40;  // highest.
1100
1101   // Prime the first token.
1102   fprintf(stderr, "ready> ");
1103   getNextToken();
1104
1105   // Make the module, which holds all the code.
1106   std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1107   TheModule = Owner.get();
1108
1109   // Create the JIT.  This takes ownership of the module.
1110   std::string ErrStr;
1111   TheExecutionEngine = EngineBuilder(std::move(Owner))
1112                            .setErrorStr(&ErrStr)
1113                            .setMCJITMemoryManager(new SectionMemoryManager())
1114                            .create();
1115   if (!TheExecutionEngine) {
1116     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1117     exit(1);
1118   }
1119
1120   FunctionPassManager OurFPM(TheModule);
1121
1122   // Set up the optimizer pipeline.  Start with registering info about how the
1123   // target lays out data structures.
1124   TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1125   OurFPM.add(new DataLayoutPass());
1126   // Provide basic AliasAnalysis support for GVN.
1127   OurFPM.add(createBasicAliasAnalysisPass());
1128   // Promote allocas to registers.
1129   OurFPM.add(createPromoteMemoryToRegisterPass());
1130   // Do simple "peephole" optimizations and bit-twiddling optzns.
1131   OurFPM.add(createInstructionCombiningPass());
1132   // Reassociate expressions.
1133   OurFPM.add(createReassociatePass());
1134   // Eliminate Common SubExpressions.
1135   OurFPM.add(createGVNPass());
1136   // Simplify the control flow graph (deleting unreachable blocks, etc).
1137   OurFPM.add(createCFGSimplificationPass());
1138
1139   OurFPM.doInitialization();
1140
1141   // Set the global so the code gen can use this.
1142   TheFPM = &OurFPM;
1143
1144   // Run the main "interpreter loop" now.
1145   MainLoop();
1146
1147   TheFPM = 0;
1148
1149   // Print out all of the generated code.
1150   TheModule->dump();
1151
1152   return 0;
1153 }