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