[weak vtables] Remove a bunch of weak vtables
[oota-llvm.git] / examples / Kaleidoscope / Chapter6 / toy.cpp
1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/Analysis/Verifier.h"
3 #include "llvm/ExecutionEngine/ExecutionEngine.h"
4 #include "llvm/ExecutionEngine/JIT.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/PassManager.h"
11 #include "llvm/Support/TargetSelect.h"
12 #include "llvm/Transforms/Scalar.h"
13 #include <cctype>
14 #include <cstdio>
15 #include <map>
16 #include <string>
17 #include <vector>
18 using namespace llvm;
19
20 //===----------------------------------------------------------------------===//
21 // Lexer
22 //===----------------------------------------------------------------------===//
23
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
26 enum Token {
27   tok_eof = -1,
28
29   // commands
30   tok_def = -2, tok_extern = -3,
31
32   // primary
33   tok_identifier = -4, tok_number = -5,
34   
35   // control
36   tok_if = -6, tok_then = -7, tok_else = -8,
37   tok_for = -9, tok_in = -10,
38   
39   // operators
40   tok_binary = -11, tok_unary = -12
41 };
42
43 static std::string IdentifierStr;  // Filled in if tok_identifier
44 static double NumVal;              // Filled in if tok_number
45
46 /// gettok - Return the next token from standard input.
47 static int gettok() {
48   static int LastChar = ' ';
49
50   // Skip any whitespace.
51   while (isspace(LastChar))
52     LastChar = getchar();
53
54   if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
55     IdentifierStr = LastChar;
56     while (isalnum((LastChar = getchar())))
57       IdentifierStr += LastChar;
58
59     if (IdentifierStr == "def") return tok_def;
60     if (IdentifierStr == "extern") return tok_extern;
61     if (IdentifierStr == "if") return tok_if;
62     if (IdentifierStr == "then") return tok_then;
63     if (IdentifierStr == "else") return tok_else;
64     if (IdentifierStr == "for") return tok_for;
65     if (IdentifierStr == "in") return tok_in;
66     if (IdentifierStr == "binary") return tok_binary;
67     if (IdentifierStr == "unary") return tok_unary;
68     return tok_identifier;
69   }
70
71   if (isdigit(LastChar) || LastChar == '.') {   // Number: [0-9.]+
72     std::string NumStr;
73     do {
74       NumStr += LastChar;
75       LastChar = getchar();
76     } while (isdigit(LastChar) || LastChar == '.');
77
78     NumVal = strtod(NumStr.c_str(), 0);
79     return tok_number;
80   }
81
82   if (LastChar == '#') {
83     // Comment until end of line.
84     do LastChar = getchar();
85     while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
86     
87     if (LastChar != EOF)
88       return gettok();
89   }
90   
91   // Check for end of file.  Don't eat the EOF.
92   if (LastChar == EOF)
93     return tok_eof;
94
95   // Otherwise, just return the character as its ascii value.
96   int ThisChar = LastChar;
97   LastChar = getchar();
98   return ThisChar;
99 }
100
101 //===----------------------------------------------------------------------===//
102 // Abstract Syntax Tree (aka Parse Tree)
103 //===----------------------------------------------------------------------===//
104
105 /// ExprAST - Base class for all expression nodes.
106 class ExprAST {
107 public:
108   virtual ~ExprAST();
109   virtual Value *Codegen() = 0;
110 };
111
112 ExprAST::~ExprAST() {}
113
114 /// NumberExprAST - Expression class for numeric literals like "1.0".
115 class NumberExprAST : public ExprAST {
116   double Val;
117 public:
118   NumberExprAST(double val) : Val(val) {}
119   virtual Value *Codegen();
120 };
121
122 /// VariableExprAST - Expression class for referencing a variable, like "a".
123 class VariableExprAST : public ExprAST {
124   std::string Name;
125 public:
126   VariableExprAST(const std::string &name) : Name(name) {}
127   virtual Value *Codegen();
128 };
129
130 /// UnaryExprAST - Expression class for a unary operator.
131 class UnaryExprAST : public ExprAST {
132   char Opcode;
133   ExprAST *Operand;
134 public:
135   UnaryExprAST(char opcode, ExprAST *operand) 
136     : Opcode(opcode), Operand(operand) {}
137   virtual Value *Codegen();
138 };
139
140 /// BinaryExprAST - Expression class for a binary operator.
141 class BinaryExprAST : public ExprAST {
142   char Op;
143   ExprAST *LHS, *RHS;
144 public:
145   BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) 
146     : Op(op), LHS(lhs), RHS(rhs) {}
147   virtual Value *Codegen();
148 };
149
150 /// CallExprAST - Expression class for function calls.
151 class CallExprAST : public ExprAST {
152   std::string Callee;
153   std::vector<ExprAST*> Args;
154 public:
155   CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
156     : Callee(callee), Args(args) {}
157   virtual Value *Codegen();
158 };
159
160 /// IfExprAST - Expression class for if/then/else.
161 class IfExprAST : public ExprAST {
162   ExprAST *Cond, *Then, *Else;
163 public:
164   IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
165   : Cond(cond), Then(then), Else(_else) {}
166   virtual Value *Codegen();
167 };
168
169 /// ForExprAST - Expression class for for/in.
170 class ForExprAST : public ExprAST {
171   std::string VarName;
172   ExprAST *Start, *End, *Step, *Body;
173 public:
174   ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
175              ExprAST *step, ExprAST *body)
176     : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
177   virtual Value *Codegen();
178 };
179
180 /// PrototypeAST - This class represents the "prototype" for a function,
181 /// which captures its name, and its argument names (thus implicitly the number
182 /// of arguments the function takes), as well as if it is an operator.
183 class PrototypeAST {
184   std::string Name;
185   std::vector<std::string> Args;
186   bool isOperator;
187   unsigned Precedence;  // Precedence if a binary op.
188 public:
189   PrototypeAST(const std::string &name, const std::vector<std::string> &args,
190                bool isoperator = false, unsigned prec = 0)
191   : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
192   
193   bool isUnaryOp() const { return isOperator && Args.size() == 1; }
194   bool isBinaryOp() const { return isOperator && Args.size() == 2; }
195   
196   char getOperatorName() const {
197     assert(isUnaryOp() || isBinaryOp());
198     return Name[Name.size()-1];
199   }
200   
201   unsigned getBinaryPrecedence() const { return Precedence; }
202   
203   Function *Codegen();
204 };
205
206 /// FunctionAST - This class represents a function definition itself.
207 class FunctionAST {
208   PrototypeAST *Proto;
209   ExprAST *Body;
210 public:
211   FunctionAST(PrototypeAST *proto, ExprAST *body)
212     : Proto(proto), Body(body) {}
213   
214   Function *Codegen();
215 };
216
217 //===----------------------------------------------------------------------===//
218 // Parser
219 //===----------------------------------------------------------------------===//
220
221 /// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current
222 /// token the parser is looking at.  getNextToken reads another token from the
223 /// lexer and updates CurTok with its results.
224 static int CurTok;
225 static int getNextToken() {
226   return CurTok = gettok();
227 }
228
229 /// BinopPrecedence - This holds the precedence for each binary operator that is
230 /// defined.
231 static std::map<char, int> BinopPrecedence;
232
233 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
234 static int GetTokPrecedence() {
235   if (!isascii(CurTok))
236     return -1;
237   
238   // Make sure it's a declared binop.
239   int TokPrec = BinopPrecedence[CurTok];
240   if (TokPrec <= 0) return -1;
241   return TokPrec;
242 }
243
244 /// Error* - These are little helper functions for error handling.
245 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
246 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
247 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
248
249 static ExprAST *ParseExpression();
250
251 /// identifierexpr
252 ///   ::= identifier
253 ///   ::= identifier '(' expression* ')'
254 static ExprAST *ParseIdentifierExpr() {
255   std::string IdName = IdentifierStr;
256   
257   getNextToken();  // eat identifier.
258   
259   if (CurTok != '(') // Simple variable ref.
260     return new VariableExprAST(IdName);
261   
262   // Call.
263   getNextToken();  // eat (
264   std::vector<ExprAST*> Args;
265   if (CurTok != ')') {
266     while (1) {
267       ExprAST *Arg = ParseExpression();
268       if (!Arg) return 0;
269       Args.push_back(Arg);
270
271       if (CurTok == ')') break;
272
273       if (CurTok != ',')
274         return Error("Expected ')' or ',' in argument list");
275       getNextToken();
276     }
277   }
278
279   // Eat the ')'.
280   getNextToken();
281   
282   return new CallExprAST(IdName, Args);
283 }
284
285 /// numberexpr ::= number
286 static ExprAST *ParseNumberExpr() {
287   ExprAST *Result = new NumberExprAST(NumVal);
288   getNextToken(); // consume the number
289   return Result;
290 }
291
292 /// parenexpr ::= '(' expression ')'
293 static ExprAST *ParseParenExpr() {
294   getNextToken();  // eat (.
295   ExprAST *V = ParseExpression();
296   if (!V) return 0;
297   
298   if (CurTok != ')')
299     return Error("expected ')'");
300   getNextToken();  // eat ).
301   return V;
302 }
303
304 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
305 static ExprAST *ParseIfExpr() {
306   getNextToken();  // eat the if.
307   
308   // condition.
309   ExprAST *Cond = ParseExpression();
310   if (!Cond) return 0;
311   
312   if (CurTok != tok_then)
313     return Error("expected then");
314   getNextToken();  // eat the then
315   
316   ExprAST *Then = ParseExpression();
317   if (Then == 0) return 0;
318   
319   if (CurTok != tok_else)
320     return Error("expected else");
321   
322   getNextToken();
323   
324   ExprAST *Else = ParseExpression();
325   if (!Else) return 0;
326   
327   return new IfExprAST(Cond, Then, Else);
328 }
329
330 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
331 static ExprAST *ParseForExpr() {
332   getNextToken();  // eat the for.
333
334   if (CurTok != tok_identifier)
335     return Error("expected identifier after for");
336   
337   std::string IdName = IdentifierStr;
338   getNextToken();  // eat identifier.
339   
340   if (CurTok != '=')
341     return Error("expected '=' after for");
342   getNextToken();  // eat '='.
343   
344   
345   ExprAST *Start = ParseExpression();
346   if (Start == 0) return 0;
347   if (CurTok != ',')
348     return Error("expected ',' after for start value");
349   getNextToken();
350   
351   ExprAST *End = ParseExpression();
352   if (End == 0) return 0;
353   
354   // The step value is optional.
355   ExprAST *Step = 0;
356   if (CurTok == ',') {
357     getNextToken();
358     Step = ParseExpression();
359     if (Step == 0) return 0;
360   }
361   
362   if (CurTok != tok_in)
363     return Error("expected 'in' after for");
364   getNextToken();  // eat 'in'.
365   
366   ExprAST *Body = ParseExpression();
367   if (Body == 0) return 0;
368
369   return new ForExprAST(IdName, Start, End, Step, Body);
370 }
371
372 /// primary
373 ///   ::= identifierexpr
374 ///   ::= numberexpr
375 ///   ::= parenexpr
376 ///   ::= ifexpr
377 ///   ::= forexpr
378 static ExprAST *ParsePrimary() {
379   switch (CurTok) {
380   default: return Error("unknown token when expecting an expression");
381   case tok_identifier: return ParseIdentifierExpr();
382   case tok_number:     return ParseNumberExpr();
383   case '(':            return ParseParenExpr();
384   case tok_if:         return ParseIfExpr();
385   case tok_for:        return ParseForExpr();
386   }
387 }
388
389 /// unary
390 ///   ::= primary
391 ///   ::= '!' unary
392 static ExprAST *ParseUnary() {
393   // If the current token is not an operator, it must be a primary expr.
394   if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
395     return ParsePrimary();
396   
397   // If this is a unary operator, read it.
398   int Opc = CurTok;
399   getNextToken();
400   if (ExprAST *Operand = ParseUnary())
401     return new UnaryExprAST(Opc, Operand);
402   return 0;
403 }
404
405 /// binoprhs
406 ///   ::= ('+' unary)*
407 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
408   // If this is a binop, find its precedence.
409   while (1) {
410     int TokPrec = GetTokPrecedence();
411     
412     // If this is a binop that binds at least as tightly as the current binop,
413     // consume it, otherwise we are done.
414     if (TokPrec < ExprPrec)
415       return LHS;
416     
417     // Okay, we know this is a binop.
418     int BinOp = CurTok;
419     getNextToken();  // eat binop
420     
421     // Parse the unary expression after the binary operator.
422     ExprAST *RHS = ParseUnary();
423     if (!RHS) return 0;
424     
425     // If BinOp binds less tightly with RHS than the operator after RHS, let
426     // the pending operator take RHS as its LHS.
427     int NextPrec = GetTokPrecedence();
428     if (TokPrec < NextPrec) {
429       RHS = ParseBinOpRHS(TokPrec+1, RHS);
430       if (RHS == 0) return 0;
431     }
432     
433     // Merge LHS/RHS.
434     LHS = new BinaryExprAST(BinOp, LHS, RHS);
435   }
436 }
437
438 /// expression
439 ///   ::= unary binoprhs
440 ///
441 static ExprAST *ParseExpression() {
442   ExprAST *LHS = ParseUnary();
443   if (!LHS) return 0;
444   
445   return ParseBinOpRHS(0, LHS);
446 }
447
448 /// prototype
449 ///   ::= id '(' id* ')'
450 ///   ::= binary LETTER number? (id, id)
451 ///   ::= unary LETTER (id)
452 static PrototypeAST *ParsePrototype() {
453   std::string FnName;
454   
455   unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
456   unsigned BinaryPrecedence = 30;
457   
458   switch (CurTok) {
459   default:
460     return ErrorP("Expected function name in prototype");
461   case tok_identifier:
462     FnName = IdentifierStr;
463     Kind = 0;
464     getNextToken();
465     break;
466   case tok_unary:
467     getNextToken();
468     if (!isascii(CurTok))
469       return ErrorP("Expected unary operator");
470     FnName = "unary";
471     FnName += (char)CurTok;
472     Kind = 1;
473     getNextToken();
474     break;
475   case tok_binary:
476     getNextToken();
477     if (!isascii(CurTok))
478       return ErrorP("Expected binary operator");
479     FnName = "binary";
480     FnName += (char)CurTok;
481     Kind = 2;
482     getNextToken();
483     
484     // Read the precedence if present.
485     if (CurTok == tok_number) {
486       if (NumVal < 1 || NumVal > 100)
487         return ErrorP("Invalid precedecnce: must be 1..100");
488       BinaryPrecedence = (unsigned)NumVal;
489       getNextToken();
490     }
491     break;
492   }
493   
494   if (CurTok != '(')
495     return ErrorP("Expected '(' in prototype");
496   
497   std::vector<std::string> ArgNames;
498   while (getNextToken() == tok_identifier)
499     ArgNames.push_back(IdentifierStr);
500   if (CurTok != ')')
501     return ErrorP("Expected ')' in prototype");
502   
503   // success.
504   getNextToken();  // eat ')'.
505   
506   // Verify right number of names for operator.
507   if (Kind && ArgNames.size() != Kind)
508     return ErrorP("Invalid number of operands for operator");
509   
510   return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
511 }
512
513 /// definition ::= 'def' prototype expression
514 static FunctionAST *ParseDefinition() {
515   getNextToken();  // eat def.
516   PrototypeAST *Proto = ParsePrototype();
517   if (Proto == 0) return 0;
518
519   if (ExprAST *E = ParseExpression())
520     return new FunctionAST(Proto, E);
521   return 0;
522 }
523
524 /// toplevelexpr ::= expression
525 static FunctionAST *ParseTopLevelExpr() {
526   if (ExprAST *E = ParseExpression()) {
527     // Make an anonymous proto.
528     PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
529     return new FunctionAST(Proto, E);
530   }
531   return 0;
532 }
533
534 /// external ::= 'extern' prototype
535 static PrototypeAST *ParseExtern() {
536   getNextToken();  // eat extern.
537   return ParsePrototype();
538 }
539
540 //===----------------------------------------------------------------------===//
541 // Code Generation
542 //===----------------------------------------------------------------------===//
543
544 static Module *TheModule;
545 static IRBuilder<> Builder(getGlobalContext());
546 static std::map<std::string, Value*> NamedValues;
547 static FunctionPassManager *TheFPM;
548
549 Value *ErrorV(const char *Str) { Error(Str); return 0; }
550
551 Value *NumberExprAST::Codegen() {
552   return ConstantFP::get(getGlobalContext(), APFloat(Val));
553 }
554
555 Value *VariableExprAST::Codegen() {
556   // Look this variable up in the function.
557   Value *V = NamedValues[Name];
558   return V ? V : ErrorV("Unknown variable name");
559 }
560
561 Value *UnaryExprAST::Codegen() {
562   Value *OperandV = Operand->Codegen();
563   if (OperandV == 0) return 0;
564   
565   Function *F = TheModule->getFunction(std::string("unary")+Opcode);
566   if (F == 0)
567     return ErrorV("Unknown unary operator");
568   
569   return Builder.CreateCall(F, OperandV, "unop");
570 }
571
572 Value *BinaryExprAST::Codegen() {
573   Value *L = LHS->Codegen();
574   Value *R = RHS->Codegen();
575   if (L == 0 || R == 0) return 0;
576   
577   switch (Op) {
578   case '+': return Builder.CreateFAdd(L, R, "addtmp");
579   case '-': return Builder.CreateFSub(L, R, "subtmp");
580   case '*': return Builder.CreateFMul(L, R, "multmp");
581   case '<':
582     L = Builder.CreateFCmpULT(L, R, "cmptmp");
583     // Convert bool 0/1 to double 0.0 or 1.0
584     return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
585                                 "booltmp");
586   default: break;
587   }
588   
589   // If it wasn't a builtin binary operator, it must be a user defined one. Emit
590   // a call to it.
591   Function *F = TheModule->getFunction(std::string("binary")+Op);
592   assert(F && "binary operator not found!");
593   
594   Value *Ops[] = { L, R };
595   return Builder.CreateCall(F, Ops, "binop");
596 }
597
598 Value *CallExprAST::Codegen() {
599   // Look up the name in the global module table.
600   Function *CalleeF = TheModule->getFunction(Callee);
601   if (CalleeF == 0)
602     return ErrorV("Unknown function referenced");
603   
604   // If argument mismatch error.
605   if (CalleeF->arg_size() != Args.size())
606     return ErrorV("Incorrect # arguments passed");
607
608   std::vector<Value*> ArgsV;
609   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
610     ArgsV.push_back(Args[i]->Codegen());
611     if (ArgsV.back() == 0) return 0;
612   }
613   
614   return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
615 }
616
617 Value *IfExprAST::Codegen() {
618   Value *CondV = Cond->Codegen();
619   if (CondV == 0) return 0;
620   
621   // Convert condition to a bool by comparing equal to 0.0.
622   CondV = Builder.CreateFCmpONE(CondV, 
623                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
624                                 "ifcond");
625   
626   Function *TheFunction = Builder.GetInsertBlock()->getParent();
627   
628   // Create blocks for the then and else cases.  Insert the 'then' block at the
629   // end of the function.
630   BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
631   BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
632   BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
633   
634   Builder.CreateCondBr(CondV, ThenBB, ElseBB);
635   
636   // Emit then value.
637   Builder.SetInsertPoint(ThenBB);
638   
639   Value *ThenV = Then->Codegen();
640   if (ThenV == 0) return 0;
641   
642   Builder.CreateBr(MergeBB);
643   // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
644   ThenBB = Builder.GetInsertBlock();
645   
646   // Emit else block.
647   TheFunction->getBasicBlockList().push_back(ElseBB);
648   Builder.SetInsertPoint(ElseBB);
649   
650   Value *ElseV = Else->Codegen();
651   if (ElseV == 0) return 0;
652   
653   Builder.CreateBr(MergeBB);
654   // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
655   ElseBB = Builder.GetInsertBlock();
656   
657   // Emit merge block.
658   TheFunction->getBasicBlockList().push_back(MergeBB);
659   Builder.SetInsertPoint(MergeBB);
660   PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
661                                   "iftmp");
662   
663   PN->addIncoming(ThenV, ThenBB);
664   PN->addIncoming(ElseV, ElseBB);
665   return PN;
666 }
667
668 Value *ForExprAST::Codegen() {
669   // Output this as:
670   //   ...
671   //   start = startexpr
672   //   goto loop
673   // loop: 
674   //   variable = phi [start, loopheader], [nextvariable, loopend]
675   //   ...
676   //   bodyexpr
677   //   ...
678   // loopend:
679   //   step = stepexpr
680   //   nextvariable = variable + step
681   //   endcond = endexpr
682   //   br endcond, loop, endloop
683   // outloop:
684   
685   // Emit the start code first, without 'variable' in scope.
686   Value *StartVal = Start->Codegen();
687   if (StartVal == 0) return 0;
688   
689   // Make the new basic block for the loop header, inserting after current
690   // block.
691   Function *TheFunction = Builder.GetInsertBlock()->getParent();
692   BasicBlock *PreheaderBB = Builder.GetInsertBlock();
693   BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
694   
695   // Insert an explicit fall through from the current block to the LoopBB.
696   Builder.CreateBr(LoopBB);
697
698   // Start insertion in LoopBB.
699   Builder.SetInsertPoint(LoopBB);
700   
701   // Start the PHI node with an entry for Start.
702   PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
703   Variable->addIncoming(StartVal, PreheaderBB);
704   
705   // Within the loop, the variable is defined equal to the PHI node.  If it
706   // shadows an existing variable, we have to restore it, so save it now.
707   Value *OldVal = NamedValues[VarName];
708   NamedValues[VarName] = Variable;
709   
710   // Emit the body of the loop.  This, like any other expr, can change the
711   // current BB.  Note that we ignore the value computed by the body, but don't
712   // allow an error.
713   if (Body->Codegen() == 0)
714     return 0;
715   
716   // Emit the step value.
717   Value *StepVal;
718   if (Step) {
719     StepVal = Step->Codegen();
720     if (StepVal == 0) return 0;
721   } else {
722     // If not specified, use 1.0.
723     StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
724   }
725   
726   Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
727
728   // Compute the end condition.
729   Value *EndCond = End->Codegen();
730   if (EndCond == 0) return EndCond;
731   
732   // Convert condition to a bool by comparing equal to 0.0.
733   EndCond = Builder.CreateFCmpONE(EndCond, 
734                               ConstantFP::get(getGlobalContext(), APFloat(0.0)),
735                                   "loopcond");
736   
737   // Create the "after loop" block and insert it.
738   BasicBlock *LoopEndBB = Builder.GetInsertBlock();
739   BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
740   
741   // Insert the conditional branch into the end of LoopEndBB.
742   Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
743   
744   // Any new code will be inserted in AfterBB.
745   Builder.SetInsertPoint(AfterBB);
746   
747   // Add a new entry to the PHI node for the backedge.
748   Variable->addIncoming(NextVar, LoopEndBB);
749   
750   // Restore the unshadowed variable.
751   if (OldVal)
752     NamedValues[VarName] = OldVal;
753   else
754     NamedValues.erase(VarName);
755
756   
757   // for expr always returns 0.0.
758   return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
759 }
760
761 Function *PrototypeAST::Codegen() {
762   // Make the function type:  double(double,double) etc.
763   std::vector<Type*> Doubles(Args.size(),
764                              Type::getDoubleTy(getGlobalContext()));
765   FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
766                                        Doubles, false);
767   
768   Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
769   
770   // If F conflicted, there was already something named 'Name'.  If it has a
771   // body, don't allow redefinition or reextern.
772   if (F->getName() != Name) {
773     // Delete the one we just made and get the existing one.
774     F->eraseFromParent();
775     F = TheModule->getFunction(Name);
776     
777     // If F already has a body, reject this.
778     if (!F->empty()) {
779       ErrorF("redefinition of function");
780       return 0;
781     }
782     
783     // If F took a different number of args, reject.
784     if (F->arg_size() != Args.size()) {
785       ErrorF("redefinition of function with different # args");
786       return 0;
787     }
788   }
789   
790   // Set names for all arguments.
791   unsigned Idx = 0;
792   for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
793        ++AI, ++Idx) {
794     AI->setName(Args[Idx]);
795     
796     // Add arguments to variable symbol table.
797     NamedValues[Args[Idx]] = AI;
798   }
799   
800   return F;
801 }
802
803 Function *FunctionAST::Codegen() {
804   NamedValues.clear();
805   
806   Function *TheFunction = Proto->Codegen();
807   if (TheFunction == 0)
808     return 0;
809   
810   // If this is an operator, install it.
811   if (Proto->isBinaryOp())
812     BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
813   
814   // Create a new basic block to start insertion into.
815   BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
816   Builder.SetInsertPoint(BB);
817   
818   if (Value *RetVal = Body->Codegen()) {
819     // Finish off the function.
820     Builder.CreateRet(RetVal);
821
822     // Validate the generated code, checking for consistency.
823     verifyFunction(*TheFunction);
824
825     // Optimize the function.
826     TheFPM->run(*TheFunction);
827     
828     return TheFunction;
829   }
830   
831   // Error reading body, remove function.
832   TheFunction->eraseFromParent();
833
834   if (Proto->isBinaryOp())
835     BinopPrecedence.erase(Proto->getOperatorName());
836   return 0;
837 }
838
839 //===----------------------------------------------------------------------===//
840 // Top-Level parsing and JIT Driver
841 //===----------------------------------------------------------------------===//
842
843 static ExecutionEngine *TheExecutionEngine;
844
845 static void HandleDefinition() {
846   if (FunctionAST *F = ParseDefinition()) {
847     if (Function *LF = F->Codegen()) {
848       fprintf(stderr, "Read function definition:");
849       LF->dump();
850     }
851   } else {
852     // Skip token for error recovery.
853     getNextToken();
854   }
855 }
856
857 static void HandleExtern() {
858   if (PrototypeAST *P = ParseExtern()) {
859     if (Function *F = P->Codegen()) {
860       fprintf(stderr, "Read extern: ");
861       F->dump();
862     }
863   } else {
864     // Skip token for error recovery.
865     getNextToken();
866   }
867 }
868
869 static void HandleTopLevelExpression() {
870   // Evaluate a top-level expression into an anonymous function.
871   if (FunctionAST *F = ParseTopLevelExpr()) {
872     if (Function *LF = F->Codegen()) {
873       // JIT the function, returning a function pointer.
874       void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
875       
876       // Cast it to the right type (takes no arguments, returns a double) so we
877       // can call it as a native function.
878       double (*FP)() = (double (*)())(intptr_t)FPtr;
879       fprintf(stderr, "Evaluated to %f\n", FP());
880     }
881   } else {
882     // Skip token for error recovery.
883     getNextToken();
884   }
885 }
886
887 /// top ::= definition | external | expression | ';'
888 static void MainLoop() {
889   while (1) {
890     fprintf(stderr, "ready> ");
891     switch (CurTok) {
892     case tok_eof:    return;
893     case ';':        getNextToken(); break;  // ignore top-level semicolons.
894     case tok_def:    HandleDefinition(); break;
895     case tok_extern: HandleExtern(); break;
896     default:         HandleTopLevelExpression(); break;
897     }
898   }
899 }
900
901 //===----------------------------------------------------------------------===//
902 // "Library" functions that can be "extern'd" from user code.
903 //===----------------------------------------------------------------------===//
904
905 /// putchard - putchar that takes a double and returns 0.
906 extern "C" 
907 double putchard(double X) {
908   putchar((char)X);
909   return 0;
910 }
911
912 /// printd - printf that takes a double prints it as "%f\n", returning 0.
913 extern "C" 
914 double printd(double X) {
915   printf("%f\n", X);
916   return 0;
917 }
918
919 //===----------------------------------------------------------------------===//
920 // Main driver code.
921 //===----------------------------------------------------------------------===//
922
923 int main() {
924   InitializeNativeTarget();
925   LLVMContext &Context = getGlobalContext();
926
927   // Install standard binary operators.
928   // 1 is lowest precedence.
929   BinopPrecedence['<'] = 10;
930   BinopPrecedence['+'] = 20;
931   BinopPrecedence['-'] = 20;
932   BinopPrecedence['*'] = 40;  // highest.
933
934   // Prime the first token.
935   fprintf(stderr, "ready> ");
936   getNextToken();
937
938   // Make the module, which holds all the code.
939   TheModule = new Module("my cool jit", Context);
940
941   // Create the JIT.  This takes ownership of the module.
942   std::string ErrStr;
943   TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
944   if (!TheExecutionEngine) {
945     fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
946     exit(1);
947   }
948
949   FunctionPassManager OurFPM(TheModule);
950
951   // Set up the optimizer pipeline.  Start with registering info about how the
952   // target lays out data structures.
953   OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
954   // Provide basic AliasAnalysis support for GVN.
955   OurFPM.add(createBasicAliasAnalysisPass());
956   // Do simple "peephole" optimizations and bit-twiddling optzns.
957   OurFPM.add(createInstructionCombiningPass());
958   // Reassociate expressions.
959   OurFPM.add(createReassociatePass());
960   // Eliminate Common SubExpressions.
961   OurFPM.add(createGVNPass());
962   // Simplify the control flow graph (deleting unreachable blocks, etc).
963   OurFPM.add(createCFGSimplificationPass());
964
965   OurFPM.doInitialization();
966
967   // Set the global so the code gen can use this.
968   TheFPM = &OurFPM;
969
970   // Run the main "interpreter loop" now.
971   MainLoop();
972
973   TheFPM = 0;
974
975   // Print out all of the generated code.
976   TheModule->dump();
977
978   return 0;
979 }