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