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