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