1 #include "../include/KaleidoscopeJIT.h"
2 #include "llvm/ADT/APFloat.h"
3 #include "llvm/ADT/STLExtras.h"
4 #include "llvm/IR/BasicBlock.h"
5 #include "llvm/IR/Constants.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/Function.h"
8 #include "llvm/IR/IRBuilder.h"
9 #include "llvm/IR/Instructions.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Type.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/TargetSelect.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Transforms/InstCombine/InstCombine.h"
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Transforms/Scalar/GVN.h"
20 #include "llvm/Transforms/Utils.h"
34 using namespace llvm::orc
;
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
41 // of these for known things.
68 static std::string IdentifierStr
; // Filled in if tok_identifier
69 static double NumVal
; // Filled in if tok_number
71 /// gettok - Return the next token from standard input.
73 static int LastChar
= ' ';
75 // Skip any whitespace.
76 while (isspace(LastChar
))
79 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
80 IdentifierStr
= LastChar
;
81 while (isalnum((LastChar
= getchar())))
82 IdentifierStr
+= LastChar
;
84 if (IdentifierStr
== "def")
86 if (IdentifierStr
== "extern")
88 if (IdentifierStr
== "if")
90 if (IdentifierStr
== "then")
92 if (IdentifierStr
== "else")
94 if (IdentifierStr
== "for")
96 if (IdentifierStr
== "in")
98 if (IdentifierStr
== "binary")
100 if (IdentifierStr
== "unary")
102 if (IdentifierStr
== "var")
104 return tok_identifier
;
107 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
111 LastChar
= getchar();
112 } while (isdigit(LastChar
) || LastChar
== '.');
114 NumVal
= strtod(NumStr
.c_str(), nullptr);
118 if (LastChar
== '#') {
119 // Comment until end of line.
121 LastChar
= getchar();
122 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
128 // Check for end of file. Don't eat the EOF.
132 // Otherwise, just return the character as its ascii value.
133 int ThisChar
= LastChar
;
134 LastChar
= getchar();
138 //===----------------------------------------------------------------------===//
139 // Abstract Syntax Tree (aka Parse Tree)
140 //===----------------------------------------------------------------------===//
144 /// ExprAST - Base class for all expression nodes.
147 virtual ~ExprAST() = default;
149 virtual Value
*codegen() = 0;
152 /// NumberExprAST - Expression class for numeric literals like "1.0".
153 class NumberExprAST
: public ExprAST
{
157 NumberExprAST(double Val
) : Val(Val
) {}
159 Value
*codegen() override
;
162 /// VariableExprAST - Expression class for referencing a variable, like "a".
163 class VariableExprAST
: public ExprAST
{
167 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
169 Value
*codegen() override
;
170 const std::string
&getName() const { return Name
; }
173 /// UnaryExprAST - Expression class for a unary operator.
174 class UnaryExprAST
: public ExprAST
{
176 std::unique_ptr
<ExprAST
> Operand
;
179 UnaryExprAST(char Opcode
, std::unique_ptr
<ExprAST
> Operand
)
180 : Opcode(Opcode
), Operand(std::move(Operand
)) {}
182 Value
*codegen() override
;
185 /// BinaryExprAST - Expression class for a binary operator.
186 class BinaryExprAST
: public ExprAST
{
188 std::unique_ptr
<ExprAST
> LHS
, RHS
;
191 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
192 std::unique_ptr
<ExprAST
> RHS
)
193 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
195 Value
*codegen() override
;
198 /// CallExprAST - Expression class for function calls.
199 class CallExprAST
: public ExprAST
{
201 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
204 CallExprAST(const std::string
&Callee
,
205 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
206 : Callee(Callee
), Args(std::move(Args
)) {}
208 Value
*codegen() override
;
211 /// IfExprAST - Expression class for if/then/else.
212 class IfExprAST
: public ExprAST
{
213 std::unique_ptr
<ExprAST
> Cond
, Then
, Else
;
216 IfExprAST(std::unique_ptr
<ExprAST
> Cond
, std::unique_ptr
<ExprAST
> Then
,
217 std::unique_ptr
<ExprAST
> Else
)
218 : Cond(std::move(Cond
)), Then(std::move(Then
)), Else(std::move(Else
)) {}
220 Value
*codegen() override
;
223 /// ForExprAST - Expression class for for/in.
224 class ForExprAST
: public ExprAST
{
226 std::unique_ptr
<ExprAST
> Start
, End
, Step
, Body
;
229 ForExprAST(const std::string
&VarName
, std::unique_ptr
<ExprAST
> Start
,
230 std::unique_ptr
<ExprAST
> End
, std::unique_ptr
<ExprAST
> Step
,
231 std::unique_ptr
<ExprAST
> Body
)
232 : VarName(VarName
), Start(std::move(Start
)), End(std::move(End
)),
233 Step(std::move(Step
)), Body(std::move(Body
)) {}
235 Value
*codegen() override
;
238 /// VarExprAST - Expression class for var/in
239 class VarExprAST
: public ExprAST
{
240 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
;
241 std::unique_ptr
<ExprAST
> Body
;
245 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
,
246 std::unique_ptr
<ExprAST
> Body
)
247 : VarNames(std::move(VarNames
)), Body(std::move(Body
)) {}
249 Value
*codegen() override
;
252 /// PrototypeAST - This class represents the "prototype" for a function,
253 /// which captures its name, and its argument names (thus implicitly the number
254 /// of arguments the function takes), as well as if it is an operator.
257 std::vector
<std::string
> Args
;
259 unsigned Precedence
; // Precedence if a binary op.
262 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
,
263 bool IsOperator
= false, unsigned Prec
= 0)
264 : Name(Name
), Args(std::move(Args
)), IsOperator(IsOperator
),
268 const std::string
&getName() const { return Name
; }
270 bool isUnaryOp() const { return IsOperator
&& Args
.size() == 1; }
271 bool isBinaryOp() const { return IsOperator
&& Args
.size() == 2; }
273 char getOperatorName() const {
274 assert(isUnaryOp() || isBinaryOp());
275 return Name
[Name
.size() - 1];
278 unsigned getBinaryPrecedence() const { return Precedence
; }
281 /// FunctionAST - This class represents a function definition itself.
283 std::unique_ptr
<PrototypeAST
> Proto
;
284 std::unique_ptr
<ExprAST
> Body
;
287 FunctionAST(std::unique_ptr
<PrototypeAST
> Proto
,
288 std::unique_ptr
<ExprAST
> Body
)
289 : Proto(std::move(Proto
)), Body(std::move(Body
)) {}
294 } // end anonymous namespace
296 //===----------------------------------------------------------------------===//
298 //===----------------------------------------------------------------------===//
300 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
301 /// token the parser is looking at. getNextToken reads another token from the
302 /// lexer and updates CurTok with its results.
304 static int getNextToken() { return CurTok
= gettok(); }
306 /// BinopPrecedence - This holds the precedence for each binary operator that is
308 static std::map
<char, int> BinopPrecedence
;
310 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
311 static int GetTokPrecedence() {
312 if (!isascii(CurTok
))
315 // Make sure it's a declared binop.
316 int TokPrec
= BinopPrecedence
[CurTok
];
322 /// LogError* - These are little helper functions for error handling.
323 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
324 fprintf(stderr
, "Error: %s\n", Str
);
328 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
333 static std::unique_ptr
<ExprAST
> ParseExpression();
335 /// numberexpr ::= number
336 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
337 auto Result
= std::make_unique
<NumberExprAST
>(NumVal
);
338 getNextToken(); // consume the number
339 return std::move(Result
);
342 /// parenexpr ::= '(' expression ')'
343 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
344 getNextToken(); // eat (.
345 auto V
= ParseExpression();
350 return LogError("expected ')'");
351 getNextToken(); // eat ).
357 /// ::= identifier '(' expression* ')'
358 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
359 std::string IdName
= IdentifierStr
;
361 getNextToken(); // eat identifier.
363 if (CurTok
!= '(') // Simple variable ref.
364 return std::make_unique
<VariableExprAST
>(IdName
);
367 getNextToken(); // eat (
368 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
371 if (auto Arg
= ParseExpression())
372 Args
.push_back(std::move(Arg
));
380 return LogError("Expected ')' or ',' in argument list");
388 return std::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
391 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
392 static std::unique_ptr
<ExprAST
> ParseIfExpr() {
393 getNextToken(); // eat the if.
396 auto Cond
= ParseExpression();
400 if (CurTok
!= tok_then
)
401 return LogError("expected then");
402 getNextToken(); // eat the then
404 auto Then
= ParseExpression();
408 if (CurTok
!= tok_else
)
409 return LogError("expected else");
413 auto Else
= ParseExpression();
417 return std::make_unique
<IfExprAST
>(std::move(Cond
), std::move(Then
),
421 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
422 static std::unique_ptr
<ExprAST
> ParseForExpr() {
423 getNextToken(); // eat the for.
425 if (CurTok
!= tok_identifier
)
426 return LogError("expected identifier after for");
428 std::string IdName
= IdentifierStr
;
429 getNextToken(); // eat identifier.
432 return LogError("expected '=' after for");
433 getNextToken(); // eat '='.
435 auto Start
= ParseExpression();
439 return LogError("expected ',' after for start value");
442 auto End
= ParseExpression();
446 // The step value is optional.
447 std::unique_ptr
<ExprAST
> Step
;
450 Step
= ParseExpression();
455 if (CurTok
!= tok_in
)
456 return LogError("expected 'in' after for");
457 getNextToken(); // eat 'in'.
459 auto Body
= ParseExpression();
463 return std::make_unique
<ForExprAST
>(IdName
, std::move(Start
), std::move(End
),
464 std::move(Step
), std::move(Body
));
467 /// varexpr ::= 'var' identifier ('=' expression)?
468 // (',' identifier ('=' expression)?)* 'in' expression
469 static std::unique_ptr
<ExprAST
> ParseVarExpr() {
470 getNextToken(); // eat the var.
472 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
;
474 // At least one variable name is required.
475 if (CurTok
!= tok_identifier
)
476 return LogError("expected identifier after var");
479 std::string Name
= IdentifierStr
;
480 getNextToken(); // eat identifier.
482 // Read the optional initializer.
483 std::unique_ptr
<ExprAST
> Init
= nullptr;
485 getNextToken(); // eat the '='.
487 Init
= ParseExpression();
492 VarNames
.push_back(std::make_pair(Name
, std::move(Init
)));
494 // End of var list, exit loop.
497 getNextToken(); // eat the ','.
499 if (CurTok
!= tok_identifier
)
500 return LogError("expected identifier list after var");
503 // At this point, we have to have 'in'.
504 if (CurTok
!= tok_in
)
505 return LogError("expected 'in' keyword after 'var'");
506 getNextToken(); // eat 'in'.
508 auto Body
= ParseExpression();
512 return std::make_unique
<VarExprAST
>(std::move(VarNames
), std::move(Body
));
516 /// ::= identifierexpr
522 static std::unique_ptr
<ExprAST
> ParsePrimary() {
525 return LogError("unknown token when expecting an expression");
527 return ParseIdentifierExpr();
529 return ParseNumberExpr();
531 return ParseParenExpr();
533 return ParseIfExpr();
535 return ParseForExpr();
537 return ParseVarExpr();
544 static std::unique_ptr
<ExprAST
> ParseUnary() {
545 // If the current token is not an operator, it must be a primary expr.
546 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
547 return ParsePrimary();
549 // If this is a unary operator, read it.
552 if (auto Operand
= ParseUnary())
553 return std::make_unique
<UnaryExprAST
>(Opc
, std::move(Operand
));
559 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
560 std::unique_ptr
<ExprAST
> LHS
) {
561 // If this is a binop, find its precedence.
563 int TokPrec
= GetTokPrecedence();
565 // If this is a binop that binds at least as tightly as the current binop,
566 // consume it, otherwise we are done.
567 if (TokPrec
< ExprPrec
)
570 // Okay, we know this is a binop.
572 getNextToken(); // eat binop
574 // Parse the unary expression after the binary operator.
575 auto RHS
= ParseUnary();
579 // If BinOp binds less tightly with RHS than the operator after RHS, let
580 // the pending operator take RHS as its LHS.
581 int NextPrec
= GetTokPrecedence();
582 if (TokPrec
< NextPrec
) {
583 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
590 std::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
), std::move(RHS
));
595 /// ::= unary binoprhs
597 static std::unique_ptr
<ExprAST
> ParseExpression() {
598 auto LHS
= ParseUnary();
602 return ParseBinOpRHS(0, std::move(LHS
));
606 /// ::= id '(' id* ')'
607 /// ::= binary LETTER number? (id, id)
608 /// ::= unary LETTER (id)
609 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
612 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
613 unsigned BinaryPrecedence
= 30;
617 return LogErrorP("Expected function name in prototype");
619 FnName
= IdentifierStr
;
625 if (!isascii(CurTok
))
626 return LogErrorP("Expected unary operator");
628 FnName
+= (char)CurTok
;
634 if (!isascii(CurTok
))
635 return LogErrorP("Expected binary operator");
637 FnName
+= (char)CurTok
;
641 // Read the precedence if present.
642 if (CurTok
== tok_number
) {
643 if (NumVal
< 1 || NumVal
> 100)
644 return LogErrorP("Invalid precedence: must be 1..100");
645 BinaryPrecedence
= (unsigned)NumVal
;
652 return LogErrorP("Expected '(' in prototype");
654 std::vector
<std::string
> ArgNames
;
655 while (getNextToken() == tok_identifier
)
656 ArgNames
.push_back(IdentifierStr
);
658 return LogErrorP("Expected ')' in prototype");
661 getNextToken(); // eat ')'.
663 // Verify right number of names for operator.
664 if (Kind
&& ArgNames
.size() != Kind
)
665 return LogErrorP("Invalid number of operands for operator");
667 return std::make_unique
<PrototypeAST
>(FnName
, ArgNames
, Kind
!= 0,
671 /// definition ::= 'def' prototype expression
672 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
673 getNextToken(); // eat def.
674 auto Proto
= ParsePrototype();
678 if (auto E
= ParseExpression())
679 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
683 /// toplevelexpr ::= expression
684 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
685 if (auto E
= ParseExpression()) {
686 // Make an anonymous proto.
687 auto Proto
= std::make_unique
<PrototypeAST
>("__anon_expr",
688 std::vector
<std::string
>());
689 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
694 /// external ::= 'extern' prototype
695 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
696 getNextToken(); // eat extern.
697 return ParsePrototype();
700 //===----------------------------------------------------------------------===//
702 //===----------------------------------------------------------------------===//
704 static LLVMContext TheContext
;
705 static IRBuilder
<> Builder(TheContext
);
706 static std::unique_ptr
<Module
> TheModule
;
707 static std::map
<std::string
, AllocaInst
*> NamedValues
;
708 static std::unique_ptr
<legacy::FunctionPassManager
> TheFPM
;
709 static std::unique_ptr
<KaleidoscopeJIT
> TheJIT
;
710 static std::map
<std::string
, std::unique_ptr
<PrototypeAST
>> FunctionProtos
;
712 Value
*LogErrorV(const char *Str
) {
717 Function
*getFunction(std::string Name
) {
718 // First, see if the function has already been added to the current module.
719 if (auto *F
= TheModule
->getFunction(Name
))
722 // If not, check whether we can codegen the declaration from some existing
724 auto FI
= FunctionProtos
.find(Name
);
725 if (FI
!= FunctionProtos
.end())
726 return FI
->second
->codegen();
728 // If no existing prototype exists, return null.
732 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
733 /// the function. This is used for mutable variables etc.
734 static AllocaInst
*CreateEntryBlockAlloca(Function
*TheFunction
,
735 const std::string
&VarName
) {
736 IRBuilder
<> TmpB(&TheFunction
->getEntryBlock(),
737 TheFunction
->getEntryBlock().begin());
738 return TmpB
.CreateAlloca(Type::getDoubleTy(TheContext
), nullptr, VarName
);
741 Value
*NumberExprAST::codegen() {
742 return ConstantFP::get(TheContext
, APFloat(Val
));
745 Value
*VariableExprAST::codegen() {
746 // Look this variable up in the function.
747 Value
*V
= NamedValues
[Name
];
749 return LogErrorV("Unknown variable name");
752 return Builder
.CreateLoad(V
, Name
.c_str());
755 Value
*UnaryExprAST::codegen() {
756 Value
*OperandV
= Operand
->codegen();
760 Function
*F
= getFunction(std::string("unary") + Opcode
);
762 return LogErrorV("Unknown unary operator");
764 return Builder
.CreateCall(F
, OperandV
, "unop");
767 Value
*BinaryExprAST::codegen() {
768 // Special case '=' because we don't want to emit the LHS as an expression.
770 // Assignment requires the LHS to be an identifier.
771 // This assume we're building without RTTI because LLVM builds that way by
772 // default. If you build LLVM with RTTI this can be changed to a
773 // dynamic_cast for automatic error checking.
774 VariableExprAST
*LHSE
= static_cast<VariableExprAST
*>(LHS
.get());
776 return LogErrorV("destination of '=' must be a variable");
778 Value
*Val
= RHS
->codegen();
783 Value
*Variable
= NamedValues
[LHSE
->getName()];
785 return LogErrorV("Unknown variable name");
787 Builder
.CreateStore(Val
, Variable
);
791 Value
*L
= LHS
->codegen();
792 Value
*R
= RHS
->codegen();
798 return Builder
.CreateFAdd(L
, R
, "addtmp");
800 return Builder
.CreateFSub(L
, R
, "subtmp");
802 return Builder
.CreateFMul(L
, R
, "multmp");
804 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
805 // Convert bool 0/1 to double 0.0 or 1.0
806 return Builder
.CreateUIToFP(L
, Type::getDoubleTy(TheContext
), "booltmp");
811 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
813 Function
*F
= getFunction(std::string("binary") + Op
);
814 assert(F
&& "binary operator not found!");
816 Value
*Ops
[] = {L
, R
};
817 return Builder
.CreateCall(F
, Ops
, "binop");
820 Value
*CallExprAST::codegen() {
821 // Look up the name in the global module table.
822 Function
*CalleeF
= getFunction(Callee
);
824 return LogErrorV("Unknown function referenced");
826 // If argument mismatch error.
827 if (CalleeF
->arg_size() != Args
.size())
828 return LogErrorV("Incorrect # arguments passed");
830 std::vector
<Value
*> ArgsV
;
831 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
832 ArgsV
.push_back(Args
[i
]->codegen());
837 return Builder
.CreateCall(CalleeF
, ArgsV
, "calltmp");
840 Value
*IfExprAST::codegen() {
841 Value
*CondV
= Cond
->codegen();
845 // Convert condition to a bool by comparing non-equal to 0.0.
846 CondV
= Builder
.CreateFCmpONE(
847 CondV
, ConstantFP::get(TheContext
, APFloat(0.0)), "ifcond");
849 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
851 // Create blocks for the then and else cases. Insert the 'then' block at the
852 // end of the function.
853 BasicBlock
*ThenBB
= BasicBlock::Create(TheContext
, "then", TheFunction
);
854 BasicBlock
*ElseBB
= BasicBlock::Create(TheContext
, "else");
855 BasicBlock
*MergeBB
= BasicBlock::Create(TheContext
, "ifcont");
857 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
860 Builder
.SetInsertPoint(ThenBB
);
862 Value
*ThenV
= Then
->codegen();
866 Builder
.CreateBr(MergeBB
);
867 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
868 ThenBB
= Builder
.GetInsertBlock();
871 TheFunction
->getBasicBlockList().push_back(ElseBB
);
872 Builder
.SetInsertPoint(ElseBB
);
874 Value
*ElseV
= Else
->codegen();
878 Builder
.CreateBr(MergeBB
);
879 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
880 ElseBB
= Builder
.GetInsertBlock();
883 TheFunction
->getBasicBlockList().push_back(MergeBB
);
884 Builder
.SetInsertPoint(MergeBB
);
885 PHINode
*PN
= Builder
.CreatePHI(Type::getDoubleTy(TheContext
), 2, "iftmp");
887 PN
->addIncoming(ThenV
, ThenBB
);
888 PN
->addIncoming(ElseV
, ElseBB
);
892 // Output for-loop as:
893 // var = alloca double
896 // store start -> var
907 // nextvar = curvar + step
908 // store nextvar -> var
909 // br endcond, loop, endloop
911 Value
*ForExprAST::codegen() {
912 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
914 // Create an alloca for the variable in the entry block.
915 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
917 // Emit the start code first, without 'variable' in scope.
918 Value
*StartVal
= Start
->codegen();
922 // Store the value into the alloca.
923 Builder
.CreateStore(StartVal
, Alloca
);
925 // Make the new basic block for the loop header, inserting after current
927 BasicBlock
*LoopBB
= BasicBlock::Create(TheContext
, "loop", TheFunction
);
929 // Insert an explicit fall through from the current block to the LoopBB.
930 Builder
.CreateBr(LoopBB
);
932 // Start insertion in LoopBB.
933 Builder
.SetInsertPoint(LoopBB
);
935 // Within the loop, the variable is defined equal to the PHI node. If it
936 // shadows an existing variable, we have to restore it, so save it now.
937 AllocaInst
*OldVal
= NamedValues
[VarName
];
938 NamedValues
[VarName
] = Alloca
;
940 // Emit the body of the loop. This, like any other expr, can change the
941 // current BB. Note that we ignore the value computed by the body, but don't
943 if (!Body
->codegen())
946 // Emit the step value.
947 Value
*StepVal
= nullptr;
949 StepVal
= Step
->codegen();
953 // If not specified, use 1.0.
954 StepVal
= ConstantFP::get(TheContext
, APFloat(1.0));
957 // Compute the end condition.
958 Value
*EndCond
= End
->codegen();
962 // Reload, increment, and restore the alloca. This handles the case where
963 // the body of the loop mutates the variable.
964 Value
*CurVar
= Builder
.CreateLoad(Alloca
, VarName
.c_str());
965 Value
*NextVar
= Builder
.CreateFAdd(CurVar
, StepVal
, "nextvar");
966 Builder
.CreateStore(NextVar
, Alloca
);
968 // Convert condition to a bool by comparing non-equal to 0.0.
969 EndCond
= Builder
.CreateFCmpONE(
970 EndCond
, ConstantFP::get(TheContext
, APFloat(0.0)), "loopcond");
972 // Create the "after loop" block and insert it.
973 BasicBlock
*AfterBB
=
974 BasicBlock::Create(TheContext
, "afterloop", TheFunction
);
976 // Insert the conditional branch into the end of LoopEndBB.
977 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
979 // Any new code will be inserted in AfterBB.
980 Builder
.SetInsertPoint(AfterBB
);
982 // Restore the unshadowed variable.
984 NamedValues
[VarName
] = OldVal
;
986 NamedValues
.erase(VarName
);
988 // for expr always returns 0.0.
989 return Constant::getNullValue(Type::getDoubleTy(TheContext
));
992 Value
*VarExprAST::codegen() {
993 std::vector
<AllocaInst
*> OldBindings
;
995 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
997 // Register all variables and emit their initializer.
998 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
) {
999 const std::string
&VarName
= VarNames
[i
].first
;
1000 ExprAST
*Init
= VarNames
[i
].second
.get();
1002 // Emit the initializer before adding the variable to scope, this prevents
1003 // the initializer from referencing the variable itself, and permits stuff
1006 // var a = a in ... # refers to outer 'a'.
1009 InitVal
= Init
->codegen();
1012 } else { // If not specified, use 0.0.
1013 InitVal
= ConstantFP::get(TheContext
, APFloat(0.0));
1016 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
1017 Builder
.CreateStore(InitVal
, Alloca
);
1019 // Remember the old variable binding so that we can restore the binding when
1021 OldBindings
.push_back(NamedValues
[VarName
]);
1023 // Remember this binding.
1024 NamedValues
[VarName
] = Alloca
;
1027 // Codegen the body, now that all vars are in scope.
1028 Value
*BodyVal
= Body
->codegen();
1032 // Pop all our variables from scope.
1033 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
)
1034 NamedValues
[VarNames
[i
].first
] = OldBindings
[i
];
1036 // Return the body computation.
1040 Function
*PrototypeAST::codegen() {
1041 // Make the function type: double(double,double) etc.
1042 std::vector
<Type
*> Doubles(Args
.size(), Type::getDoubleTy(TheContext
));
1044 FunctionType::get(Type::getDoubleTy(TheContext
), Doubles
, false);
1047 Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
.get());
1049 // Set names for all arguments.
1051 for (auto &Arg
: F
->args())
1052 Arg
.setName(Args
[Idx
++]);
1057 Function
*FunctionAST::codegen() {
1058 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1059 // reference to it for use below.
1061 FunctionProtos
[Proto
->getName()] = std::move(Proto
);
1062 Function
*TheFunction
= getFunction(P
.getName());
1066 // If this is an operator, install it.
1068 BinopPrecedence
[P
.getOperatorName()] = P
.getBinaryPrecedence();
1070 // Create a new basic block to start insertion into.
1071 BasicBlock
*BB
= BasicBlock::Create(TheContext
, "entry", TheFunction
);
1072 Builder
.SetInsertPoint(BB
);
1074 // Record the function arguments in the NamedValues map.
1075 NamedValues
.clear();
1076 for (auto &Arg
: TheFunction
->args()) {
1077 // Create an alloca for this variable.
1078 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, Arg
.getName());
1080 // Store the initial value into the alloca.
1081 Builder
.CreateStore(&Arg
, Alloca
);
1083 // Add arguments to variable symbol table.
1084 NamedValues
[Arg
.getName()] = Alloca
;
1087 if (Value
*RetVal
= Body
->codegen()) {
1088 // Finish off the function.
1089 Builder
.CreateRet(RetVal
);
1091 // Validate the generated code, checking for consistency.
1092 verifyFunction(*TheFunction
);
1094 // Run the optimizer on the function.
1095 TheFPM
->run(*TheFunction
);
1100 // Error reading body, remove function.
1101 TheFunction
->eraseFromParent();
1104 BinopPrecedence
.erase(P
.getOperatorName());
1108 //===----------------------------------------------------------------------===//
1109 // Top-Level parsing and JIT Driver
1110 //===----------------------------------------------------------------------===//
1112 static void InitializeModuleAndPassManager() {
1113 // Open a new module.
1114 TheModule
= std::make_unique
<Module
>("my cool jit", TheContext
);
1115 TheModule
->setDataLayout(TheJIT
->getTargetMachine().createDataLayout());
1117 // Create a new pass manager attached to it.
1118 TheFPM
= std::make_unique
<legacy::FunctionPassManager
>(TheModule
.get());
1120 // Promote allocas to registers.
1121 TheFPM
->add(createPromoteMemoryToRegisterPass());
1122 // Do simple "peephole" optimizations and bit-twiddling optzns.
1123 TheFPM
->add(createInstructionCombiningPass());
1124 // Reassociate expressions.
1125 TheFPM
->add(createReassociatePass());
1126 // Eliminate Common SubExpressions.
1127 TheFPM
->add(createGVNPass());
1128 // Simplify the control flow graph (deleting unreachable blocks, etc).
1129 TheFPM
->add(createCFGSimplificationPass());
1131 TheFPM
->doInitialization();
1134 static void HandleDefinition() {
1135 if (auto FnAST
= ParseDefinition()) {
1136 if (auto *FnIR
= FnAST
->codegen()) {
1137 fprintf(stderr
, "Read function definition:");
1138 FnIR
->print(errs());
1139 fprintf(stderr
, "\n");
1140 TheJIT
->addModule(std::move(TheModule
));
1141 InitializeModuleAndPassManager();
1144 // Skip token for error recovery.
1149 static void HandleExtern() {
1150 if (auto ProtoAST
= ParseExtern()) {
1151 if (auto *FnIR
= ProtoAST
->codegen()) {
1152 fprintf(stderr
, "Read extern: ");
1153 FnIR
->print(errs());
1154 fprintf(stderr
, "\n");
1155 FunctionProtos
[ProtoAST
->getName()] = std::move(ProtoAST
);
1158 // Skip token for error recovery.
1163 static void HandleTopLevelExpression() {
1164 // Evaluate a top-level expression into an anonymous function.
1165 if (auto FnAST
= ParseTopLevelExpr()) {
1166 if (FnAST
->codegen()) {
1167 // JIT the module containing the anonymous expression, keeping a handle so
1168 // we can free it later.
1169 auto H
= TheJIT
->addModule(std::move(TheModule
));
1170 InitializeModuleAndPassManager();
1172 // Search the JIT for the __anon_expr symbol.
1173 auto ExprSymbol
= TheJIT
->findSymbol("__anon_expr");
1174 assert(ExprSymbol
&& "Function not found");
1176 // Get the symbol's address and cast it to the right type (takes no
1177 // arguments, returns a double) so we can call it as a native function.
1178 double (*FP
)() = (double (*)())(intptr_t)cantFail(ExprSymbol
.getAddress());
1179 fprintf(stderr
, "Evaluated to %f\n", FP());
1181 // Delete the anonymous expression module from the JIT.
1182 TheJIT
->removeModule(H
);
1185 // Skip token for error recovery.
1190 /// top ::= definition | external | expression | ';'
1191 static void MainLoop() {
1193 fprintf(stderr
, "ready> ");
1197 case ';': // ignore top-level semicolons.
1207 HandleTopLevelExpression();
1213 //===----------------------------------------------------------------------===//
1214 // "Library" functions that can be "extern'd" from user code.
1215 //===----------------------------------------------------------------------===//
1218 #define DLLEXPORT __declspec(dllexport)
1223 /// putchard - putchar that takes a double and returns 0.
1224 extern "C" DLLEXPORT
double putchard(double X
) {
1225 fputc((char)X
, stderr
);
1229 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1230 extern "C" DLLEXPORT
double printd(double X
) {
1231 fprintf(stderr
, "%f\n", X
);
1235 //===----------------------------------------------------------------------===//
1236 // Main driver code.
1237 //===----------------------------------------------------------------------===//
1240 InitializeNativeTarget();
1241 InitializeNativeTargetAsmPrinter();
1242 InitializeNativeTargetAsmParser();
1244 // Install standard binary operators.
1245 // 1 is lowest precedence.
1246 BinopPrecedence
['='] = 2;
1247 BinopPrecedence
['<'] = 10;
1248 BinopPrecedence
['+'] = 20;
1249 BinopPrecedence
['-'] = 20;
1250 BinopPrecedence
['*'] = 40; // highest.
1252 // Prime the first token.
1253 fprintf(stderr
, "ready> ");
1256 TheJIT
= std::make_unique
<KaleidoscopeJIT
>();
1258 InitializeModuleAndPassManager();
1260 // Run the main "interpreter loop" now.