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