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