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