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