b68f807e3e7af29289e154baf9a565d82fad6dbc
[oota-llvm.git] / examples / Kaleidoscope / Orc / fully_lazy / toy.cpp
1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
3 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
4 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
5 #include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
6 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
7 #include "llvm/ExecutionEngine/Orc/OrcTargetSupport.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/LLVMContext.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/TargetSelect.h"
16 #include "llvm/Transforms/Scalar.h"
17 #include <cctype>
18 #include <iomanip>
19 #include <iostream>
20 #include <map>
21 #include <sstream>
22 #include <string>
23 #include <vector>
24
25 using namespace llvm;
26 using namespace llvm::orc;
27
28 //===----------------------------------------------------------------------===//
29 // Lexer
30 //===----------------------------------------------------------------------===//
31
32 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
33 // of these for known things.
34 enum Token {
35   tok_eof = -1,
36
37   // commands
38   tok_def = -2, tok_extern = -3,
39
40   // primary
41   tok_identifier = -4, tok_number = -5,
42   
43   // control
44   tok_if = -6, tok_then = -7, tok_else = -8,
45   tok_for = -9, tok_in = -10,
46   
47   // operators
48   tok_binary = -11, tok_unary = -12,
49   
50   // var definition
51   tok_var = -13
52 };
53
54 static std::string IdentifierStr;  // Filled in if tok_identifier
55 static double NumVal;              // Filled in if tok_number
56
57 /// gettok - Return the next token from standard input.
58 static int gettok() {
59   static int LastChar = ' ';
60
61   // Skip any whitespace.
62   while (isspace(LastChar))
63     LastChar = getchar();
64
65   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
66     IdentifierStr = LastChar;
67     while (isalnum((LastChar = getchar())))
68       IdentifierStr += LastChar;
69
70     if (IdentifierStr == "def") return tok_def;
71     if (IdentifierStr == "extern") return tok_extern;
72     if (IdentifierStr == "if") return tok_if;
73     if (IdentifierStr == "then") return tok_then;
74     if (IdentifierStr == "else") return tok_else;
75     if (IdentifierStr == "for") return tok_for;
76     if (IdentifierStr == "in") return tok_in;
77     if (IdentifierStr == "binary") return tok_binary;
78     if (IdentifierStr == "unary") return tok_unary;
79     if (IdentifierStr == "var") return tok_var;
80     return tok_identifier;
81   }
82
83   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
84     std::string NumStr;
85     do {
86       NumStr += LastChar;
87       LastChar = getchar();
88     } while (isdigit(LastChar) || LastChar == '.');
89
90     NumVal = strtod(NumStr.c_str(), 0);
91     return tok_number;
92   }
93
94   if (LastChar == '#') {
95     // Comment until end of line.
96     do LastChar = getchar();
97     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
98     
99     if (LastChar != EOF)
100       return gettok();
101   }
102   
103   // Check for end of file.  Don't eat the EOF.
104   if (LastChar == EOF)
105     return tok_eof;
106
107   // Otherwise, just return the character as its ascii value.
108   int ThisChar = LastChar;
109   LastChar = getchar();
110   return ThisChar;
111 }
112
113 //===----------------------------------------------------------------------===//
114 // Abstract Syntax Tree (aka Parse Tree)
115 //===----------------------------------------------------------------------===//
116
117 class IRGenContext;
118
119 /// ExprAST - Base class for all expression nodes.
120 struct ExprAST {
121   virtual ~ExprAST() {}
122   virtual Value *IRGen(IRGenContext &C) const = 0;
123 };
124
125 /// NumberExprAST - Expression class for numeric literals like "1.0".
126 struct NumberExprAST : public ExprAST {
127   NumberExprAST(double Val) : Val(Val) {}
128   Value *IRGen(IRGenContext &C) const override;
129
130   double Val;
131 };
132
133 /// VariableExprAST - Expression class for referencing a variable, like "a".
134 struct VariableExprAST : public ExprAST {
135   VariableExprAST(std::string Name) : Name(std::move(Name)) {}
136   Value *IRGen(IRGenContext &C) const override;
137
138   std::string Name;
139 };
140
141 /// UnaryExprAST - Expression class for a unary operator.
142 struct UnaryExprAST : public ExprAST {
143   UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand) 
144     : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
145
146   Value *IRGen(IRGenContext &C) const override;
147
148   char Opcode;
149   std::unique_ptr<ExprAST> Operand;
150 };
151
152 /// BinaryExprAST - Expression class for a binary operator.
153 struct BinaryExprAST : public ExprAST {
154   BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
155                 std::unique_ptr<ExprAST> RHS) 
156     : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
157
158   Value *IRGen(IRGenContext &C) const override;
159
160   char Op;
161   std::unique_ptr<ExprAST> LHS, RHS;
162 };
163
164 /// CallExprAST - Expression class for function calls.
165 struct CallExprAST : public ExprAST {
166   CallExprAST(std::string CalleeName,
167               std::vector<std::unique_ptr<ExprAST>> Args)
168     : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
169
170   Value *IRGen(IRGenContext &C) const override;
171
172   std::string CalleeName;
173   std::vector<std::unique_ptr<ExprAST>> Args;
174 };
175
176 /// IfExprAST - Expression class for if/then/else.
177 struct IfExprAST : public ExprAST {
178   IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
179             std::unique_ptr<ExprAST> Else)
180     : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
181   Value *IRGen(IRGenContext &C) const override;
182
183   std::unique_ptr<ExprAST> Cond, Then, Else;
184 };
185
186 /// ForExprAST - Expression class for for/in.
187 struct ForExprAST : public ExprAST {
188   ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
189              std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
190              std::unique_ptr<ExprAST> Body)
191     : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
192       Step(std::move(Step)), Body(std::move(Body)) {}
193
194   Value *IRGen(IRGenContext &C) const override;
195
196   std::string VarName;
197   std::unique_ptr<ExprAST> Start, End, Step, Body;
198 };
199
200 /// VarExprAST - Expression class for var/in
201 struct VarExprAST : public ExprAST {
202   typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
203   typedef std::vector<Binding> BindingList;
204
205   VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
206     : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
207
208   Value *IRGen(IRGenContext &C) const override;
209
210   BindingList VarBindings;
211   std::unique_ptr<ExprAST> Body;
212 };
213
214 /// PrototypeAST - This class represents the "prototype" for a function,
215 /// which captures its argument names as well as if it is an operator.
216 struct PrototypeAST {
217   PrototypeAST(std::string Name, std::vector<std::string> Args,
218                bool IsOperator = false, unsigned Precedence = 0)
219     : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
220       Precedence(Precedence) {}
221
222   Function *IRGen(IRGenContext &C) const;
223   void CreateArgumentAllocas(Function *F, IRGenContext &C);
224
225   bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
226   bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
227   
228   char getOperatorName() const {
229     assert(isUnaryOp() || isBinaryOp());
230     return Name[Name.size()-1];
231   }
232
233   std::string Name;
234   std::vector<std::string> Args;
235   bool IsOperator;
236   unsigned Precedence;  // Precedence if a binary op.
237 };
238
239 /// FunctionAST - This class represents a function definition itself.
240 struct FunctionAST {
241   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
242               std::unique_ptr<ExprAST> Body)
243     : Proto(std::move(Proto)), Body(std::move(Body)) {}
244
245   Function *IRGen(IRGenContext &C) const;
246
247   std::unique_ptr<PrototypeAST> Proto;
248   std::unique_ptr<ExprAST> Body;
249 };
250
251 //===----------------------------------------------------------------------===//
252 // Parser
253 //===----------------------------------------------------------------------===//
254
255 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
256 /// token the parser is looking at.  getNextToken reads another token from the
257 /// lexer and updates CurTok with its results.
258 static int CurTok;
259 static int getNextToken() {
260   return CurTok = gettok();
261 }
262
263 /// BinopPrecedence - This holds the precedence for each binary operator that is
264 /// defined.
265 static std::map<char, int> BinopPrecedence;
266
267 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
268 static int GetTokPrecedence() {
269   if (!isascii(CurTok))
270     return -1;
271   
272   // Make sure it's a declared binop.
273   int TokPrec = BinopPrecedence[CurTok];
274   if (TokPrec <= 0) return -1;
275   return TokPrec;
276 }
277
278 template <typename T>
279 std::unique_ptr<T> ErrorU(const std::string &Str) {
280   std::cerr << "Error: " << Str << "\n";
281   return nullptr;
282 }
283
284 template <typename T>
285 T* ErrorP(const std::string &Str) {
286   std::cerr << "Error: " << Str << "\n";
287   return nullptr;
288 }
289
290 static std::unique_ptr<ExprAST> ParseExpression();
291
292 /// identifierexpr
293 ///   ::= identifier
294 ///   ::= identifier '(' expression* ')'
295 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
296   std::string IdName = IdentifierStr;
297   
298   getNextToken();  // eat identifier.
299   
300   if (CurTok != '(') // Simple variable ref.
301     return llvm::make_unique<VariableExprAST>(IdName);
302   
303   // Call.
304   getNextToken();  // eat (
305   std::vector<std::unique_ptr<ExprAST>> Args;
306   if (CurTok != ')') {
307     while (1) {
308       auto Arg = ParseExpression();
309       if (!Arg) return nullptr;
310       Args.push_back(std::move(Arg));
311
312       if (CurTok == ')') break;
313
314       if (CurTok != ',')
315         return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
316       getNextToken();
317     }
318   }
319
320   // Eat the ')'.
321   getNextToken();
322   
323   return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
324 }
325
326 /// numberexpr ::= number
327 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
328   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
329   getNextToken(); // consume the number
330   return Result;
331 }
332
333 /// parenexpr ::= '(' expression ')'
334 static std::unique_ptr<ExprAST> ParseParenExpr() {
335   getNextToken();  // eat (.
336   auto V = ParseExpression();
337   if (!V)
338     return nullptr;
339   
340   if (CurTok != ')')
341     return ErrorU<ExprAST>("expected ')'");
342   getNextToken();  // eat ).
343   return V;
344 }
345
346 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
347 static std::unique_ptr<ExprAST> ParseIfExpr() {
348   getNextToken();  // eat the if.
349   
350   // condition.
351   auto Cond = ParseExpression();
352   if (!Cond)
353     return nullptr;
354   
355   if (CurTok != tok_then)
356     return ErrorU<ExprAST>("expected then");
357   getNextToken();  // eat the then
358   
359   auto Then = ParseExpression();
360   if (!Then)
361     return nullptr;
362   
363   if (CurTok != tok_else)
364     return ErrorU<ExprAST>("expected else");
365   
366   getNextToken();
367   
368   auto Else = ParseExpression();
369   if (!Else)
370     return nullptr;
371   
372   return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
373                                       std::move(Else));
374 }
375
376 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
377 static std::unique_ptr<ForExprAST> ParseForExpr() {
378   getNextToken();  // eat the for.
379
380   if (CurTok != tok_identifier)
381     return ErrorU<ForExprAST>("expected identifier after for");
382   
383   std::string IdName = IdentifierStr;
384   getNextToken();  // eat identifier.
385   
386   if (CurTok != '=')
387     return ErrorU<ForExprAST>("expected '=' after for");
388   getNextToken();  // eat '='.
389   
390   
391   auto Start = ParseExpression();
392   if (!Start)
393     return nullptr;
394   if (CurTok != ',')
395     return ErrorU<ForExprAST>("expected ',' after for start value");
396   getNextToken();
397   
398   auto End = ParseExpression();
399   if (!End)
400     return nullptr;
401   
402   // The step value is optional.
403   std::unique_ptr<ExprAST> Step;
404   if (CurTok == ',') {
405     getNextToken();
406     Step = ParseExpression();
407     if (!Step)
408       return nullptr;
409   }
410   
411   if (CurTok != tok_in)
412     return ErrorU<ForExprAST>("expected 'in' after for");
413   getNextToken();  // eat 'in'.
414   
415   auto Body = ParseExpression();
416   if (Body)
417     return nullptr;
418
419   return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
420                                        std::move(Step), std::move(Body));
421 }
422
423 /// varexpr ::= 'var' identifier ('=' expression)? 
424 //                    (',' identifier ('=' expression)?)* 'in' expression
425 static std::unique_ptr<VarExprAST> ParseVarExpr() {
426   getNextToken();  // eat the var.
427
428   VarExprAST::BindingList VarBindings;
429
430   // At least one variable name is required.
431   if (CurTok != tok_identifier)
432     return ErrorU<VarExprAST>("expected identifier after var");
433   
434   while (1) {
435     std::string Name = IdentifierStr;
436     getNextToken();  // eat identifier.
437
438     // Read the optional initializer.
439     std::unique_ptr<ExprAST> Init;
440     if (CurTok == '=') {
441       getNextToken(); // eat the '='.
442       
443       Init = ParseExpression();
444       if (!Init)
445         return nullptr;
446     }
447     
448     VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
449     
450     // End of var list, exit loop.
451     if (CurTok != ',') break;
452     getNextToken(); // eat the ','.
453     
454     if (CurTok != tok_identifier)
455       return ErrorU<VarExprAST>("expected identifier list after var");
456   }
457   
458   // At this point, we have to have 'in'.
459   if (CurTok != tok_in)
460     return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
461   getNextToken();  // eat 'in'.
462   
463   auto Body = ParseExpression();
464   if (!Body)
465     return nullptr;
466   
467   return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
468 }
469
470 /// primary
471 ///   ::= identifierexpr
472 ///   ::= numberexpr
473 ///   ::= parenexpr
474 ///   ::= ifexpr
475 ///   ::= forexpr
476 ///   ::= varexpr
477 static std::unique_ptr<ExprAST> ParsePrimary() {
478   switch (CurTok) {
479   default: return ErrorU<ExprAST>("unknown token when expecting an expression");
480   case tok_identifier: return ParseIdentifierExpr();
481   case tok_number:     return ParseNumberExpr();
482   case '(':            return ParseParenExpr();
483   case tok_if:         return ParseIfExpr();
484   case tok_for:        return ParseForExpr();
485   case tok_var:        return ParseVarExpr();
486   }
487 }
488
489 /// unary
490 ///   ::= primary
491 ///   ::= '!' unary
492 static std::unique_ptr<ExprAST> ParseUnary() {
493   // If the current token is not an operator, it must be a primary expr.
494   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
495     return ParsePrimary();
496   
497   // If this is a unary operator, read it.
498   int Opc = CurTok;
499   getNextToken();
500   if (auto Operand = ParseUnary())
501     return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
502   return nullptr;
503 }
504
505 /// binoprhs
506 ///   ::= ('+' unary)*
507 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
508                                               std::unique_ptr<ExprAST> LHS) {
509   // If this is a binop, find its precedence.
510   while (1) {
511     int TokPrec = GetTokPrecedence();
512     
513     // If this is a binop that binds at least as tightly as the current binop,
514     // consume it, otherwise we are done.
515     if (TokPrec < ExprPrec)
516       return LHS;
517     
518     // Okay, we know this is a binop.
519     int BinOp = CurTok;
520     getNextToken();  // eat binop
521     
522     // Parse the unary expression after the binary operator.
523     auto RHS = ParseUnary();
524     if (!RHS)
525       return nullptr;
526     
527     // If BinOp binds less tightly with RHS than the operator after RHS, let
528     // the pending operator take RHS as its LHS.
529     int NextPrec = GetTokPrecedence();
530     if (TokPrec < NextPrec) {
531       RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
532       if (!RHS)
533         return nullptr;
534     }
535     
536     // Merge LHS/RHS.
537     LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
538   }
539 }
540
541 /// expression
542 ///   ::= unary binoprhs
543 ///
544 static std::unique_ptr<ExprAST> ParseExpression() {
545   auto LHS = ParseUnary();
546   if (!LHS)
547     return nullptr;
548   
549   return ParseBinOpRHS(0, std::move(LHS));
550 }
551
552 /// prototype
553 ///   ::= id '(' id* ')'
554 ///   ::= binary LETTER number? (id, id)
555 ///   ::= unary LETTER (id)
556 static std::unique_ptr<PrototypeAST> ParsePrototype() {
557   std::string FnName;
558   
559   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
560   unsigned BinaryPrecedence = 30;
561   
562   switch (CurTok) {
563   default:
564     return ErrorU<PrototypeAST>("Expected function name in prototype");
565   case tok_identifier:
566     FnName = IdentifierStr;
567     Kind = 0;
568     getNextToken();
569     break;
570   case tok_unary:
571     getNextToken();
572     if (!isascii(CurTok))
573       return ErrorU<PrototypeAST>("Expected unary operator");
574     FnName = "unary";
575     FnName += (char)CurTok;
576     Kind = 1;
577     getNextToken();
578     break;
579   case tok_binary:
580     getNextToken();
581     if (!isascii(CurTok))
582       return ErrorU<PrototypeAST>("Expected binary operator");
583     FnName = "binary";
584     FnName += (char)CurTok;
585     Kind = 2;
586     getNextToken();
587     
588     // Read the precedence if present.
589     if (CurTok == tok_number) {
590       if (NumVal < 1 || NumVal > 100)
591         return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
592       BinaryPrecedence = (unsigned)NumVal;
593       getNextToken();
594     }
595     break;
596   }
597   
598   if (CurTok != '(')
599     return ErrorU<PrototypeAST>("Expected '(' in prototype");
600   
601   std::vector<std::string> ArgNames;
602   while (getNextToken() == tok_identifier)
603     ArgNames.push_back(IdentifierStr);
604   if (CurTok != ')')
605     return ErrorU<PrototypeAST>("Expected ')' in prototype");
606   
607   // success.
608   getNextToken();  // eat ')'.
609   
610   // Verify right number of names for operator.
611   if (Kind && ArgNames.size() != Kind)
612     return ErrorU<PrototypeAST>("Invalid number of operands for operator");
613   
614   return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
615                                          BinaryPrecedence);
616 }
617
618 /// definition ::= 'def' prototype expression
619 static std::unique_ptr<FunctionAST> ParseDefinition() {
620   getNextToken();  // eat def.
621   auto Proto = ParsePrototype();
622   if (!Proto)
623     return nullptr;
624
625   if (auto Body = ParseExpression())
626     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
627   return nullptr;
628 }
629
630 /// toplevelexpr ::= expression
631 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
632   if (auto E = ParseExpression()) {
633     // Make an anonymous proto.
634     auto Proto =
635       llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
636     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
637   }
638   return nullptr;
639 }
640
641 /// external ::= 'extern' prototype
642 static std::unique_ptr<PrototypeAST> ParseExtern() {
643   getNextToken();  // eat extern.
644   return ParsePrototype();
645 }
646
647 //===----------------------------------------------------------------------===//
648 // Code Generation
649 //===----------------------------------------------------------------------===//
650
651 // FIXME: Obviously we can do better than this
652 std::string GenerateUniqueName(const std::string &Root) {
653   static int i = 0;
654   std::ostringstream NameStream;
655   NameStream << Root << ++i;
656   return NameStream.str();
657 }
658
659 std::string MakeLegalFunctionName(std::string Name)
660 {
661   std::string NewName;
662   assert(!Name.empty() && "Base name must not be empty");
663
664   // Start with what we have
665   NewName = Name;
666
667   // Look for a numberic first character
668   if (NewName.find_first_of("0123456789") == 0) {
669     NewName.insert(0, 1, 'n');
670   }
671
672   // Replace illegal characters with their ASCII equivalent
673   std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
674   size_t pos;
675   while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
676     std::ostringstream NumStream;
677     NumStream << (int)NewName.at(pos);
678     NewName = NewName.replace(pos, 1, NumStream.str());
679   }
680
681   return NewName;
682 }
683
684 class SessionContext {
685 public:
686   SessionContext(LLVMContext &C)
687     : Context(C), TM(EngineBuilder().selectTarget()) {}
688   LLVMContext& getLLVMContext() const { return Context; }
689   TargetMachine& getTarget() { return *TM; }
690   void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
691   PrototypeAST* getPrototypeAST(const std::string &Name);
692 private:
693   typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
694   
695   LLVMContext &Context;
696   std::unique_ptr<TargetMachine> TM;
697       
698   PrototypeMap Prototypes;
699 };
700
701 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
702   Prototypes[P->Name] = std::move(P);
703 }
704
705 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
706   PrototypeMap::iterator I = Prototypes.find(Name);
707   if (I != Prototypes.end())
708     return I->second.get();
709   return nullptr;
710 }
711
712 class IRGenContext {
713 public:
714
715   IRGenContext(SessionContext &S)
716     : Session(S),
717       M(new Module(GenerateUniqueName("jit_module_"),
718                    Session.getLLVMContext())),
719       Builder(Session.getLLVMContext()) {
720     M->setDataLayout(Session.getTarget().createDataLayout());
721   }
722
723   SessionContext& getSession() { return Session; }
724   Module& getM() const { return *M; }
725   std::unique_ptr<Module> takeM() { return std::move(M); }
726   IRBuilder<>& getBuilder() { return Builder; }
727   LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
728   Function* getPrototype(const std::string &Name);
729
730   std::map<std::string, AllocaInst*> NamedValues;
731 private:
732   SessionContext &Session;
733   std::unique_ptr<Module> M;
734   IRBuilder<> Builder;
735 };
736
737 Function* IRGenContext::getPrototype(const std::string &Name) {
738   if (Function *ExistingProto = M->getFunction(Name))
739     return ExistingProto;
740   if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
741     return ProtoAST->IRGen(*this);
742   return nullptr;
743 }
744
745 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
746 /// the function.  This is used for mutable variables etc.
747 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
748                                           const std::string &VarName) {
749   IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
750                  TheFunction->getEntryBlock().begin());
751   return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
752                            VarName.c_str());
753 }
754
755 Value *NumberExprAST::IRGen(IRGenContext &C) const {
756   return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
757 }
758
759 Value *VariableExprAST::IRGen(IRGenContext &C) const {
760   // Look this variable up in the function.
761   Value *V = C.NamedValues[Name];
762
763   if (V == 0)
764     return ErrorP<Value>("Unknown variable name '" + Name + "'");
765
766   // Load the value.
767   return C.getBuilder().CreateLoad(V, Name.c_str());
768 }
769
770 Value *UnaryExprAST::IRGen(IRGenContext &C) const {
771   if (Value *OperandV = Operand->IRGen(C)) {
772     std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
773     if (Function *F = C.getPrototype(FnName))
774       return C.getBuilder().CreateCall(F, OperandV, "unop");
775     return ErrorP<Value>("Unknown unary operator");
776   }
777
778   // Could not codegen operand - return null.
779   return nullptr;
780 }
781
782 Value *BinaryExprAST::IRGen(IRGenContext &C) const {
783   // Special case '=' because we don't want to emit the LHS as an expression.
784   if (Op == '=') {
785     // Assignment requires the LHS to be an identifier.
786     auto LHSVar = static_cast<VariableExprAST&>(*LHS);
787     // Codegen the RHS.
788     Value *Val = RHS->IRGen(C);
789     if (!Val) return nullptr;
790
791     // Look up the name.
792     if (auto Variable = C.NamedValues[LHSVar.Name]) {
793       C.getBuilder().CreateStore(Val, Variable);
794       return Val;
795     }
796     return ErrorP<Value>("Unknown variable name");
797   }
798   
799   Value *L = LHS->IRGen(C);
800   Value *R = RHS->IRGen(C);
801   if (!L || !R) return nullptr;
802   
803   switch (Op) {
804   case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
805   case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
806   case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
807   case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
808   case '<':
809     L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
810     // Convert bool 0/1 to double 0.0 or 1.0
811     return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
812                                 "booltmp");
813   default: break;
814   }
815   
816   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
817   // a call to it.
818   std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
819   if (Function *F = C.getPrototype(FnName)) {
820     Value *Ops[] = { L, R };
821     return C.getBuilder().CreateCall(F, Ops, "binop");
822   }
823    
824   return ErrorP<Value>("Unknown binary operator");
825 }
826
827 Value *CallExprAST::IRGen(IRGenContext &C) const {
828   // Look up the name in the global module table.
829   if (auto CalleeF = C.getPrototype(CalleeName)) {
830     // If argument mismatch error.
831     if (CalleeF->arg_size() != Args.size())
832       return ErrorP<Value>("Incorrect # arguments passed");
833
834     std::vector<Value*> ArgsV;
835     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
836       ArgsV.push_back(Args[i]->IRGen(C));
837       if (!ArgsV.back()) return nullptr;
838     }
839     
840     return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
841   }
842
843   return ErrorP<Value>("Unknown function referenced");
844 }
845
846 Value *IfExprAST::IRGen(IRGenContext &C) const {
847   Value *CondV = Cond->IRGen(C);
848   if (!CondV) return nullptr;
849   
850   // Convert condition to a bool by comparing equal to 0.0.
851   ConstantFP *FPZero = 
852     ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
853   CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
854   
855   Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
856   
857   // Create blocks for the then and else cases.  Insert the 'then' block at the
858   // end of the function.
859   BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
860   BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
861   BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
862   
863   C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
864   
865   // Emit then value.
866   C.getBuilder().SetInsertPoint(ThenBB);
867   
868   Value *ThenV = Then->IRGen(C);
869   if (!ThenV) return nullptr;
870   
871   C.getBuilder().CreateBr(MergeBB);
872   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
873   ThenBB = C.getBuilder().GetInsertBlock();
874   
875   // Emit else block.
876   TheFunction->getBasicBlockList().push_back(ElseBB);
877   C.getBuilder().SetInsertPoint(ElseBB);
878   
879   Value *ElseV = Else->IRGen(C);
880   if (!ElseV) return nullptr;
881   
882   C.getBuilder().CreateBr(MergeBB);
883   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
884   ElseBB = C.getBuilder().GetInsertBlock();
885   
886   // Emit merge block.
887   TheFunction->getBasicBlockList().push_back(MergeBB);
888   C.getBuilder().SetInsertPoint(MergeBB);
889   PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
890                                   "iftmp");
891   
892   PN->addIncoming(ThenV, ThenBB);
893   PN->addIncoming(ElseV, ElseBB);
894   return PN;
895 }
896
897 Value *ForExprAST::IRGen(IRGenContext &C) const {
898   // Output this as:
899   //   var = alloca double
900   //   ...
901   //   start = startexpr
902   //   store start -> var
903   //   goto loop
904   // loop: 
905   //   ...
906   //   bodyexpr
907   //   ...
908   // loopend:
909   //   step = stepexpr
910   //   endcond = endexpr
911   //
912   //   curvar = load var
913   //   nextvar = curvar + step
914   //   store nextvar -> var
915   //   br endcond, loop, endloop
916   // outloop:
917   
918   Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
919
920   // Create an alloca for the variable in the entry block.
921   AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
922   
923   // Emit the start code first, without 'variable' in scope.
924   Value *StartVal = Start->IRGen(C);
925   if (!StartVal) return nullptr;
926   
927   // Store the value into the alloca.
928   C.getBuilder().CreateStore(StartVal, Alloca);
929   
930   // Make the new basic block for the loop header, inserting after current
931   // block.
932   BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
933   
934   // Insert an explicit fall through from the current block to the LoopBB.
935   C.getBuilder().CreateBr(LoopBB);
936
937   // Start insertion in LoopBB.
938   C.getBuilder().SetInsertPoint(LoopBB);
939   
940   // Within the loop, the variable is defined equal to the PHI node.  If it
941   // shadows an existing variable, we have to restore it, so save it now.
942   AllocaInst *OldVal = C.NamedValues[VarName];
943   C.NamedValues[VarName] = Alloca;
944   
945   // Emit the body of the loop.  This, like any other expr, can change the
946   // current BB.  Note that we ignore the value computed by the body, but don't
947   // allow an error.
948   if (!Body->IRGen(C))
949     return nullptr;
950   
951   // Emit the step value.
952   Value *StepVal;
953   if (Step) {
954     StepVal = Step->IRGen(C);
955     if (!StepVal) return nullptr;
956   } else {
957     // If not specified, use 1.0.
958     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
959   }
960   
961   // Compute the end condition.
962   Value *EndCond = End->IRGen(C);
963   if (EndCond == 0) return EndCond;
964   
965   // Reload, increment, and restore the alloca.  This handles the case where
966   // the body of the loop mutates the variable.
967   Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
968   Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
969   C.getBuilder().CreateStore(NextVar, Alloca);
970   
971   // Convert condition to a bool by comparing equal to 0.0.
972   EndCond = C.getBuilder().CreateFCmpONE(EndCond, 
973                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
974                                   "loopcond");
975   
976   // Create the "after loop" block and insert it.
977   BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
978   
979   // Insert the conditional branch into the end of LoopEndBB.
980   C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
981   
982   // Any new code will be inserted in AfterBB.
983   C.getBuilder().SetInsertPoint(AfterBB);
984   
985   // Restore the unshadowed variable.
986   if (OldVal)
987     C.NamedValues[VarName] = OldVal;
988   else
989     C.NamedValues.erase(VarName);
990
991   
992   // for expr always returns 0.0.
993   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
994 }
995
996 Value *VarExprAST::IRGen(IRGenContext &C) const {
997   std::vector<AllocaInst *> OldBindings;
998   
999   Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
1000
1001   // Register all variables and emit their initializer.
1002   for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
1003     auto &VarName = VarBindings[i].first;
1004     auto &Init = VarBindings[i].second;
1005     
1006     // Emit the initializer before adding the variable to scope, this prevents
1007     // the initializer from referencing the variable itself, and permits stuff
1008     // like this:
1009     //  var a = 1 in
1010     //    var a = a in ...   # refers to outer 'a'.
1011     Value *InitVal;
1012     if (Init) {
1013       InitVal = Init->IRGen(C);
1014       if (!InitVal) return nullptr;
1015     } else // If not specified, use 0.0.
1016       InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1017     
1018     AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1019     C.getBuilder().CreateStore(InitVal, Alloca);
1020
1021     // Remember the old variable binding so that we can restore the binding when
1022     // we unrecurse.
1023     OldBindings.push_back(C.NamedValues[VarName]);
1024     
1025     // Remember this binding.
1026     C.NamedValues[VarName] = Alloca;
1027   }
1028   
1029   // Codegen the body, now that all vars are in scope.
1030   Value *BodyVal = Body->IRGen(C);
1031   if (!BodyVal) return nullptr;
1032   
1033   // Pop all our variables from scope.
1034   for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1035     C.NamedValues[VarBindings[i].first] = OldBindings[i];
1036
1037   // Return the body computation.
1038   return BodyVal;
1039 }
1040
1041 Function *PrototypeAST::IRGen(IRGenContext &C) const {
1042   std::string FnName = MakeLegalFunctionName(Name);
1043
1044   // Make the function type:  double(double,double) etc.
1045   std::vector<Type*> Doubles(Args.size(), 
1046                              Type::getDoubleTy(getGlobalContext()));
1047   FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1048                                        Doubles, false);
1049   Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1050                                  &C.getM());
1051
1052   // If F conflicted, there was already something named 'FnName'.  If it has a
1053   // body, don't allow redefinition or reextern.
1054   if (F->getName() != FnName) {
1055     // Delete the one we just made and get the existing one.
1056     F->eraseFromParent();
1057     F = C.getM().getFunction(Name);
1058     
1059     // If F already has a body, reject this.
1060     if (!F->empty()) {
1061       ErrorP<Function>("redefinition of function");
1062       return nullptr;
1063     }
1064     
1065     // If F took a different number of args, reject.
1066     if (F->arg_size() != Args.size()) {
1067       ErrorP<Function>("redefinition of function with different # args");
1068       return nullptr;
1069     }
1070   }
1071   
1072   // Set names for all arguments.
1073   unsigned Idx = 0;
1074   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1075        ++AI, ++Idx)
1076     AI->setName(Args[Idx]);
1077     
1078   return F;
1079 }
1080
1081 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1082 /// argument in the symbol table so that references to it will succeed.
1083 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1084   Function::arg_iterator AI = F->arg_begin();
1085   for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1086     // Create an alloca for this variable.
1087     AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1088
1089     // Store the initial value into the alloca.
1090     C.getBuilder().CreateStore(AI, Alloca);
1091
1092     // Add arguments to variable symbol table.
1093     C.NamedValues[Args[Idx]] = Alloca;
1094   }
1095 }
1096
1097 Function *FunctionAST::IRGen(IRGenContext &C) const {
1098   C.NamedValues.clear();
1099   
1100   Function *TheFunction = Proto->IRGen(C);
1101   if (!TheFunction)
1102     return nullptr;
1103   
1104   // If this is an operator, install it.
1105   if (Proto->isBinaryOp())
1106     BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1107   
1108   // Create a new basic block to start insertion into.
1109   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1110   C.getBuilder().SetInsertPoint(BB);
1111   
1112   // Add all arguments to the symbol table and create their allocas.
1113   Proto->CreateArgumentAllocas(TheFunction, C);
1114
1115   if (Value *RetVal = Body->IRGen(C)) {
1116     // Finish off the function.
1117     C.getBuilder().CreateRet(RetVal);
1118
1119     // Validate the generated code, checking for consistency.
1120     verifyFunction(*TheFunction);
1121
1122     return TheFunction;
1123   }
1124   
1125   // Error reading body, remove function.
1126   TheFunction->eraseFromParent();
1127
1128   if (Proto->isBinaryOp())
1129     BinopPrecedence.erase(Proto->getOperatorName());
1130   return nullptr;
1131 }
1132
1133 //===----------------------------------------------------------------------===//
1134 // Top-Level parsing and JIT Driver
1135 //===----------------------------------------------------------------------===//
1136
1137 static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1138                                            const FunctionAST &F) {
1139   IRGenContext C(S);
1140   auto LF = F.IRGen(C);
1141   if (!LF)
1142     return nullptr;
1143 #ifndef MINIMAL_STDERR_OUTPUT
1144   fprintf(stderr, "Read function definition:");
1145   LF->dump();
1146 #endif
1147   return C.takeM();
1148 }
1149
1150 template <typename T>
1151 static std::vector<T> singletonSet(T t) {
1152   std::vector<T> Vec;
1153   Vec.push_back(std::move(t));
1154   return Vec;
1155 }
1156
1157 static void EarthShatteringKaboom() {
1158   fprintf(stderr, "Earth shattering kaboom.");
1159   exit(1);
1160 }
1161
1162 class KaleidoscopeJIT {
1163 public:
1164   typedef ObjectLinkingLayer<> ObjLayerT;
1165   typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1166   typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1167   typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1168
1169   KaleidoscopeJIT(SessionContext &Session)
1170     : Session(Session),
1171       CompileLayer(ObjectLayer, SimpleCompiler(Session.getTarget())),
1172       LazyEmitLayer(CompileLayer),
1173       CompileCallbacks(LazyEmitLayer, CCMgrMemMgr, Session.getLLVMContext(),
1174                        reinterpret_cast<uintptr_t>(EarthShatteringKaboom),
1175                        64) {}
1176
1177   std::string mangle(const std::string &Name) {
1178     std::string MangledName;
1179     {
1180       raw_string_ostream MangledNameStream(MangledName);
1181       Mangler::getNameWithPrefix(MangledNameStream, Name,
1182                                  Session.getTarget().createDataLayout());
1183     }
1184     return MangledName;
1185   }
1186
1187   void addFunctionAST(std::unique_ptr<FunctionAST> FnAST) {
1188     std::cerr << "Adding AST: " << FnAST->Proto->Name << "\n";
1189     FunctionDefs[mangle(FnAST->Proto->Name)] = std::move(FnAST);
1190   }
1191
1192   ModuleHandleT addModule(std::unique_ptr<Module> M) {
1193     // We need a memory manager to allocate memory and resolve symbols for this
1194     // new module. Create one that resolves symbols by looking back into the
1195     // JIT.
1196     auto Resolver = createLambdaResolver(
1197                       [&](const std::string &Name) {
1198                         // First try to find 'Name' within the JIT.
1199                         if (auto Symbol = findSymbol(Name))
1200                           return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
1201                                                          Symbol.getFlags());
1202
1203                         // If we don't already have a definition of 'Name' then search
1204                         // the ASTs.
1205                         return searchFunctionASTs(Name);
1206                       },
1207                       [](const std::string &S) { return nullptr; } );
1208
1209     return LazyEmitLayer.addModuleSet(singletonSet(std::move(M)),
1210                                       make_unique<SectionMemoryManager>(),
1211                                       std::move(Resolver));
1212   }
1213
1214   void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1215
1216   JITSymbol findSymbol(const std::string &Name) {
1217     return LazyEmitLayer.findSymbol(Name, false);
1218   }
1219
1220   JITSymbol findSymbolIn(ModuleHandleT H, const std::string &Name) {
1221     return LazyEmitLayer.findSymbolIn(H, Name, false);
1222   }
1223
1224   JITSymbol findUnmangledSymbol(const std::string &Name) {
1225     return findSymbol(mangle(Name));
1226   }
1227
1228   JITSymbol findUnmangledSymbolIn(ModuleHandleT H, const std::string &Name) {
1229     return findSymbolIn(H, mangle(Name));
1230   }
1231
1232 private:
1233
1234   // This method searches the FunctionDefs map for a definition of 'Name'. If it
1235   // finds one it generates a stub for it and returns the address of the stub.
1236   RuntimeDyld::SymbolInfo searchFunctionASTs(const std::string &Name) {
1237     auto DefI = FunctionDefs.find(Name);
1238     if (DefI == FunctionDefs.end())
1239       return 0;
1240
1241     // Return the address of the stub.
1242     // Take the FunctionAST out of the map.
1243     auto FnAST = std::move(DefI->second);
1244     FunctionDefs.erase(DefI);
1245
1246     // IRGen the AST, add it to the JIT, and return the address for it.
1247     auto H = irGenStub(std::move(FnAST));
1248     auto Sym = findSymbolIn(H, Name);
1249     return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
1250   }
1251
1252   // This method will take the AST for a function definition and IR-gen a stub
1253   // for that function that will, on first call, IR-gen the actual body of the
1254   // function.
1255   ModuleHandleT irGenStub(std::unique_ptr<FunctionAST> FnAST) {
1256     // Step 1) IRGen a prototype for the stub. This will have the same type as
1257     //         the function.
1258     IRGenContext C(Session);
1259     Function *F = FnAST->Proto->IRGen(C);
1260
1261     // Step 2) Get a compile callback that can be used to compile the body of
1262     //         the function. The resulting CallbackInfo type will let us set the
1263     //         compile and update actions for the callback, and get a pointer to
1264     //         the jit trampoline that we need to call to trigger those actions.
1265     auto CallbackInfo =
1266       CompileCallbacks.getCompileCallback(F->getContext());
1267
1268     // Step 3) Create a stub that will indirectly call the body of this
1269     //         function once it is compiled. Initially, set the function
1270     //         pointer for the indirection to point at the trampoline.
1271     std::string BodyPtrName = (F->getName() + "$address").str();
1272     GlobalVariable *FunctionBodyPointer =
1273       createImplPointer(*F->getType(), *F->getParent(), BodyPtrName,
1274                         createIRTypedAddress(*F->getFunctionType(),
1275                                              CallbackInfo.getAddress()));
1276     makeStub(*F, *FunctionBodyPointer);
1277
1278     // Step 4) Add the module containing the stub to the JIT.
1279     auto StubH = addModule(C.takeM());
1280
1281     // Step 5) Set the compile and update actions.
1282     //
1283     //   The compile action will IRGen the function and add it to the JIT, then
1284     // request its address, which will trigger codegen. Since we don't need the
1285     // AST after this, we pass ownership of the AST into the compile action:
1286     // compile actions (and update actions) are deleted after they're run, so
1287     // this will free the AST for us.
1288     //
1289     //   The update action will update FunctionBodyPointer to point at the newly
1290     // compiled function.
1291     std::shared_ptr<FunctionAST> Fn = std::move(FnAST);
1292     CallbackInfo.setCompileAction([this, Fn, BodyPtrName, StubH]() {
1293       auto H = addModule(IRGen(Session, *Fn));
1294       auto BodySym = findUnmangledSymbolIn(H, Fn->Proto->Name);
1295       auto BodyPtrSym = findUnmangledSymbolIn(StubH, BodyPtrName);
1296       assert(BodySym && "Missing function body.");
1297       assert(BodyPtrSym && "Missing function pointer.");
1298       auto BodyAddr = BodySym.getAddress();
1299       auto BodyPtr = reinterpret_cast<void*>(
1300                        static_cast<uintptr_t>(BodyPtrSym.getAddress()));
1301       memcpy(BodyPtr, &BodyAddr, sizeof(uintptr_t));
1302       return BodyAddr;
1303     });
1304
1305     return StubH;
1306   }
1307
1308   SessionContext &Session;
1309   SectionMemoryManager CCMgrMemMgr;
1310   ObjLayerT ObjectLayer;
1311   CompileLayerT CompileLayer;
1312   LazyEmitLayerT LazyEmitLayer;
1313
1314   std::map<std::string, std::unique_ptr<FunctionAST>> FunctionDefs;
1315
1316   JITCompileCallbackManager<LazyEmitLayerT, OrcX86_64> CompileCallbacks;
1317 };
1318
1319 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1320   if (auto F = ParseDefinition()) {
1321     S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1322     J.addFunctionAST(std::move(F));
1323   } else {
1324     // Skip token for error recovery.
1325     getNextToken();
1326   }
1327 }
1328
1329 static void HandleExtern(SessionContext &S) {
1330   if (auto P = ParseExtern())
1331     S.addPrototypeAST(std::move(P));
1332   else {
1333     // Skip token for error recovery.
1334     getNextToken();
1335   }
1336 }
1337
1338 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1339   // Evaluate a top-level expression into an anonymous function.
1340   if (auto F = ParseTopLevelExpr()) {
1341     IRGenContext C(S);
1342     if (auto ExprFunc = F->IRGen(C)) {
1343 #ifndef MINIMAL_STDERR_OUTPUT
1344       std::cerr << "Expression function:\n";
1345       ExprFunc->dump();
1346 #endif
1347       // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1348       // this module as soon as we've executed Function ExprFunc.
1349       auto H = J.addModule(C.takeM());
1350
1351       // Get the address of the JIT'd function in memory.
1352       auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1353       
1354       // Cast it to the right type (takes no arguments, returns a double) so we
1355       // can call it as a native function.
1356       double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1357 #ifdef MINIMAL_STDERR_OUTPUT
1358       FP();
1359 #else
1360       std::cerr << "Evaluated to " << FP() << "\n";
1361 #endif
1362
1363       // Remove the function.
1364       J.removeModule(H);
1365     }
1366   } else {
1367     // Skip token for error recovery.
1368     getNextToken();
1369   }
1370 }
1371
1372 /// top ::= definition | external | expression | ';'
1373 static void MainLoop() {
1374   SessionContext S(getGlobalContext());
1375   KaleidoscopeJIT J(S);
1376
1377   while (1) {
1378     switch (CurTok) {
1379     case tok_eof:    return;
1380     case ';':        getNextToken(); continue;  // ignore top-level semicolons.
1381     case tok_def:    HandleDefinition(S, J); break;
1382     case tok_extern: HandleExtern(S); break;
1383     default:         HandleTopLevelExpression(S, J); break;
1384     }
1385 #ifndef MINIMAL_STDERR_OUTPUT
1386     std::cerr << "ready> ";
1387 #endif
1388   }
1389 }
1390
1391 //===----------------------------------------------------------------------===//
1392 // "Library" functions that can be "extern'd" from user code.
1393 //===----------------------------------------------------------------------===//
1394
1395 /// putchard - putchar that takes a double and returns 0.
1396 extern "C" 
1397 double putchard(double X) {
1398   putchar((char)X);
1399   return 0;
1400 }
1401
1402 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1403 extern "C" 
1404 double printd(double X) {
1405   printf("%f", X);
1406   return 0;
1407 }
1408
1409 extern "C" 
1410 double printlf() {
1411   printf("\n");
1412   return 0;
1413 }
1414
1415 //===----------------------------------------------------------------------===//
1416 // Main driver code.
1417 //===----------------------------------------------------------------------===//
1418
1419 int main() {
1420   InitializeNativeTarget();
1421   InitializeNativeTargetAsmPrinter();
1422   InitializeNativeTargetAsmParser();
1423
1424   // Install standard binary operators.
1425   // 1 is lowest precedence.
1426   BinopPrecedence['='] = 2;
1427   BinopPrecedence['<'] = 10;
1428   BinopPrecedence['+'] = 20;
1429   BinopPrecedence['-'] = 20;
1430   BinopPrecedence['/'] = 40;
1431   BinopPrecedence['*'] = 40;  // highest.
1432
1433   // Prime the first token.
1434 #ifndef MINIMAL_STDERR_OUTPUT
1435   std::cerr << "ready> ";
1436 #endif
1437   getNextToken();
1438
1439   std::cerr << std::fixed;
1440
1441   // Run the main "interpreter loop" now.
1442   MainLoop();
1443
1444   return 0;
1445 }
1446