1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/JIT.h"
4 #include "llvm/IR/DataLayout.h"
5 #include "llvm/IR/DerivedTypes.h"
6 #include "llvm/IR/IRBuilder.h"
7 #include "llvm/IR/LLVMContext.h"
8 #include "llvm/IR/Module.h"
9 #include "llvm/IR/Verifier.h"
10 #include "llvm/PassManager.h"
11 #include "llvm/Support/TargetSelect.h"
12 #include "llvm/Transforms/Scalar.h"
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
30 tok_def = -2, tok_extern = -3,
33 tok_identifier = -4, tok_number = -5,
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10,
40 tok_binary = -11, tok_unary = -12,
46 static std::string IdentifierStr; // Filled in if tok_identifier
47 static double NumVal; // Filled in if tok_number
49 /// gettok - Return the next token from standard input.
51 static int LastChar = ' ';
53 // Skip any whitespace.
54 while (isspace(LastChar))
57 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
58 IdentifierStr = LastChar;
59 while (isalnum((LastChar = getchar())))
60 IdentifierStr += LastChar;
62 if (IdentifierStr == "def") return tok_def;
63 if (IdentifierStr == "extern") return tok_extern;
64 if (IdentifierStr == "if") return tok_if;
65 if (IdentifierStr == "then") return tok_then;
66 if (IdentifierStr == "else") return tok_else;
67 if (IdentifierStr == "for") return tok_for;
68 if (IdentifierStr == "in") return tok_in;
69 if (IdentifierStr == "binary") return tok_binary;
70 if (IdentifierStr == "unary") return tok_unary;
71 if (IdentifierStr == "var") return tok_var;
72 return tok_identifier;
75 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
80 } while (isdigit(LastChar) || LastChar == '.');
82 NumVal = strtod(NumStr.c_str(), 0);
86 if (LastChar == '#') {
87 // Comment until end of line.
88 do LastChar = getchar();
89 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
95 // Check for end of file. Don't eat the EOF.
99 // Otherwise, just return the character as its ascii value.
100 int ThisChar = LastChar;
101 LastChar = getchar();
105 //===----------------------------------------------------------------------===//
106 // Abstract Syntax Tree (aka Parse Tree)
107 //===----------------------------------------------------------------------===//
109 /// ExprAST - Base class for all expression nodes.
112 virtual ~ExprAST() {}
113 virtual Value *Codegen() = 0;
116 /// NumberExprAST - Expression class for numeric literals like "1.0".
117 class NumberExprAST : public ExprAST {
120 NumberExprAST(double val) : Val(val) {}
121 virtual Value *Codegen();
124 /// VariableExprAST - Expression class for referencing a variable, like "a".
125 class VariableExprAST : public ExprAST {
128 VariableExprAST(const std::string &name) : Name(name) {}
129 const std::string &getName() const { return Name; }
130 virtual Value *Codegen();
133 /// UnaryExprAST - Expression class for a unary operator.
134 class UnaryExprAST : public ExprAST {
138 UnaryExprAST(char opcode, ExprAST *operand)
139 : Opcode(opcode), Operand(operand) {}
140 virtual Value *Codegen();
143 /// BinaryExprAST - Expression class for a binary operator.
144 class BinaryExprAST : public ExprAST {
148 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
149 : Op(op), LHS(lhs), RHS(rhs) {}
150 virtual Value *Codegen();
153 /// CallExprAST - Expression class for function calls.
154 class CallExprAST : public ExprAST {
156 std::vector<ExprAST*> Args;
158 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
159 : Callee(callee), Args(args) {}
160 virtual Value *Codegen();
163 /// IfExprAST - Expression class for if/then/else.
164 class IfExprAST : public ExprAST {
165 ExprAST *Cond, *Then, *Else;
167 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
168 : Cond(cond), Then(then), Else(_else) {}
169 virtual Value *Codegen();
172 /// ForExprAST - Expression class for for/in.
173 class ForExprAST : public ExprAST {
175 ExprAST *Start, *End, *Step, *Body;
177 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
178 ExprAST *step, ExprAST *body)
179 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
180 virtual Value *Codegen();
183 /// VarExprAST - Expression class for var/in
184 class VarExprAST : public ExprAST {
185 std::vector<std::pair<std::string, ExprAST*> > VarNames;
188 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
190 : VarNames(varnames), Body(body) {}
192 virtual Value *Codegen();
195 /// PrototypeAST - This class represents the "prototype" for a function,
196 /// which captures its argument names as well as if it is an operator.
199 std::vector<std::string> Args;
201 unsigned Precedence; // Precedence if a binary op.
203 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
204 bool isoperator = false, unsigned prec = 0)
205 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
207 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
208 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
210 char getOperatorName() const {
211 assert(isUnaryOp() || isBinaryOp());
212 return Name[Name.size()-1];
215 unsigned getBinaryPrecedence() const { return Precedence; }
219 void CreateArgumentAllocas(Function *F);
222 /// FunctionAST - This class represents a function definition itself.
227 FunctionAST(PrototypeAST *proto, ExprAST *body)
228 : Proto(proto), Body(body) {}
232 } // end anonymous namespace
234 //===----------------------------------------------------------------------===//
236 //===----------------------------------------------------------------------===//
238 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
239 /// token the parser is looking at. getNextToken reads another token from the
240 /// lexer and updates CurTok with its results.
242 static int getNextToken() {
243 return CurTok = gettok();
246 /// BinopPrecedence - This holds the precedence for each binary operator that is
248 static std::map<char, int> BinopPrecedence;
250 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
251 static int GetTokPrecedence() {
252 if (!isascii(CurTok))
255 // Make sure it's a declared binop.
256 int TokPrec = BinopPrecedence[CurTok];
257 if (TokPrec <= 0) return -1;
261 /// Error* - These are little helper functions for error handling.
262 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
263 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
264 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
266 static ExprAST *ParseExpression();
270 /// ::= identifier '(' expression* ')'
271 static ExprAST *ParseIdentifierExpr() {
272 std::string IdName = IdentifierStr;
274 getNextToken(); // eat identifier.
276 if (CurTok != '(') // Simple variable ref.
277 return new VariableExprAST(IdName);
280 getNextToken(); // eat (
281 std::vector<ExprAST*> Args;
284 ExprAST *Arg = ParseExpression();
288 if (CurTok == ')') break;
291 return Error("Expected ')' or ',' in argument list");
299 return new CallExprAST(IdName, Args);
302 /// numberexpr ::= number
303 static ExprAST *ParseNumberExpr() {
304 ExprAST *Result = new NumberExprAST(NumVal);
305 getNextToken(); // consume the number
309 /// parenexpr ::= '(' expression ')'
310 static ExprAST *ParseParenExpr() {
311 getNextToken(); // eat (.
312 ExprAST *V = ParseExpression();
316 return Error("expected ')'");
317 getNextToken(); // eat ).
321 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
322 static ExprAST *ParseIfExpr() {
323 getNextToken(); // eat the if.
326 ExprAST *Cond = ParseExpression();
329 if (CurTok != tok_then)
330 return Error("expected then");
331 getNextToken(); // eat the then
333 ExprAST *Then = ParseExpression();
334 if (Then == 0) return 0;
336 if (CurTok != tok_else)
337 return Error("expected else");
341 ExprAST *Else = ParseExpression();
344 return new IfExprAST(Cond, Then, Else);
347 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
348 static ExprAST *ParseForExpr() {
349 getNextToken(); // eat the for.
351 if (CurTok != tok_identifier)
352 return Error("expected identifier after for");
354 std::string IdName = IdentifierStr;
355 getNextToken(); // eat identifier.
358 return Error("expected '=' after for");
359 getNextToken(); // eat '='.
362 ExprAST *Start = ParseExpression();
363 if (Start == 0) return 0;
365 return Error("expected ',' after for start value");
368 ExprAST *End = ParseExpression();
369 if (End == 0) return 0;
371 // The step value is optional.
375 Step = ParseExpression();
376 if (Step == 0) return 0;
379 if (CurTok != tok_in)
380 return Error("expected 'in' after for");
381 getNextToken(); // eat 'in'.
383 ExprAST *Body = ParseExpression();
384 if (Body == 0) return 0;
386 return new ForExprAST(IdName, Start, End, Step, Body);
389 /// varexpr ::= 'var' identifier ('=' expression)?
390 // (',' identifier ('=' expression)?)* 'in' expression
391 static ExprAST *ParseVarExpr() {
392 getNextToken(); // eat the var.
394 std::vector<std::pair<std::string, ExprAST*> > VarNames;
396 // At least one variable name is required.
397 if (CurTok != tok_identifier)
398 return Error("expected identifier after var");
401 std::string Name = IdentifierStr;
402 getNextToken(); // eat identifier.
404 // Read the optional initializer.
407 getNextToken(); // eat the '='.
409 Init = ParseExpression();
410 if (Init == 0) return 0;
413 VarNames.push_back(std::make_pair(Name, Init));
415 // End of var list, exit loop.
416 if (CurTok != ',') break;
417 getNextToken(); // eat the ','.
419 if (CurTok != tok_identifier)
420 return Error("expected identifier list after var");
423 // At this point, we have to have 'in'.
424 if (CurTok != tok_in)
425 return Error("expected 'in' keyword after 'var'");
426 getNextToken(); // eat 'in'.
428 ExprAST *Body = ParseExpression();
429 if (Body == 0) return 0;
431 return new VarExprAST(VarNames, Body);
435 /// ::= identifierexpr
441 static ExprAST *ParsePrimary() {
443 default: return Error("unknown token when expecting an expression");
444 case tok_identifier: return ParseIdentifierExpr();
445 case tok_number: return ParseNumberExpr();
446 case '(': return ParseParenExpr();
447 case tok_if: return ParseIfExpr();
448 case tok_for: return ParseForExpr();
449 case tok_var: return ParseVarExpr();
456 static ExprAST *ParseUnary() {
457 // If the current token is not an operator, it must be a primary expr.
458 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
459 return ParsePrimary();
461 // If this is a unary operator, read it.
464 if (ExprAST *Operand = ParseUnary())
465 return new UnaryExprAST(Opc, Operand);
471 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
472 // If this is a binop, find its precedence.
474 int TokPrec = GetTokPrecedence();
476 // If this is a binop that binds at least as tightly as the current binop,
477 // consume it, otherwise we are done.
478 if (TokPrec < ExprPrec)
481 // Okay, we know this is a binop.
483 getNextToken(); // eat binop
485 // Parse the unary expression after the binary operator.
486 ExprAST *RHS = ParseUnary();
489 // If BinOp binds less tightly with RHS than the operator after RHS, let
490 // the pending operator take RHS as its LHS.
491 int NextPrec = GetTokPrecedence();
492 if (TokPrec < NextPrec) {
493 RHS = ParseBinOpRHS(TokPrec+1, RHS);
494 if (RHS == 0) return 0;
498 LHS = new BinaryExprAST(BinOp, LHS, RHS);
503 /// ::= unary binoprhs
505 static ExprAST *ParseExpression() {
506 ExprAST *LHS = ParseUnary();
509 return ParseBinOpRHS(0, LHS);
513 /// ::= id '(' id* ')'
514 /// ::= binary LETTER number? (id, id)
515 /// ::= unary LETTER (id)
516 static PrototypeAST *ParsePrototype() {
519 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
520 unsigned BinaryPrecedence = 30;
524 return ErrorP("Expected function name in prototype");
526 FnName = IdentifierStr;
532 if (!isascii(CurTok))
533 return ErrorP("Expected unary operator");
535 FnName += (char)CurTok;
541 if (!isascii(CurTok))
542 return ErrorP("Expected binary operator");
544 FnName += (char)CurTok;
548 // Read the precedence if present.
549 if (CurTok == tok_number) {
550 if (NumVal < 1 || NumVal > 100)
551 return ErrorP("Invalid precedecnce: must be 1..100");
552 BinaryPrecedence = (unsigned)NumVal;
559 return ErrorP("Expected '(' in prototype");
561 std::vector<std::string> ArgNames;
562 while (getNextToken() == tok_identifier)
563 ArgNames.push_back(IdentifierStr);
565 return ErrorP("Expected ')' in prototype");
568 getNextToken(); // eat ')'.
570 // Verify right number of names for operator.
571 if (Kind && ArgNames.size() != Kind)
572 return ErrorP("Invalid number of operands for operator");
574 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
577 /// definition ::= 'def' prototype expression
578 static FunctionAST *ParseDefinition() {
579 getNextToken(); // eat def.
580 PrototypeAST *Proto = ParsePrototype();
581 if (Proto == 0) return 0;
583 if (ExprAST *E = ParseExpression())
584 return new FunctionAST(Proto, E);
588 /// toplevelexpr ::= expression
589 static FunctionAST *ParseTopLevelExpr() {
590 if (ExprAST *E = ParseExpression()) {
591 // Make an anonymous proto.
592 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
593 return new FunctionAST(Proto, E);
598 /// external ::= 'extern' prototype
599 static PrototypeAST *ParseExtern() {
600 getNextToken(); // eat extern.
601 return ParsePrototype();
604 //===----------------------------------------------------------------------===//
606 //===----------------------------------------------------------------------===//
608 static Module *TheModule;
609 static IRBuilder<> Builder(getGlobalContext());
610 static std::map<std::string, AllocaInst*> NamedValues;
611 static FunctionPassManager *TheFPM;
613 Value *ErrorV(const char *Str) { Error(Str); return 0; }
615 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
616 /// the function. This is used for mutable variables etc.
617 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
618 const std::string &VarName) {
619 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
620 TheFunction->getEntryBlock().begin());
621 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
625 Value *NumberExprAST::Codegen() {
626 return ConstantFP::get(getGlobalContext(), APFloat(Val));
629 Value *VariableExprAST::Codegen() {
630 // Look this variable up in the function.
631 Value *V = NamedValues[Name];
632 if (V == 0) return ErrorV("Unknown variable name");
635 return Builder.CreateLoad(V, Name.c_str());
638 Value *UnaryExprAST::Codegen() {
639 Value *OperandV = Operand->Codegen();
640 if (OperandV == 0) return 0;
642 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
644 return ErrorV("Unknown unary operator");
646 return Builder.CreateCall(F, OperandV, "unop");
649 Value *BinaryExprAST::Codegen() {
650 // Special case '=' because we don't want to emit the LHS as an expression.
652 // Assignment requires the LHS to be an identifier.
653 VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
655 return ErrorV("destination of '=' must be a variable");
657 Value *Val = RHS->Codegen();
658 if (Val == 0) return 0;
661 Value *Variable = NamedValues[LHSE->getName()];
662 if (Variable == 0) return ErrorV("Unknown variable name");
664 Builder.CreateStore(Val, Variable);
668 Value *L = LHS->Codegen();
669 Value *R = RHS->Codegen();
670 if (L == 0 || R == 0) return 0;
673 case '+': return Builder.CreateFAdd(L, R, "addtmp");
674 case '-': return Builder.CreateFSub(L, R, "subtmp");
675 case '*': return Builder.CreateFMul(L, R, "multmp");
677 L = Builder.CreateFCmpULT(L, R, "cmptmp");
678 // Convert bool 0/1 to double 0.0 or 1.0
679 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
684 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
686 Function *F = TheModule->getFunction(std::string("binary")+Op);
687 assert(F && "binary operator not found!");
689 Value *Ops[] = { L, R };
690 return Builder.CreateCall(F, Ops, "binop");
693 Value *CallExprAST::Codegen() {
694 // Look up the name in the global module table.
695 Function *CalleeF = TheModule->getFunction(Callee);
697 return ErrorV("Unknown function referenced");
699 // If argument mismatch error.
700 if (CalleeF->arg_size() != Args.size())
701 return ErrorV("Incorrect # arguments passed");
703 std::vector<Value*> ArgsV;
704 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
705 ArgsV.push_back(Args[i]->Codegen());
706 if (ArgsV.back() == 0) return 0;
709 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
712 Value *IfExprAST::Codegen() {
713 Value *CondV = Cond->Codegen();
714 if (CondV == 0) return 0;
716 // Convert condition to a bool by comparing equal to 0.0.
717 CondV = Builder.CreateFCmpONE(CondV,
718 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
721 Function *TheFunction = Builder.GetInsertBlock()->getParent();
723 // Create blocks for the then and else cases. Insert the 'then' block at the
724 // end of the function.
725 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
726 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
727 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
729 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
732 Builder.SetInsertPoint(ThenBB);
734 Value *ThenV = Then->Codegen();
735 if (ThenV == 0) return 0;
737 Builder.CreateBr(MergeBB);
738 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
739 ThenBB = Builder.GetInsertBlock();
742 TheFunction->getBasicBlockList().push_back(ElseBB);
743 Builder.SetInsertPoint(ElseBB);
745 Value *ElseV = Else->Codegen();
746 if (ElseV == 0) return 0;
748 Builder.CreateBr(MergeBB);
749 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
750 ElseBB = Builder.GetInsertBlock();
753 TheFunction->getBasicBlockList().push_back(MergeBB);
754 Builder.SetInsertPoint(MergeBB);
755 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
758 PN->addIncoming(ThenV, ThenBB);
759 PN->addIncoming(ElseV, ElseBB);
763 Value *ForExprAST::Codegen() {
765 // var = alloca double
768 // store start -> var
779 // nextvar = curvar + step
780 // store nextvar -> var
781 // br endcond, loop, endloop
784 Function *TheFunction = Builder.GetInsertBlock()->getParent();
786 // Create an alloca for the variable in the entry block.
787 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
789 // Emit the start code first, without 'variable' in scope.
790 Value *StartVal = Start->Codegen();
791 if (StartVal == 0) return 0;
793 // Store the value into the alloca.
794 Builder.CreateStore(StartVal, Alloca);
796 // Make the new basic block for the loop header, inserting after current
798 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
800 // Insert an explicit fall through from the current block to the LoopBB.
801 Builder.CreateBr(LoopBB);
803 // Start insertion in LoopBB.
804 Builder.SetInsertPoint(LoopBB);
806 // Within the loop, the variable is defined equal to the PHI node. If it
807 // shadows an existing variable, we have to restore it, so save it now.
808 AllocaInst *OldVal = NamedValues[VarName];
809 NamedValues[VarName] = Alloca;
811 // Emit the body of the loop. This, like any other expr, can change the
812 // current BB. Note that we ignore the value computed by the body, but don't
814 if (Body->Codegen() == 0)
817 // Emit the step value.
820 StepVal = Step->Codegen();
821 if (StepVal == 0) return 0;
823 // If not specified, use 1.0.
824 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
827 // Compute the end condition.
828 Value *EndCond = End->Codegen();
829 if (EndCond == 0) return EndCond;
831 // Reload, increment, and restore the alloca. This handles the case where
832 // the body of the loop mutates the variable.
833 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
834 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
835 Builder.CreateStore(NextVar, Alloca);
837 // Convert condition to a bool by comparing equal to 0.0.
838 EndCond = Builder.CreateFCmpONE(EndCond,
839 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
842 // Create the "after loop" block and insert it.
843 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
845 // Insert the conditional branch into the end of LoopEndBB.
846 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
848 // Any new code will be inserted in AfterBB.
849 Builder.SetInsertPoint(AfterBB);
851 // Restore the unshadowed variable.
853 NamedValues[VarName] = OldVal;
855 NamedValues.erase(VarName);
858 // for expr always returns 0.0.
859 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
862 Value *VarExprAST::Codegen() {
863 std::vector<AllocaInst *> OldBindings;
865 Function *TheFunction = Builder.GetInsertBlock()->getParent();
867 // Register all variables and emit their initializer.
868 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
869 const std::string &VarName = VarNames[i].first;
870 ExprAST *Init = VarNames[i].second;
872 // Emit the initializer before adding the variable to scope, this prevents
873 // the initializer from referencing the variable itself, and permits stuff
876 // var a = a in ... # refers to outer 'a'.
879 InitVal = Init->Codegen();
880 if (InitVal == 0) return 0;
881 } else { // If not specified, use 0.0.
882 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
885 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
886 Builder.CreateStore(InitVal, Alloca);
888 // Remember the old variable binding so that we can restore the binding when
890 OldBindings.push_back(NamedValues[VarName]);
892 // Remember this binding.
893 NamedValues[VarName] = Alloca;
896 // Codegen the body, now that all vars are in scope.
897 Value *BodyVal = Body->Codegen();
898 if (BodyVal == 0) return 0;
900 // Pop all our variables from scope.
901 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
902 NamedValues[VarNames[i].first] = OldBindings[i];
904 // Return the body computation.
908 Function *PrototypeAST::Codegen() {
909 // Make the function type: double(double,double) etc.
910 std::vector<Type*> Doubles(Args.size(),
911 Type::getDoubleTy(getGlobalContext()));
912 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
915 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
917 // If F conflicted, there was already something named 'Name'. If it has a
918 // body, don't allow redefinition or reextern.
919 if (F->getName() != Name) {
920 // Delete the one we just made and get the existing one.
921 F->eraseFromParent();
922 F = TheModule->getFunction(Name);
924 // If F already has a body, reject this.
926 ErrorF("redefinition of function");
930 // If F took a different number of args, reject.
931 if (F->arg_size() != Args.size()) {
932 ErrorF("redefinition of function with different # args");
937 // Set names for all arguments.
939 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
941 AI->setName(Args[Idx]);
946 /// CreateArgumentAllocas - Create an alloca for each argument and register the
947 /// argument in the symbol table so that references to it will succeed.
948 void PrototypeAST::CreateArgumentAllocas(Function *F) {
949 Function::arg_iterator AI = F->arg_begin();
950 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
951 // Create an alloca for this variable.
952 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
954 // Store the initial value into the alloca.
955 Builder.CreateStore(AI, Alloca);
957 // Add arguments to variable symbol table.
958 NamedValues[Args[Idx]] = Alloca;
962 Function *FunctionAST::Codegen() {
965 Function *TheFunction = Proto->Codegen();
966 if (TheFunction == 0)
969 // If this is an operator, install it.
970 if (Proto->isBinaryOp())
971 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
973 // Create a new basic block to start insertion into.
974 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
975 Builder.SetInsertPoint(BB);
977 // Add all arguments to the symbol table and create their allocas.
978 Proto->CreateArgumentAllocas(TheFunction);
980 if (Value *RetVal = Body->Codegen()) {
981 // Finish off the function.
982 Builder.CreateRet(RetVal);
984 // Validate the generated code, checking for consistency.
985 verifyFunction(*TheFunction);
987 // Optimize the function.
988 TheFPM->run(*TheFunction);
993 // Error reading body, remove function.
994 TheFunction->eraseFromParent();
996 if (Proto->isBinaryOp())
997 BinopPrecedence.erase(Proto->getOperatorName());
1001 //===----------------------------------------------------------------------===//
1002 // Top-Level parsing and JIT Driver
1003 //===----------------------------------------------------------------------===//
1005 static ExecutionEngine *TheExecutionEngine;
1007 static void HandleDefinition() {
1008 if (FunctionAST *F = ParseDefinition()) {
1009 if (Function *LF = F->Codegen()) {
1010 fprintf(stderr, "Read function definition:");
1014 // Skip token for error recovery.
1019 static void HandleExtern() {
1020 if (PrototypeAST *P = ParseExtern()) {
1021 if (Function *F = P->Codegen()) {
1022 fprintf(stderr, "Read extern: ");
1026 // Skip token for error recovery.
1031 static void HandleTopLevelExpression() {
1032 // Evaluate a top-level expression into an anonymous function.
1033 if (FunctionAST *F = ParseTopLevelExpr()) {
1034 if (Function *LF = F->Codegen()) {
1035 // JIT the function, returning a function pointer.
1036 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1038 // Cast it to the right type (takes no arguments, returns a double) so we
1039 // can call it as a native function.
1040 double (*FP)() = (double (*)())(intptr_t)FPtr;
1041 fprintf(stderr, "Evaluated to %f\n", FP());
1044 // Skip token for error recovery.
1049 /// top ::= definition | external | expression | ';'
1050 static void MainLoop() {
1052 fprintf(stderr, "ready> ");
1054 case tok_eof: return;
1055 case ';': getNextToken(); break; // ignore top-level semicolons.
1056 case tok_def: HandleDefinition(); break;
1057 case tok_extern: HandleExtern(); break;
1058 default: HandleTopLevelExpression(); break;
1063 //===----------------------------------------------------------------------===//
1064 // "Library" functions that can be "extern'd" from user code.
1065 //===----------------------------------------------------------------------===//
1067 /// putchard - putchar that takes a double and returns 0.
1069 double putchard(double X) {
1074 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1076 double printd(double X) {
1081 //===----------------------------------------------------------------------===//
1082 // Main driver code.
1083 //===----------------------------------------------------------------------===//
1086 InitializeNativeTarget();
1087 LLVMContext &Context = getGlobalContext();
1089 // Install standard binary operators.
1090 // 1 is lowest precedence.
1091 BinopPrecedence['='] = 2;
1092 BinopPrecedence['<'] = 10;
1093 BinopPrecedence['+'] = 20;
1094 BinopPrecedence['-'] = 20;
1095 BinopPrecedence['*'] = 40; // highest.
1097 // Prime the first token.
1098 fprintf(stderr, "ready> ");
1101 // Make the module, which holds all the code.
1102 TheModule = new Module("my cool jit", Context);
1104 // Create the JIT. This takes ownership of the module.
1106 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
1107 if (!TheExecutionEngine) {
1108 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1112 FunctionPassManager OurFPM(TheModule);
1114 // Set up the optimizer pipeline. Start with registering info about how the
1115 // target lays out data structures.
1116 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1117 OurFPM.add(new DataLayoutPass(TheModule));
1118 // Provide basic AliasAnalysis support for GVN.
1119 OurFPM.add(createBasicAliasAnalysisPass());
1120 // Promote allocas to registers.
1121 OurFPM.add(createPromoteMemoryToRegisterPass());
1122 // Do simple "peephole" optimizations and bit-twiddling optzns.
1123 OurFPM.add(createInstructionCombiningPass());
1124 // Reassociate expressions.
1125 OurFPM.add(createReassociatePass());
1126 // Eliminate Common SubExpressions.
1127 OurFPM.add(createGVNPass());
1128 // Simplify the control flow graph (deleting unreachable blocks, etc).
1129 OurFPM.add(createCFGSimplificationPass());
1131 OurFPM.doInitialization();
1133 // Set the global so the code gen can use this.
1136 // Run the main "interpreter loop" now.
1141 // Print out all of the generated code.