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