[Kaleidoscope] More inter-chapter diff reduction.
[oota-llvm.git] / examples / Kaleidoscope / Chapter3 / toy.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/IR/Verifier.h"
3 #include "llvm/IR/DerivedTypes.h"
4 #include "llvm/IR/IRBuilder.h"
5 #include "llvm/IR/LLVMContext.h"
6 #include "llvm/IR/Module.h"
7 #include <cctype>
8 #include <cstdio>
9 #include <map>
10 #include <string>
11 #include <vector>
12 using namespace llvm;
13
14 //===----------------------------------------------------------------------===//
15 // Lexer
16 //===----------------------------------------------------------------------===//
17
18 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
19 // of these for known things.
20 enum Token {
21   tok_eof = -1,
22
23   // commands
24   tok_def = -2,
25   tok_extern = -3,
26
27   // primary
28   tok_identifier = -4,
29   tok_number = -5
30 };
31
32 static std::string IdentifierStr; // Filled in if tok_identifier
33 static double NumVal;             // Filled in if tok_number
34
35 /// gettok - Return the next token from standard input.
36 static int gettok() {
37   static int LastChar = ' ';
38
39   // Skip any whitespace.
40   while (isspace(LastChar))
41     LastChar = getchar();
42
43   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
44     IdentifierStr = LastChar;
45     while (isalnum((LastChar = getchar())))
46       IdentifierStr += LastChar;
47
48     if (IdentifierStr == "def")
49       return tok_def;
50     if (IdentifierStr == "extern")
51       return tok_extern;
52     return tok_identifier;
53   }
54
55   if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
56     std::string NumStr;
57     do {
58       NumStr += LastChar;
59       LastChar = getchar();
60     } while (isdigit(LastChar) || LastChar == '.');
61
62     NumVal = strtod(NumStr.c_str(), 0);
63     return tok_number;
64   }
65
66   if (LastChar == '#') {
67     // Comment until end of line.
68     do
69       LastChar = getchar();
70     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
71
72     if (LastChar != EOF)
73       return gettok();
74   }
75
76   // Check for end of file.  Don't eat the EOF.
77   if (LastChar == EOF)
78     return tok_eof;
79
80   // Otherwise, just return the character as its ascii value.
81   int ThisChar = LastChar;
82   LastChar = getchar();
83   return ThisChar;
84 }
85
86 //===----------------------------------------------------------------------===//
87 // Abstract Syntax Tree (aka Parse Tree)
88 //===----------------------------------------------------------------------===//
89 namespace {
90 /// ExprAST - Base class for all expression nodes.
91 class ExprAST {
92 public:
93   virtual ~ExprAST() {}
94   virtual Value *Codegen() = 0;
95 };
96
97 /// NumberExprAST - Expression class for numeric literals like "1.0".
98 class NumberExprAST : public ExprAST {
99   double Val;
100
101 public:
102   NumberExprAST(double Val) : Val(Val) {}
103   Value *Codegen() override;
104 };
105
106 /// VariableExprAST - Expression class for referencing a variable, like "a".
107 class VariableExprAST : public ExprAST {
108   std::string Name;
109
110 public:
111   VariableExprAST(const std::string &Name) : Name(Name) {}
112   Value *Codegen() override;
113 };
114
115 /// BinaryExprAST - Expression class for a binary operator.
116 class BinaryExprAST : public ExprAST {
117   char Op;
118   std::unique_ptr<ExprAST> LHS, RHS;
119
120 public:
121   BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
122                 std::unique_ptr<ExprAST> RHS)
123       : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
124   Value *Codegen() override;
125 };
126
127 /// CallExprAST - Expression class for function calls.
128 class CallExprAST : public ExprAST {
129   std::string Callee;
130   std::vector<std::unique_ptr<ExprAST>> Args;
131
132 public:
133   CallExprAST(const std::string &Callee,
134               std::vector<std::unique_ptr<ExprAST>> Args)
135       : Callee(Callee), Args(std::move(Args)) {}
136   Value *Codegen() override;
137 };
138
139 /// PrototypeAST - This class represents the "prototype" for a function,
140 /// which captures its name, and its argument names (thus implicitly the number
141 /// of arguments the function takes).
142 class PrototypeAST {
143   std::string Name;
144   std::vector<std::string> Args;
145
146 public:
147   PrototypeAST(const std::string &Name, std::vector<std::string> Args)
148       : Name(Name), Args(std::move(Args)) {}
149   Function *Codegen();
150 };
151
152 /// FunctionAST - This class represents a function definition itself.
153 class FunctionAST {
154   std::unique_ptr<PrototypeAST> Proto;
155   std::unique_ptr<ExprAST> Body;
156
157 public:
158   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
159               std::unique_ptr<ExprAST> Body)
160       : Proto(std::move(Proto)), Body(std::move(Body)) {}
161   Function *Codegen();
162 };
163 } // end anonymous namespace
164
165 //===----------------------------------------------------------------------===//
166 // Parser
167 //===----------------------------------------------------------------------===//
168
169 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
170 /// token the parser is looking at.  getNextToken reads another token from the
171 /// lexer and updates CurTok with its results.
172 static int CurTok;
173 static int getNextToken() { return CurTok = gettok(); }
174
175 /// BinopPrecedence - This holds the precedence for each binary operator that is
176 /// defined.
177 static std::map<char, int> BinopPrecedence;
178
179 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
180 static int GetTokPrecedence() {
181   if (!isascii(CurTok))
182     return -1;
183
184   // Make sure it's a declared binop.
185   int TokPrec = BinopPrecedence[CurTok];
186   if (TokPrec <= 0)
187     return -1;
188   return TokPrec;
189 }
190
191 /// Error* - These are little helper functions for error handling.
192 std::unique_ptr<ExprAST> Error(const char *Str) {
193   fprintf(stderr, "Error: %s\n", Str);
194   return nullptr;
195 }
196 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
197   Error(Str);
198   return nullptr;
199 }
200 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
201   Error(Str);
202   return nullptr;
203 }
204
205 static std::unique_ptr<ExprAST> ParseExpression();
206
207 /// numberexpr ::= number
208 static std::unique_ptr<ExprAST> ParseNumberExpr() {
209   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
210   getNextToken(); // consume the number
211   return std::move(Result);
212 }
213
214 /// parenexpr ::= '(' expression ')'
215 static std::unique_ptr<ExprAST> ParseParenExpr() {
216   getNextToken(); // eat (.
217   auto V = ParseExpression();
218   if (!V)
219     return nullptr;
220
221   if (CurTok != ')')
222     return Error("expected ')'");
223   getNextToken(); // eat ).
224   return V;
225 }
226
227 /// identifierexpr
228 ///   ::= identifier
229 ///   ::= identifier '(' expression* ')'
230 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
231   std::string IdName = IdentifierStr;
232
233   getNextToken(); // eat identifier.
234
235   if (CurTok != '(') // Simple variable ref.
236     return llvm::make_unique<VariableExprAST>(IdName);
237
238   // Call.
239   getNextToken(); // eat (
240   std::vector<std::unique_ptr<ExprAST>> Args;
241   if (CurTok != ')') {
242     while (1) {
243       if (auto Arg = ParseExpression())
244         Args.push_back(std::move(Arg));
245       else
246         return nullptr;
247
248       if (CurTok == ')')
249         break;
250
251       if (CurTok != ',')
252         return Error("Expected ')' or ',' in argument list");
253       getNextToken();
254     }
255   }
256
257   // Eat the ')'.
258   getNextToken();
259
260   return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
261 }
262
263 /// primary
264 ///   ::= identifierexpr
265 ///   ::= numberexpr
266 ///   ::= parenexpr
267 static std::unique_ptr<ExprAST> ParsePrimary() {
268   switch (CurTok) {
269   default:
270     return Error("unknown token when expecting an expression");
271   case tok_identifier:
272     return ParseIdentifierExpr();
273   case tok_number:
274     return ParseNumberExpr();
275   case '(':
276     return ParseParenExpr();
277   }
278 }
279
280 /// binoprhs
281 ///   ::= ('+' primary)*
282 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
283                                               std::unique_ptr<ExprAST> LHS) {
284   // If this is a binop, find its precedence.
285   while (1) {
286     int TokPrec = GetTokPrecedence();
287
288     // If this is a binop that binds at least as tightly as the current binop,
289     // consume it, otherwise we are done.
290     if (TokPrec < ExprPrec)
291       return LHS;
292
293     // Okay, we know this is a binop.
294     int BinOp = CurTok;
295     getNextToken(); // eat binop
296
297     // Parse the primary expression after the binary operator.
298     auto RHS = ParsePrimary();
299     if (!RHS)
300       return nullptr;
301
302     // If BinOp binds less tightly with RHS than the operator after RHS, let
303     // the pending operator take RHS as its LHS.
304     int NextPrec = GetTokPrecedence();
305     if (TokPrec < NextPrec) {
306       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
307       if (!RHS)
308         return nullptr;
309     }
310
311     // Merge LHS/RHS.
312     LHS =
313         llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
314   }
315 }
316
317 /// expression
318 ///   ::= primary binoprhs
319 ///
320 static std::unique_ptr<ExprAST> ParseExpression() {
321   auto LHS = ParsePrimary();
322   if (!LHS)
323     return nullptr;
324
325   return ParseBinOpRHS(0, std::move(LHS));
326 }
327
328 /// prototype
329 ///   ::= id '(' id* ')'
330 static std::unique_ptr<PrototypeAST> ParsePrototype() {
331   if (CurTok != tok_identifier)
332     return ErrorP("Expected function name in prototype");
333
334   std::string FnName = IdentifierStr;
335   getNextToken();
336
337   if (CurTok != '(')
338     return ErrorP("Expected '(' in prototype");
339
340   std::vector<std::string> ArgNames;
341   while (getNextToken() == tok_identifier)
342     ArgNames.push_back(IdentifierStr);
343   if (CurTok != ')')
344     return ErrorP("Expected ')' in prototype");
345
346   // success.
347   getNextToken(); // eat ')'.
348
349   return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
350 }
351
352 /// definition ::= 'def' prototype expression
353 static std::unique_ptr<FunctionAST> ParseDefinition() {
354   getNextToken(); // eat def.
355   auto Proto = ParsePrototype();
356   if (!Proto)
357     return nullptr;
358
359   if (auto E = ParseExpression())
360     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
361   return nullptr;
362 }
363
364 /// toplevelexpr ::= expression
365 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
366   if (auto E = ParseExpression()) {
367     // Make an anonymous proto.
368     auto Proto =
369         llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
370     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
371   }
372   return nullptr;
373 }
374
375 /// external ::= 'extern' prototype
376 static std::unique_ptr<PrototypeAST> ParseExtern() {
377   getNextToken(); // eat extern.
378   return ParsePrototype();
379 }
380
381 //===----------------------------------------------------------------------===//
382 // Code Generation
383 //===----------------------------------------------------------------------===//
384
385 Value *ErrorV(const char *Str) {
386   Error(Str);
387   return nullptr;
388 }
389
390 static Module *TheModule;
391 static IRBuilder<> Builder(getGlobalContext());
392 static std::map<std::string, Value *> NamedValues;
393
394 Value *NumberExprAST::Codegen() {
395   return ConstantFP::get(getGlobalContext(), APFloat(Val));
396 }
397
398 Value *VariableExprAST::Codegen() {
399   // Look this variable up in the function.
400   Value *V = NamedValues[Name];
401   if (!V)
402     return ErrorV("Unknown variable name");
403   return V;
404 }
405
406 Value *BinaryExprAST::Codegen() {
407   Value *L = LHS->Codegen();
408   Value *R = RHS->Codegen();
409   if (!L || !R)
410     return nullptr;
411
412   switch (Op) {
413   case '+':
414     return Builder.CreateFAdd(L, R, "addtmp");
415   case '-':
416     return Builder.CreateFSub(L, R, "subtmp");
417   case '*':
418     return Builder.CreateFMul(L, R, "multmp");
419   case '<':
420     L = Builder.CreateFCmpULT(L, R, "cmptmp");
421     // Convert bool 0/1 to double 0.0 or 1.0
422     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
423                                 "booltmp");
424   default:
425     return ErrorV("invalid binary operator");
426   }
427 }
428
429 Value *CallExprAST::Codegen() {
430   // Look up the name in the global module table.
431   Function *CalleeF = TheModule->getFunction(Callee);
432   if (!CalleeF)
433     return ErrorV("Unknown function referenced");
434
435   // If argument mismatch error.
436   if (CalleeF->arg_size() != Args.size())
437     return ErrorV("Incorrect # arguments passed");
438
439   std::vector<Value *> ArgsV;
440   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
441     ArgsV.push_back(Args[i]->Codegen());
442     if (!ArgsV.back())
443       return nullptr;
444   }
445
446   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
447 }
448
449 Function *PrototypeAST::Codegen() {
450   // Make the function type:  double(double,double) etc.
451   std::vector<Type *> Doubles(Args.size(),
452                               Type::getDoubleTy(getGlobalContext()));
453   FunctionType *FT =
454       FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
455
456   Function *F =
457       Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
458
459   // If F conflicted, there was already something named 'Name'.  If it has a
460   // body, don't allow redefinition or reextern.
461   if (F->getName() != Name) {
462     // Delete the one we just made and get the existing one.
463     F->eraseFromParent();
464     F = TheModule->getFunction(Name);
465
466     // If F already has a body, reject this.
467     if (!F->empty()) {
468       ErrorF("redefinition of function");
469       return nullptr;
470     }
471
472     // If F took a different number of args, reject.
473     if (F->arg_size() != Args.size()) {
474       ErrorF("redefinition of function with different # args");
475       return nullptr;
476     }
477   }
478
479   // Set names for all arguments.
480   unsigned Idx = 0;
481   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
482        ++AI, ++Idx) {
483     AI->setName(Args[Idx]);
484
485     // Add arguments to variable symbol table.
486     NamedValues[Args[Idx]] = AI;
487   }
488
489   return F;
490 }
491
492 Function *FunctionAST::Codegen() {
493   NamedValues.clear();
494
495   Function *TheFunction = Proto->Codegen();
496   if (!TheFunction)
497     return nullptr;
498
499   // Create a new basic block to start insertion into.
500   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
501   Builder.SetInsertPoint(BB);
502
503   if (Value *RetVal = Body->Codegen()) {
504     // Finish off the function.
505     Builder.CreateRet(RetVal);
506
507     // Validate the generated code, checking for consistency.
508     verifyFunction(*TheFunction);
509
510     return TheFunction;
511   }
512
513   // Error reading body, remove function.
514   TheFunction->eraseFromParent();
515   return nullptr;
516 }
517
518 //===----------------------------------------------------------------------===//
519 // Top-Level parsing and JIT Driver
520 //===----------------------------------------------------------------------===//
521
522 static void HandleDefinition() {
523   if (auto FnAST = ParseDefinition()) {
524     if (auto *FnIR = FnAST->Codegen()) {
525       fprintf(stderr, "Read function definition:");
526       FnIR->dump();
527     }
528   } else {
529     // Skip token for error recovery.
530     getNextToken();
531   }
532 }
533
534 static void HandleExtern() {
535   if (auto ProtoAST = ParseExtern()) {
536     if (auto *FnIR = ProtoAST->Codegen()) {
537       fprintf(stderr, "Read extern: ");
538       FnIR->dump();
539     }
540   } else {
541     // Skip token for error recovery.
542     getNextToken();
543   }
544 }
545
546 static void HandleTopLevelExpression() {
547   // Evaluate a top-level expression into an anonymous function.
548   if (auto FnAST = ParseTopLevelExpr()) {
549     if (auto *FnIR = FnAST->Codegen()) {
550       fprintf(stderr, "Read top-level expression:");
551       FnIR->dump();
552     }
553   } else {
554     // Skip token for error recovery.
555     getNextToken();
556   }
557 }
558
559 /// top ::= definition | external | expression | ';'
560 static void MainLoop() {
561   while (1) {
562     fprintf(stderr, "ready> ");
563     switch (CurTok) {
564     case tok_eof:
565       return;
566     case ';': // ignore top-level semicolons.
567       getNextToken();
568       break;
569     case tok_def:
570       HandleDefinition();
571       break;
572     case tok_extern:
573       HandleExtern();
574       break;
575     default:
576       HandleTopLevelExpression();
577       break;
578     }
579   }
580 }
581
582 //===----------------------------------------------------------------------===//
583 // Main driver code.
584 //===----------------------------------------------------------------------===//
585
586 int main() {
587   LLVMContext &Context = getGlobalContext();
588
589   // Install standard binary operators.
590   // 1 is lowest precedence.
591   BinopPrecedence['<'] = 10;
592   BinopPrecedence['+'] = 20;
593   BinopPrecedence['-'] = 20;
594   BinopPrecedence['*'] = 40; // highest.
595
596   // Prime the first token.
597   fprintf(stderr, "ready> ");
598   getNextToken();
599
600   // Make the module, which holds all the code.
601   std::unique_ptr<Module> Owner =
602       llvm::make_unique<Module>("my cool jit", Context);
603   TheModule = Owner.get();
604
605   // Run the main "interpreter loop" now.
606   MainLoop();
607
608   // Print out all of the generated code.
609   TheModule->dump();
610
611   return 0;
612 }