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