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