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