Fix Clang-tidy modernize-use-nullptr warnings in examples and include directories...
[oota-llvm.git] / examples / Kaleidoscope / Chapter3 / toy.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/IR/IRBuilder.h"
3 #include "llvm/IR/LLVMContext.h"
4 #include "llvm/IR/Module.h"
5 #include "llvm/IR/Verifier.h"
6 #include <cctype>
7 #include <cstdio>
8 #include <map>
9 #include <string>
10 #include <vector>
11
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(), nullptr);
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   const std::string &getName() const { return Name; }
151 };
152
153 /// FunctionAST - This class represents a function definition itself.
154 class FunctionAST {
155   std::unique_ptr<PrototypeAST> Proto;
156   std::unique_ptr<ExprAST> Body;
157
158 public:
159   FunctionAST(std::unique_ptr<PrototypeAST> Proto,
160               std::unique_ptr<ExprAST> Body)
161       : Proto(std::move(Proto)), Body(std::move(Body)) {}
162   Function *codegen();
163 };
164 } // end anonymous namespace
165
166 //===----------------------------------------------------------------------===//
167 // Parser
168 //===----------------------------------------------------------------------===//
169
170 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
171 /// token the parser is looking at.  getNextToken reads another token from the
172 /// lexer and updates CurTok with its results.
173 static int CurTok;
174 static int getNextToken() { return CurTok = gettok(); }
175
176 /// BinopPrecedence - This holds the precedence for each binary operator that is
177 /// defined.
178 static std::map<char, int> BinopPrecedence;
179
180 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
181 static int GetTokPrecedence() {
182   if (!isascii(CurTok))
183     return -1;
184
185   // Make sure it's a declared binop.
186   int TokPrec = BinopPrecedence[CurTok];
187   if (TokPrec <= 0)
188     return -1;
189   return TokPrec;
190 }
191
192 /// Error* - These are little helper functions for error handling.
193 std::unique_ptr<ExprAST> Error(const char *Str) {
194   fprintf(stderr, "Error: %s\n", Str);
195   return nullptr;
196 }
197
198 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
199   Error(Str);
200   return nullptr;
201 }
202
203 static std::unique_ptr<ExprAST> ParseExpression();
204
205 /// numberexpr ::= number
206 static std::unique_ptr<ExprAST> ParseNumberExpr() {
207   auto Result = llvm::make_unique<NumberExprAST>(NumVal);
208   getNextToken(); // consume the number
209   return std::move(Result);
210 }
211
212 /// parenexpr ::= '(' expression ')'
213 static std::unique_ptr<ExprAST> ParseParenExpr() {
214   getNextToken(); // eat (.
215   auto V = ParseExpression();
216   if (!V)
217     return nullptr;
218
219   if (CurTok != ')')
220     return Error("expected ')'");
221   getNextToken(); // eat ).
222   return V;
223 }
224
225 /// identifierexpr
226 ///   ::= identifier
227 ///   ::= identifier '(' expression* ')'
228 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
229   std::string IdName = IdentifierStr;
230
231   getNextToken(); // eat identifier.
232
233   if (CurTok != '(') // Simple variable ref.
234     return llvm::make_unique<VariableExprAST>(IdName);
235
236   // Call.
237   getNextToken(); // eat (
238   std::vector<std::unique_ptr<ExprAST>> Args;
239   if (CurTok != ')') {
240     while (1) {
241       if (auto Arg = ParseExpression())
242         Args.push_back(std::move(Arg));
243       else
244         return nullptr;
245
246       if (CurTok == ')')
247         break;
248
249       if (CurTok != ',')
250         return Error("Expected ')' or ',' in argument list");
251       getNextToken();
252     }
253   }
254
255   // Eat the ')'.
256   getNextToken();
257
258   return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
259 }
260
261 /// primary
262 ///   ::= identifierexpr
263 ///   ::= numberexpr
264 ///   ::= parenexpr
265 static std::unique_ptr<ExprAST> ParsePrimary() {
266   switch (CurTok) {
267   default:
268     return Error("unknown token when expecting an expression");
269   case tok_identifier:
270     return ParseIdentifierExpr();
271   case tok_number:
272     return ParseNumberExpr();
273   case '(':
274     return ParseParenExpr();
275   }
276 }
277
278 /// binoprhs
279 ///   ::= ('+' primary)*
280 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
281                                               std::unique_ptr<ExprAST> LHS) {
282   // If this is a binop, find its precedence.
283   while (1) {
284     int TokPrec = GetTokPrecedence();
285
286     // If this is a binop that binds at least as tightly as the current binop,
287     // consume it, otherwise we are done.
288     if (TokPrec < ExprPrec)
289       return LHS;
290
291     // Okay, we know this is a binop.
292     int BinOp = CurTok;
293     getNextToken(); // eat binop
294
295     // Parse the primary expression after the binary operator.
296     auto RHS = ParsePrimary();
297     if (!RHS)
298       return nullptr;
299
300     // If BinOp binds less tightly with RHS than the operator after RHS, let
301     // the pending operator take RHS as its LHS.
302     int NextPrec = GetTokPrecedence();
303     if (TokPrec < NextPrec) {
304       RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
305       if (!RHS)
306         return nullptr;
307     }
308
309     // Merge LHS/RHS.
310     LHS =
311         llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
312   }
313 }
314
315 /// expression
316 ///   ::= primary binoprhs
317 ///
318 static std::unique_ptr<ExprAST> ParseExpression() {
319   auto LHS = ParsePrimary();
320   if (!LHS)
321     return nullptr;
322
323   return ParseBinOpRHS(0, std::move(LHS));
324 }
325
326 /// prototype
327 ///   ::= id '(' id* ')'
328 static std::unique_ptr<PrototypeAST> ParsePrototype() {
329   if (CurTok != tok_identifier)
330     return ErrorP("Expected function name in prototype");
331
332   std::string FnName = IdentifierStr;
333   getNextToken();
334
335   if (CurTok != '(')
336     return ErrorP("Expected '(' in prototype");
337
338   std::vector<std::string> ArgNames;
339   while (getNextToken() == tok_identifier)
340     ArgNames.push_back(IdentifierStr);
341   if (CurTok != ')')
342     return ErrorP("Expected ')' in prototype");
343
344   // success.
345   getNextToken(); // eat ')'.
346
347   return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
348 }
349
350 /// definition ::= 'def' prototype expression
351 static std::unique_ptr<FunctionAST> ParseDefinition() {
352   getNextToken(); // eat def.
353   auto Proto = ParsePrototype();
354   if (!Proto)
355     return nullptr;
356
357   if (auto E = ParseExpression())
358     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
359   return nullptr;
360 }
361
362 /// toplevelexpr ::= expression
363 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
364   if (auto E = ParseExpression()) {
365     // Make an anonymous proto.
366     auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
367                                                  std::vector<std::string>());
368     return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
369   }
370   return nullptr;
371 }
372
373 /// external ::= 'extern' prototype
374 static std::unique_ptr<PrototypeAST> ParseExtern() {
375   getNextToken(); // eat extern.
376   return ParsePrototype();
377 }
378
379 //===----------------------------------------------------------------------===//
380 // Code Generation
381 //===----------------------------------------------------------------------===//
382
383 static std::unique_ptr<Module> TheModule;
384 static IRBuilder<> Builder(getGlobalContext());
385 static std::map<std::string, Value *> NamedValues;
386
387 Value *ErrorV(const char *Str) {
388   Error(Str);
389   return nullptr;
390 }
391
392 Value *NumberExprAST::codegen() {
393   return ConstantFP::get(getGlobalContext(), APFloat(Val));
394 }
395
396 Value *VariableExprAST::codegen() {
397   // Look this variable up in the function.
398   Value *V = NamedValues[Name];
399   if (!V)
400     return ErrorV("Unknown variable name");
401   return V;
402 }
403
404 Value *BinaryExprAST::codegen() {
405   Value *L = LHS->codegen();
406   Value *R = RHS->codegen();
407   if (!L || !R)
408     return nullptr;
409
410   switch (Op) {
411   case '+':
412     return Builder.CreateFAdd(L, R, "addtmp");
413   case '-':
414     return Builder.CreateFSub(L, R, "subtmp");
415   case '*':
416     return Builder.CreateFMul(L, R, "multmp");
417   case '<':
418     L = Builder.CreateFCmpULT(L, R, "cmptmp");
419     // Convert bool 0/1 to double 0.0 or 1.0
420     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
421                                 "booltmp");
422   default:
423     return ErrorV("invalid binary operator");
424   }
425 }
426
427 Value *CallExprAST::codegen() {
428   // Look up the name in the global module table.
429   Function *CalleeF = TheModule->getFunction(Callee);
430   if (!CalleeF)
431     return ErrorV("Unknown function referenced");
432
433   // If argument mismatch error.
434   if (CalleeF->arg_size() != Args.size())
435     return ErrorV("Incorrect # arguments passed");
436
437   std::vector<Value *> ArgsV;
438   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
439     ArgsV.push_back(Args[i]->codegen());
440     if (!ArgsV.back())
441       return nullptr;
442   }
443
444   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
445 }
446
447 Function *PrototypeAST::codegen() {
448   // Make the function type:  double(double,double) etc.
449   std::vector<Type *> Doubles(Args.size(),
450                               Type::getDoubleTy(getGlobalContext()));
451   FunctionType *FT =
452       FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
453
454   Function *F =
455       Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
456
457   // Set names for all arguments.
458   unsigned Idx = 0;
459   for (auto &Arg : F->args())
460     Arg.setName(Args[Idx++]);
461
462   return F;
463 }
464
465 Function *FunctionAST::codegen() {
466   // First, check for an existing function from a previous 'extern' declaration.
467   Function *TheFunction = TheModule->getFunction(Proto->getName());
468
469   if (!TheFunction)
470     TheFunction = Proto->codegen();
471
472   if (!TheFunction)
473     return nullptr;
474
475   // Create a new basic block to start insertion into.
476   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
477   Builder.SetInsertPoint(BB);
478
479   // Record the function arguments in the NamedValues map.
480   NamedValues.clear();
481   for (auto &Arg : TheFunction->args())
482     NamedValues[Arg.getName()] = &Arg;
483
484   if (Value *RetVal = Body->codegen()) {
485     // Finish off the function.
486     Builder.CreateRet(RetVal);
487
488     // Validate the generated code, checking for consistency.
489     verifyFunction(*TheFunction);
490
491     return TheFunction;
492   }
493
494   // Error reading body, remove function.
495   TheFunction->eraseFromParent();
496   return nullptr;
497 }
498
499 //===----------------------------------------------------------------------===//
500 // Top-Level parsing and JIT Driver
501 //===----------------------------------------------------------------------===//
502
503 static void HandleDefinition() {
504   if (auto FnAST = ParseDefinition()) {
505     if (auto *FnIR = FnAST->codegen()) {
506       fprintf(stderr, "Read function definition:");
507       FnIR->dump();
508     }
509   } else {
510     // Skip token for error recovery.
511     getNextToken();
512   }
513 }
514
515 static void HandleExtern() {
516   if (auto ProtoAST = ParseExtern()) {
517     if (auto *FnIR = ProtoAST->codegen()) {
518       fprintf(stderr, "Read extern: ");
519       FnIR->dump();
520     }
521   } else {
522     // Skip token for error recovery.
523     getNextToken();
524   }
525 }
526
527 static void HandleTopLevelExpression() {
528   // Evaluate a top-level expression into an anonymous function.
529   if (auto FnAST = ParseTopLevelExpr()) {
530     if (auto *FnIR = FnAST->codegen()) {
531       fprintf(stderr, "Read top-level expression:");
532       FnIR->dump();
533     }
534   } else {
535     // Skip token for error recovery.
536     getNextToken();
537   }
538 }
539
540 /// top ::= definition | external | expression | ';'
541 static void MainLoop() {
542   while (1) {
543     fprintf(stderr, "ready> ");
544     switch (CurTok) {
545     case tok_eof:
546       return;
547     case ';': // ignore top-level semicolons.
548       getNextToken();
549       break;
550     case tok_def:
551       HandleDefinition();
552       break;
553     case tok_extern:
554       HandleExtern();
555       break;
556     default:
557       HandleTopLevelExpression();
558       break;
559     }
560   }
561 }
562
563 //===----------------------------------------------------------------------===//
564 // Main driver code.
565 //===----------------------------------------------------------------------===//
566
567 int main() {
568   // Install standard binary operators.
569   // 1 is lowest precedence.
570   BinopPrecedence['<'] = 10;
571   BinopPrecedence['+'] = 20;
572   BinopPrecedence['-'] = 20;
573   BinopPrecedence['*'] = 40; // highest.
574
575   // Prime the first token.
576   fprintf(stderr, "ready> ");
577   getNextToken();
578
579   // Make the module, which holds all the code.
580   TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
581
582   // Run the main "interpreter loop" now.
583   MainLoop();
584
585   // Print out all of the generated code.
586   TheModule->dump();
587
588   return 0;
589 }