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