1 #define MINIMAL_STDERR_OUTPUT
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.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/LegacyPassManager.h"
10 #include "llvm/IR/Module.h"
11 #include "llvm/IR/Verifier.h"
12 #include "llvm/IRReader/IRReader.h"
13 #include "llvm/Support/CommandLine.h"
14 #include "llvm/Support/SourceMgr.h"
15 #include "llvm/Support/TargetSelect.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/Transforms/Scalar.h"
26 //===----------------------------------------------------------------------===//
27 // Command-line options
28 //===----------------------------------------------------------------------===//
33 cl::desc("Specify the name of an IR file to load for function definitions"),
34 cl::value_desc("input IR file name"));
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
42 // of these for known things.
47 tok_def
= -2, tok_extern
= -3,
50 tok_identifier
= -4, tok_number
= -5,
53 tok_if
= -6, tok_then
= -7, tok_else
= -8,
54 tok_for
= -9, tok_in
= -10,
57 tok_binary
= -11, tok_unary
= -12,
63 static std::string IdentifierStr
; // Filled in if tok_identifier
64 static double NumVal
; // Filled in if tok_number
66 /// gettok - Return the next token from standard input.
68 static int LastChar
= ' ';
70 // Skip any whitespace.
71 while (isspace(LastChar
))
74 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
75 IdentifierStr
= LastChar
;
76 while (isalnum((LastChar
= getchar())))
77 IdentifierStr
+= LastChar
;
79 if (IdentifierStr
== "def") return tok_def
;
80 if (IdentifierStr
== "extern") return tok_extern
;
81 if (IdentifierStr
== "if") return tok_if
;
82 if (IdentifierStr
== "then") return tok_then
;
83 if (IdentifierStr
== "else") return tok_else
;
84 if (IdentifierStr
== "for") return tok_for
;
85 if (IdentifierStr
== "in") return tok_in
;
86 if (IdentifierStr
== "binary") return tok_binary
;
87 if (IdentifierStr
== "unary") return tok_unary
;
88 if (IdentifierStr
== "var") return tok_var
;
89 return tok_identifier
;
92 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
97 } while (isdigit(LastChar
) || LastChar
== '.');
99 NumVal
= strtod(NumStr
.c_str(), 0);
103 if (LastChar
== '#') {
104 // Comment until end of line.
105 do LastChar
= getchar();
106 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
112 // Check for end of file. Don't eat the EOF.
116 // Otherwise, just return the character as its ascii value.
117 int ThisChar
= LastChar
;
118 LastChar
= getchar();
122 //===----------------------------------------------------------------------===//
123 // Abstract Syntax Tree (aka Parse Tree)
124 //===----------------------------------------------------------------------===//
126 /// ExprAST - Base class for all expression nodes.
129 virtual ~ExprAST() {}
130 virtual Value
*Codegen() = 0;
133 /// NumberExprAST - Expression class for numeric literals like "1.0".
134 class NumberExprAST
: public ExprAST
{
137 NumberExprAST(double val
) : Val(val
) {}
138 virtual Value
*Codegen();
141 /// VariableExprAST - Expression class for referencing a variable, like "a".
142 class VariableExprAST
: public ExprAST
{
145 VariableExprAST(const std::string
&name
) : Name(name
) {}
146 const std::string
&getName() const { return Name
; }
147 virtual Value
*Codegen();
150 /// UnaryExprAST - Expression class for a unary operator.
151 class UnaryExprAST
: public ExprAST
{
155 UnaryExprAST(char opcode
, ExprAST
*operand
)
156 : Opcode(opcode
), Operand(operand
) {}
157 virtual Value
*Codegen();
160 /// BinaryExprAST - Expression class for a binary operator.
161 class BinaryExprAST
: public ExprAST
{
165 BinaryExprAST(char op
, ExprAST
*lhs
, ExprAST
*rhs
)
166 : Op(op
), LHS(lhs
), RHS(rhs
) {}
167 virtual Value
*Codegen();
170 /// CallExprAST - Expression class for function calls.
171 class CallExprAST
: public ExprAST
{
173 std::vector
<ExprAST
*> Args
;
175 CallExprAST(const std::string
&callee
, std::vector
<ExprAST
*> &args
)
176 : Callee(callee
), Args(args
) {}
177 virtual Value
*Codegen();
180 /// IfExprAST - Expression class for if/then/else.
181 class IfExprAST
: public ExprAST
{
182 ExprAST
*Cond
, *Then
, *Else
;
184 IfExprAST(ExprAST
*cond
, ExprAST
*then
, ExprAST
*_else
)
185 : Cond(cond
), Then(then
), Else(_else
) {}
186 virtual Value
*Codegen();
189 /// ForExprAST - Expression class for for/in.
190 class ForExprAST
: public ExprAST
{
192 ExprAST
*Start
, *End
, *Step
, *Body
;
194 ForExprAST(const std::string
&varname
, ExprAST
*start
, ExprAST
*end
,
195 ExprAST
*step
, ExprAST
*body
)
196 : VarName(varname
), Start(start
), End(end
), Step(step
), Body(body
) {}
197 virtual Value
*Codegen();
200 /// VarExprAST - Expression class for var/in
201 class VarExprAST
: public ExprAST
{
202 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
205 VarExprAST(const std::vector
<std::pair
<std::string
, ExprAST
*> > &varnames
,
207 : VarNames(varnames
), Body(body
) {}
209 virtual Value
*Codegen();
212 /// PrototypeAST - This class represents the "prototype" for a function,
213 /// which captures its argument names as well as if it is an operator.
216 std::vector
<std::string
> Args
;
218 unsigned Precedence
; // Precedence if a binary op.
220 PrototypeAST(const std::string
&name
, const std::vector
<std::string
> &args
,
221 bool isoperator
= false, unsigned prec
= 0)
222 : Name(name
), Args(args
), isOperator(isoperator
), Precedence(prec
) {}
224 bool isUnaryOp() const { return isOperator
&& Args
.size() == 1; }
225 bool isBinaryOp() const { return isOperator
&& Args
.size() == 2; }
227 char getOperatorName() const {
228 assert(isUnaryOp() || isBinaryOp());
229 return Name
[Name
.size()-1];
232 unsigned getBinaryPrecedence() const { return Precedence
; }
236 void CreateArgumentAllocas(Function
*F
);
239 /// FunctionAST - This class represents a function definition itself.
244 FunctionAST(PrototypeAST
*proto
, ExprAST
*body
)
245 : Proto(proto
), Body(body
) {}
250 //===----------------------------------------------------------------------===//
252 //===----------------------------------------------------------------------===//
254 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
255 /// token the parser is looking at. getNextToken reads another token from the
256 /// lexer and updates CurTok with its results.
258 static int getNextToken() {
259 return CurTok
= gettok();
262 /// BinopPrecedence - This holds the precedence for each binary operator that is
264 static std::map
<char, int> BinopPrecedence
;
266 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
267 static int GetTokPrecedence() {
268 if (!isascii(CurTok
))
271 // Make sure it's a declared binop.
272 int TokPrec
= BinopPrecedence
[CurTok
];
273 if (TokPrec
<= 0) return -1;
277 /// Error* - These are little helper functions for error handling.
278 ExprAST
*Error(const char *Str
) { fprintf(stderr
, "Error: %s\n", Str
);return 0;}
279 PrototypeAST
*ErrorP(const char *Str
) { Error(Str
); return 0; }
280 FunctionAST
*ErrorF(const char *Str
) { Error(Str
); return 0; }
282 static ExprAST
*ParseExpression();
286 /// ::= identifier '(' expression* ')'
287 static ExprAST
*ParseIdentifierExpr() {
288 std::string IdName
= IdentifierStr
;
290 getNextToken(); // eat identifier.
292 if (CurTok
!= '(') // Simple variable ref.
293 return new VariableExprAST(IdName
);
296 getNextToken(); // eat (
297 std::vector
<ExprAST
*> Args
;
300 ExprAST
*Arg
= ParseExpression();
304 if (CurTok
== ')') break;
307 return Error("Expected ')' or ',' in argument list");
315 return new CallExprAST(IdName
, Args
);
318 /// numberexpr ::= number
319 static ExprAST
*ParseNumberExpr() {
320 ExprAST
*Result
= new NumberExprAST(NumVal
);
321 getNextToken(); // consume the number
325 /// parenexpr ::= '(' expression ')'
326 static ExprAST
*ParseParenExpr() {
327 getNextToken(); // eat (.
328 ExprAST
*V
= ParseExpression();
332 return Error("expected ')'");
333 getNextToken(); // eat ).
337 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
338 static ExprAST
*ParseIfExpr() {
339 getNextToken(); // eat the if.
342 ExprAST
*Cond
= ParseExpression();
345 if (CurTok
!= tok_then
)
346 return Error("expected then");
347 getNextToken(); // eat the then
349 ExprAST
*Then
= ParseExpression();
350 if (Then
== 0) return 0;
352 if (CurTok
!= tok_else
)
353 return Error("expected else");
357 ExprAST
*Else
= ParseExpression();
360 return new IfExprAST(Cond
, Then
, Else
);
363 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
364 static ExprAST
*ParseForExpr() {
365 getNextToken(); // eat the for.
367 if (CurTok
!= tok_identifier
)
368 return Error("expected identifier after for");
370 std::string IdName
= IdentifierStr
;
371 getNextToken(); // eat identifier.
374 return Error("expected '=' after for");
375 getNextToken(); // eat '='.
378 ExprAST
*Start
= ParseExpression();
379 if (Start
== 0) return 0;
381 return Error("expected ',' after for start value");
384 ExprAST
*End
= ParseExpression();
385 if (End
== 0) return 0;
387 // The step value is optional.
391 Step
= ParseExpression();
392 if (Step
== 0) return 0;
395 if (CurTok
!= tok_in
)
396 return Error("expected 'in' after for");
397 getNextToken(); // eat 'in'.
399 ExprAST
*Body
= ParseExpression();
400 if (Body
== 0) return 0;
402 return new ForExprAST(IdName
, Start
, End
, Step
, Body
);
405 /// varexpr ::= 'var' identifier ('=' expression)?
406 // (',' identifier ('=' expression)?)* 'in' expression
407 static ExprAST
*ParseVarExpr() {
408 getNextToken(); // eat the var.
410 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
412 // At least one variable name is required.
413 if (CurTok
!= tok_identifier
)
414 return Error("expected identifier after var");
417 std::string Name
= IdentifierStr
;
418 getNextToken(); // eat identifier.
420 // Read the optional initializer.
423 getNextToken(); // eat the '='.
425 Init
= ParseExpression();
426 if (Init
== 0) return 0;
429 VarNames
.push_back(std::make_pair(Name
, Init
));
431 // End of var list, exit loop.
432 if (CurTok
!= ',') break;
433 getNextToken(); // eat the ','.
435 if (CurTok
!= tok_identifier
)
436 return Error("expected identifier list after var");
439 // At this point, we have to have 'in'.
440 if (CurTok
!= tok_in
)
441 return Error("expected 'in' keyword after 'var'");
442 getNextToken(); // eat 'in'.
444 ExprAST
*Body
= ParseExpression();
445 if (Body
== 0) return 0;
447 return new VarExprAST(VarNames
, Body
);
451 /// ::= identifierexpr
457 static ExprAST
*ParsePrimary() {
459 default: return Error("unknown token when expecting an expression");
460 case tok_identifier
: return ParseIdentifierExpr();
461 case tok_number
: return ParseNumberExpr();
462 case '(': return ParseParenExpr();
463 case tok_if
: return ParseIfExpr();
464 case tok_for
: return ParseForExpr();
465 case tok_var
: return ParseVarExpr();
472 static ExprAST
*ParseUnary() {
473 // If the current token is not an operator, it must be a primary expr.
474 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
475 return ParsePrimary();
477 // If this is a unary operator, read it.
480 if (ExprAST
*Operand
= ParseUnary())
481 return new UnaryExprAST(Opc
, Operand
);
487 static ExprAST
*ParseBinOpRHS(int ExprPrec
, ExprAST
*LHS
) {
488 // If this is a binop, find its precedence.
490 int TokPrec
= GetTokPrecedence();
492 // If this is a binop that binds at least as tightly as the current binop,
493 // consume it, otherwise we are done.
494 if (TokPrec
< ExprPrec
)
497 // Okay, we know this is a binop.
499 getNextToken(); // eat binop
501 // Parse the unary expression after the binary operator.
502 ExprAST
*RHS
= ParseUnary();
505 // If BinOp binds less tightly with RHS than the operator after RHS, let
506 // the pending operator take RHS as its LHS.
507 int NextPrec
= GetTokPrecedence();
508 if (TokPrec
< NextPrec
) {
509 RHS
= ParseBinOpRHS(TokPrec
+1, RHS
);
510 if (RHS
== 0) return 0;
514 LHS
= new BinaryExprAST(BinOp
, LHS
, RHS
);
519 /// ::= unary binoprhs
521 static ExprAST
*ParseExpression() {
522 ExprAST
*LHS
= ParseUnary();
525 return ParseBinOpRHS(0, LHS
);
529 /// ::= id '(' id* ')'
530 /// ::= binary LETTER number? (id, id)
531 /// ::= unary LETTER (id)
532 static PrototypeAST
*ParsePrototype() {
535 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
536 unsigned BinaryPrecedence
= 30;
540 return ErrorP("Expected function name in prototype");
542 FnName
= IdentifierStr
;
548 if (!isascii(CurTok
))
549 return ErrorP("Expected unary operator");
551 FnName
+= (char)CurTok
;
557 if (!isascii(CurTok
))
558 return ErrorP("Expected binary operator");
560 FnName
+= (char)CurTok
;
564 // Read the precedence if present.
565 if (CurTok
== tok_number
) {
566 if (NumVal
< 1 || NumVal
> 100)
567 return ErrorP("Invalid precedecnce: must be 1..100");
568 BinaryPrecedence
= (unsigned)NumVal
;
575 return ErrorP("Expected '(' in prototype");
577 std::vector
<std::string
> ArgNames
;
578 while (getNextToken() == tok_identifier
)
579 ArgNames
.push_back(IdentifierStr
);
581 return ErrorP("Expected ')' in prototype");
584 getNextToken(); // eat ')'.
586 // Verify right number of names for operator.
587 if (Kind
&& ArgNames
.size() != Kind
)
588 return ErrorP("Invalid number of operands for operator");
590 return new PrototypeAST(FnName
, ArgNames
, Kind
!= 0, BinaryPrecedence
);
593 /// definition ::= 'def' prototype expression
594 static FunctionAST
*ParseDefinition() {
595 getNextToken(); // eat def.
596 PrototypeAST
*Proto
= ParsePrototype();
597 if (Proto
== 0) return 0;
599 if (ExprAST
*E
= ParseExpression())
600 return new FunctionAST(Proto
, E
);
604 /// toplevelexpr ::= expression
605 static FunctionAST
*ParseTopLevelExpr() {
606 if (ExprAST
*E
= ParseExpression()) {
607 // Make an anonymous proto.
608 PrototypeAST
*Proto
= new PrototypeAST("", std::vector
<std::string
>());
609 return new FunctionAST(Proto
, E
);
614 /// external ::= 'extern' prototype
615 static PrototypeAST
*ParseExtern() {
616 getNextToken(); // eat extern.
617 return ParsePrototype();
620 //===----------------------------------------------------------------------===//
622 //===----------------------------------------------------------------------===//
624 static Module
*TheModule
;
625 static FunctionPassManager
*TheFPM
;
626 static LLVMContext TheContext
;
627 static IRBuilder
<> Builder(TheContext
);
628 static std::map
<std::string
, AllocaInst
*> NamedValues
;
630 Value
*ErrorV(const char *Str
) { Error(Str
); return 0; }
632 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
633 /// the function. This is used for mutable variables etc.
634 static AllocaInst
*CreateEntryBlockAlloca(Function
*TheFunction
,
635 const std::string
&VarName
) {
636 IRBuilder
<> TmpB(&TheFunction
->getEntryBlock(),
637 TheFunction
->getEntryBlock().begin());
638 return TmpB
.CreateAlloca(Type::getDoubleTy(TheContext
), 0, VarName
.c_str());
641 Value
*NumberExprAST::Codegen() {
642 return ConstantFP::get(TheContext
, APFloat(Val
));
645 Value
*VariableExprAST::Codegen() {
646 // Look this variable up in the function.
647 Value
*V
= NamedValues
[Name
];
648 if (V
== 0) return ErrorV("Unknown variable name");
651 return Builder
.CreateLoad(V
, Name
.c_str());
654 Value
*UnaryExprAST::Codegen() {
655 Value
*OperandV
= Operand
->Codegen();
656 if (OperandV
== 0) return 0;
658 Function
*F
= TheHelper
->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode
));
660 Function
*F
= TheModule
->getFunction(std::string("unary")+Opcode
);
663 return ErrorV("Unknown unary operator");
665 return Builder
.CreateCall(F
, OperandV
, "unop");
668 Value
*BinaryExprAST::Codegen() {
669 // Special case '=' because we don't want to emit the LHS as an expression.
671 // Assignment requires the LHS to be an identifier.
672 // For now, I'm building without RTTI because LLVM builds that way by
673 // default and so we need to build that way to use the command line supprt.
674 // If you build LLVM with RTTI this can be changed back to a dynamic_cast.
675 VariableExprAST
*LHSE
= static_cast<VariableExprAST
*>(LHS
);
677 return ErrorV("destination of '=' must be a variable");
679 Value
*Val
= RHS
->Codegen();
680 if (Val
== 0) return 0;
683 Value
*Variable
= NamedValues
[LHSE
->getName()];
684 if (Variable
== 0) return ErrorV("Unknown variable name");
686 Builder
.CreateStore(Val
, Variable
);
690 Value
*L
= LHS
->Codegen();
691 Value
*R
= RHS
->Codegen();
692 if (L
== 0 || R
== 0) return 0;
695 case '+': return Builder
.CreateFAdd(L
, R
, "addtmp");
696 case '-': return Builder
.CreateFSub(L
, R
, "subtmp");
697 case '*': return Builder
.CreateFMul(L
, R
, "multmp");
698 case '/': return Builder
.CreateFDiv(L
, R
, "divtmp");
700 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
701 // Convert bool 0/1 to double 0.0 or 1.0
702 return Builder
.CreateUIToFP(L
, Type::getDoubleTy(TheContext
), "booltmp");
706 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
708 Function
*F
= TheModule
->getFunction(std::string("binary")+Op
);
709 assert(F
&& "binary operator not found!");
711 Value
*Ops
[] = { L
, R
};
712 return Builder
.CreateCall(F
, Ops
, "binop");
715 Value
*CallExprAST::Codegen() {
716 // Look up the name in the global module table.
717 Function
*CalleeF
= TheModule
->getFunction(Callee
);
720 sprintf(error_str
, "Unknown function referenced %s", Callee
.c_str());
721 return ErrorV(error_str
);
724 // If argument mismatch error.
725 if (CalleeF
->arg_size() != Args
.size())
726 return ErrorV("Incorrect # arguments passed");
728 std::vector
<Value
*> ArgsV
;
729 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
730 ArgsV
.push_back(Args
[i
]->Codegen());
731 if (ArgsV
.back() == 0) return 0;
734 return Builder
.CreateCall(CalleeF
, ArgsV
, "calltmp");
737 Value
*IfExprAST::Codegen() {
738 Value
*CondV
= Cond
->Codegen();
739 if (CondV
== 0) return 0;
741 // Convert condition to a bool by comparing equal to 0.0.
742 CondV
= Builder
.CreateFCmpONE(
743 CondV
, ConstantFP::get(TheContext
, APFloat(0.0)), "ifcond");
745 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
747 // Create blocks for the then and else cases. Insert the 'then' block at the
748 // end of the function.
749 BasicBlock
*ThenBB
= BasicBlock::Create(TheContext
, "then", TheFunction
);
750 BasicBlock
*ElseBB
= BasicBlock::Create(TheContext
, "else");
751 BasicBlock
*MergeBB
= BasicBlock::Create(TheContext
, "ifcont");
753 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
756 Builder
.SetInsertPoint(ThenBB
);
758 Value
*ThenV
= Then
->Codegen();
759 if (ThenV
== 0) return 0;
761 Builder
.CreateBr(MergeBB
);
762 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
763 ThenBB
= Builder
.GetInsertBlock();
766 TheFunction
->getBasicBlockList().push_back(ElseBB
);
767 Builder
.SetInsertPoint(ElseBB
);
769 Value
*ElseV
= Else
->Codegen();
770 if (ElseV
== 0) return 0;
772 Builder
.CreateBr(MergeBB
);
773 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
774 ElseBB
= Builder
.GetInsertBlock();
777 TheFunction
->getBasicBlockList().push_back(MergeBB
);
778 Builder
.SetInsertPoint(MergeBB
);
779 PHINode
*PN
= Builder
.CreatePHI(Type::getDoubleTy(TheContext
), 2, "iftmp");
781 PN
->addIncoming(ThenV
, ThenBB
);
782 PN
->addIncoming(ElseV
, ElseBB
);
786 Value
*ForExprAST::Codegen() {
788 // var = alloca double
791 // store start -> var
802 // nextvar = curvar + step
803 // store nextvar -> var
804 // br endcond, loop, endloop
807 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
809 // Create an alloca for the variable in the entry block.
810 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
812 // Emit the start code first, without 'variable' in scope.
813 Value
*StartVal
= Start
->Codegen();
814 if (StartVal
== 0) return 0;
816 // Store the value into the alloca.
817 Builder
.CreateStore(StartVal
, Alloca
);
819 // Make the new basic block for the loop header, inserting after current
821 BasicBlock
*LoopBB
= BasicBlock::Create(TheContext
, "loop", TheFunction
);
823 // Insert an explicit fall through from the current block to the LoopBB.
824 Builder
.CreateBr(LoopBB
);
826 // Start insertion in LoopBB.
827 Builder
.SetInsertPoint(LoopBB
);
829 // Within the loop, the variable is defined equal to the PHI node. If it
830 // shadows an existing variable, we have to restore it, so save it now.
831 AllocaInst
*OldVal
= NamedValues
[VarName
];
832 NamedValues
[VarName
] = Alloca
;
834 // Emit the body of the loop. This, like any other expr, can change the
835 // current BB. Note that we ignore the value computed by the body, but don't
837 if (Body
->Codegen() == 0)
840 // Emit the step value.
843 StepVal
= Step
->Codegen();
844 if (StepVal
== 0) return 0;
846 // If not specified, use 1.0.
847 StepVal
= ConstantFP::get(TheContext
, APFloat(1.0));
850 // Compute the end condition.
851 Value
*EndCond
= End
->Codegen();
852 if (EndCond
== 0) return EndCond
;
854 // Reload, increment, and restore the alloca. This handles the case where
855 // the body of the loop mutates the variable.
856 Value
*CurVar
= Builder
.CreateLoad(Alloca
, VarName
.c_str());
857 Value
*NextVar
= Builder
.CreateFAdd(CurVar
, StepVal
, "nextvar");
858 Builder
.CreateStore(NextVar
, Alloca
);
860 // Convert condition to a bool by comparing equal to 0.0.
861 EndCond
= Builder
.CreateFCmpONE(
862 EndCond
, ConstantFP::get(TheContext
, APFloat(0.0)), "loopcond");
864 // Create the "after loop" block and insert it.
865 BasicBlock
*AfterBB
=
866 BasicBlock::Create(TheContext
, "afterloop", TheFunction
);
868 // Insert the conditional branch into the end of LoopEndBB.
869 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
871 // Any new code will be inserted in AfterBB.
872 Builder
.SetInsertPoint(AfterBB
);
874 // Restore the unshadowed variable.
876 NamedValues
[VarName
] = OldVal
;
878 NamedValues
.erase(VarName
);
881 // for expr always returns 0.0.
882 return Constant::getNullValue(Type::getDoubleTy(TheContext
));
885 Value
*VarExprAST::Codegen() {
886 std::vector
<AllocaInst
*> OldBindings
;
888 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
890 // Register all variables and emit their initializer.
891 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
) {
892 const std::string
&VarName
= VarNames
[i
].first
;
893 ExprAST
*Init
= VarNames
[i
].second
;
895 // Emit the initializer before adding the variable to scope, this prevents
896 // the initializer from referencing the variable itself, and permits stuff
899 // var a = a in ... # refers to outer 'a'.
902 InitVal
= Init
->Codegen();
903 if (InitVal
== 0) return 0;
904 } else { // If not specified, use 0.0.
905 InitVal
= ConstantFP::get(TheContext
, APFloat(0.0));
908 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
909 Builder
.CreateStore(InitVal
, Alloca
);
911 // Remember the old variable binding so that we can restore the binding when
913 OldBindings
.push_back(NamedValues
[VarName
]);
915 // Remember this binding.
916 NamedValues
[VarName
] = Alloca
;
919 // Codegen the body, now that all vars are in scope.
920 Value
*BodyVal
= Body
->Codegen();
921 if (BodyVal
== 0) return 0;
923 // Pop all our variables from scope.
924 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
)
925 NamedValues
[VarNames
[i
].first
] = OldBindings
[i
];
927 // Return the body computation.
931 Function
*PrototypeAST::Codegen() {
932 // Make the function type: double(double,double) etc.
933 std::vector
<Type
*> Doubles(Args
.size(), Type::getDoubleTy(TheContext
));
935 FunctionType::get(Type::getDoubleTy(TheContext
), Doubles
, false);
937 Function
*F
= Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
);
938 // If F conflicted, there was already something named 'Name'. If it has a
939 // body, don't allow redefinition or reextern.
940 if (F
->getName() != Name
) {
941 // Delete the one we just made and get the existing one.
942 F
->eraseFromParent();
943 F
= TheModule
->getFunction(Name
);
944 // If F already has a body, reject this.
946 ErrorF("redefinition of function");
949 // If F took a different number of args, reject.
950 if (F
->arg_size() != Args
.size()) {
951 ErrorF("redefinition of function with different # args");
956 // Set names for all arguments.
958 for (Function::arg_iterator AI
= F
->arg_begin(); Idx
!= Args
.size();
960 AI
->setName(Args
[Idx
]);
965 /// CreateArgumentAllocas - Create an alloca for each argument and register the
966 /// argument in the symbol table so that references to it will succeed.
967 void PrototypeAST::CreateArgumentAllocas(Function
*F
) {
968 Function::arg_iterator AI
= F
->arg_begin();
969 for (unsigned Idx
= 0, e
= Args
.size(); Idx
!= e
; ++Idx
, ++AI
) {
970 // Create an alloca for this variable.
971 AllocaInst
*Alloca
= CreateEntryBlockAlloca(F
, Args
[Idx
]);
973 // Store the initial value into the alloca.
974 Builder
.CreateStore(AI
, Alloca
);
976 // Add arguments to variable symbol table.
977 NamedValues
[Args
[Idx
]] = Alloca
;
981 Function
*FunctionAST::Codegen() {
984 Function
*TheFunction
= Proto
->Codegen();
985 if (TheFunction
== 0)
988 // If this is an operator, install it.
989 if (Proto
->isBinaryOp())
990 BinopPrecedence
[Proto
->getOperatorName()] = Proto
->getBinaryPrecedence();
992 // Create a new basic block to start insertion into.
993 BasicBlock
*BB
= BasicBlock::Create(TheContext
, "entry", TheFunction
);
994 Builder
.SetInsertPoint(BB
);
996 // Add all arguments to the symbol table and create their allocas.
997 Proto
->CreateArgumentAllocas(TheFunction
);
999 if (Value
*RetVal
= Body
->Codegen()) {
1000 // Finish off the function.
1001 Builder
.CreateRet(RetVal
);
1003 // Validate the generated code, checking for consistency.
1004 verifyFunction(*TheFunction
);
1006 // Optimize the function.
1007 TheFPM
->run(*TheFunction
);
1012 // Error reading body, remove function.
1013 TheFunction
->eraseFromParent();
1015 if (Proto
->isBinaryOp())
1016 BinopPrecedence
.erase(Proto
->getOperatorName());
1020 //===----------------------------------------------------------------------===//
1021 // Top-Level parsing and JIT Driver
1022 //===----------------------------------------------------------------------===//
1024 static ExecutionEngine
*TheExecutionEngine
;
1026 static void HandleDefinition() {
1027 if (FunctionAST
*F
= ParseDefinition()) {
1028 if (Function
*LF
= F
->Codegen()) {
1029 #ifndef MINIMAL_STDERR_OUTPUT
1030 fprintf(stderr
, "Read function definition:");
1035 // Skip token for error recovery.
1040 static void HandleExtern() {
1041 if (PrototypeAST
*P
= ParseExtern()) {
1042 if (Function
*F
= P
->Codegen()) {
1043 #ifndef MINIMAL_STDERR_OUTPUT
1044 fprintf(stderr
, "Read extern: ");
1049 // Skip token for error recovery.
1054 static void HandleTopLevelExpression() {
1055 // Evaluate a top-level expression into an anonymous function.
1056 if (FunctionAST
*F
= ParseTopLevelExpr()) {
1057 if (Function
*LF
= F
->Codegen()) {
1058 // JIT the function, returning a function pointer.
1059 void *FPtr
= TheExecutionEngine
->getPointerToFunction(LF
);
1060 // Cast it to the right type (takes no arguments, returns a double) so we
1061 // can call it as a native function.
1062 double (*FP
)() = (double (*)())(intptr_t)FPtr
;
1063 #ifdef MINIMAL_STDERR_OUTPUT
1066 fprintf(stderr
, "Evaluated to %f\n", FP());
1070 // Skip token for error recovery.
1075 /// top ::= definition | external | expression | ';'
1076 static void MainLoop() {
1078 #ifndef MINIMAL_STDERR_OUTPUT
1079 fprintf(stderr
, "ready> ");
1082 case tok_eof
: return;
1083 case ';': getNextToken(); break; // ignore top-level semicolons.
1084 case tok_def
: HandleDefinition(); break;
1085 case tok_extern
: HandleExtern(); break;
1086 default: HandleTopLevelExpression(); break;
1091 //===----------------------------------------------------------------------===//
1092 // "Library" functions that can be "extern'd" from user code.
1093 //===----------------------------------------------------------------------===//
1095 /// putchard - putchar that takes a double and returns 0.
1097 double putchard(double X
) {
1102 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1104 double printd(double X
) {
1115 //===----------------------------------------------------------------------===//
1116 // Command line input file handlers
1117 //===----------------------------------------------------------------------===//
1119 Module
* parseInputIR(std::string InputFile
) {
1121 Module
*M
= ParseIRFile(InputFile
, Err
, TheContext
);
1123 Err
.print("IR parsing failed: ", errs());
1130 //===----------------------------------------------------------------------===//
1131 // Main driver code.
1132 //===----------------------------------------------------------------------===//
1134 int main(int argc
, char **argv
) {
1135 InitializeNativeTarget();
1136 LLVMContext
&Context
= TheContext
;
1138 cl::ParseCommandLineOptions(argc
, argv
,
1139 "Kaleidoscope example program\n");
1141 // Install standard binary operators.
1142 // 1 is lowest precedence.
1143 BinopPrecedence
['='] = 2;
1144 BinopPrecedence
['<'] = 10;
1145 BinopPrecedence
['+'] = 20;
1146 BinopPrecedence
['-'] = 20;
1147 BinopPrecedence
['/'] = 40;
1148 BinopPrecedence
['*'] = 40; // highest.
1150 // Make the module, which holds all the code.
1151 if (!InputIR
.empty()) {
1152 TheModule
= parseInputIR(InputIR
);
1154 TheModule
= new Module("my cool jit", Context
);
1157 // Create the JIT. This takes ownership of the module.
1159 TheExecutionEngine
= EngineBuilder(TheModule
).setErrorStr(&ErrStr
).create();
1160 if (!TheExecutionEngine
) {
1161 fprintf(stderr
, "Could not create ExecutionEngine: %s\n", ErrStr
.c_str());
1165 FunctionPassManager
OurFPM(TheModule
);
1167 // Set up the optimizer pipeline. Start with registering info about how the
1168 // target lays out data structures.
1169 OurFPM
.add(new DataLayout(*TheExecutionEngine
->getDataLayout()));
1170 // Provide basic AliasAnalysis support for GVN.
1171 OurFPM
.add(createBasicAliasAnalysisPass());
1172 // Promote allocas to registers.
1173 OurFPM
.add(createPromoteMemoryToRegisterPass());
1174 // Do simple "peephole" optimizations and bit-twiddling optzns.
1175 OurFPM
.add(createInstructionCombiningPass());
1176 // Reassociate expressions.
1177 OurFPM
.add(createReassociatePass());
1178 // Eliminate Common SubExpressions.
1179 OurFPM
.add(createGVNPass());
1180 // Simplify the control flow graph (deleting unreachable blocks, etc).
1181 OurFPM
.add(createCFGSimplificationPass());
1183 OurFPM
.doInitialization();
1185 // Set the global so the code gen can use this.
1188 // Prime the first token.
1189 #ifndef MINIMAL_STDERR_OUTPUT
1190 fprintf(stderr
, "ready> ");
1194 // Run the main "interpreter loop" now.
1197 // Print out all of the generated code.
1199 #if !defined(MINIMAL_STDERR_OUTPUT) || defined(DUMP_FINAL_MODULE)