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