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