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