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"
32 using namespace llvm::orc
;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
39 // of these for known things.
59 static std::string IdentifierStr
; // Filled in if tok_identifier
60 static double NumVal
; // Filled in if tok_number
62 /// gettok - Return the next token from standard input.
64 static int LastChar
= ' ';
66 // Skip any whitespace.
67 while (isspace(LastChar
))
70 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
71 IdentifierStr
= LastChar
;
72 while (isalnum((LastChar
= getchar())))
73 IdentifierStr
+= LastChar
;
75 if (IdentifierStr
== "def")
77 if (IdentifierStr
== "extern")
79 if (IdentifierStr
== "if")
81 if (IdentifierStr
== "then")
83 if (IdentifierStr
== "else")
85 if (IdentifierStr
== "for")
87 if (IdentifierStr
== "in")
89 return tok_identifier
;
92 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
97 } while (isdigit(LastChar
) || LastChar
== '.');
99 NumVal
= strtod(NumStr
.c_str(), nullptr);
103 if (LastChar
== '#') {
104 // Comment until end of line.
106 LastChar
= getchar();
107 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
113 // Check for end of file. Don't eat the EOF.
117 // Otherwise, just return the character as its ascii value.
118 int ThisChar
= LastChar
;
119 LastChar
= getchar();
123 //===----------------------------------------------------------------------===//
124 // Abstract Syntax Tree (aka Parse Tree)
125 //===----------------------------------------------------------------------===//
129 /// ExprAST - Base class for all expression nodes.
132 virtual ~ExprAST() = default;
134 virtual Value
*codegen() = 0;
137 /// NumberExprAST - Expression class for numeric literals like "1.0".
138 class NumberExprAST
: public ExprAST
{
142 NumberExprAST(double Val
) : Val(Val
) {}
144 Value
*codegen() override
;
147 /// VariableExprAST - Expression class for referencing a variable, like "a".
148 class VariableExprAST
: public ExprAST
{
152 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
154 Value
*codegen() override
;
157 /// BinaryExprAST - Expression class for a binary operator.
158 class BinaryExprAST
: public ExprAST
{
160 std::unique_ptr
<ExprAST
> LHS
, RHS
;
163 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
164 std::unique_ptr
<ExprAST
> RHS
)
165 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
167 Value
*codegen() override
;
170 /// CallExprAST - Expression class for function calls.
171 class CallExprAST
: public ExprAST
{
173 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
176 CallExprAST(const std::string
&Callee
,
177 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
178 : Callee(Callee
), Args(std::move(Args
)) {}
180 Value
*codegen() override
;
183 /// IfExprAST - Expression class for if/then/else.
184 class IfExprAST
: public ExprAST
{
185 std::unique_ptr
<ExprAST
> Cond
, Then
, Else
;
188 IfExprAST(std::unique_ptr
<ExprAST
> Cond
, std::unique_ptr
<ExprAST
> Then
,
189 std::unique_ptr
<ExprAST
> Else
)
190 : Cond(std::move(Cond
)), Then(std::move(Then
)), Else(std::move(Else
)) {}
192 Value
*codegen() override
;
195 /// ForExprAST - Expression class for for/in.
196 class ForExprAST
: public ExprAST
{
198 std::unique_ptr
<ExprAST
> Start
, End
, Step
, Body
;
201 ForExprAST(const std::string
&VarName
, std::unique_ptr
<ExprAST
> Start
,
202 std::unique_ptr
<ExprAST
> End
, std::unique_ptr
<ExprAST
> Step
,
203 std::unique_ptr
<ExprAST
> Body
)
204 : VarName(VarName
), Start(std::move(Start
)), End(std::move(End
)),
205 Step(std::move(Step
)), Body(std::move(Body
)) {}
207 Value
*codegen() override
;
210 /// PrototypeAST - This class represents the "prototype" for a function,
211 /// which captures its name, and its argument names (thus implicitly the number
212 /// of arguments the function takes).
215 std::vector
<std::string
> Args
;
218 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
)
219 : Name(Name
), Args(std::move(Args
)) {}
222 const std::string
&getName() const { return Name
; }
225 /// FunctionAST - This class represents a function definition itself.
227 std::unique_ptr
<PrototypeAST
> Proto
;
228 std::unique_ptr
<ExprAST
> Body
;
231 FunctionAST(std::unique_ptr
<PrototypeAST
> Proto
,
232 std::unique_ptr
<ExprAST
> Body
)
233 : Proto(std::move(Proto
)), Body(std::move(Body
)) {}
238 } // end anonymous namespace
240 //===----------------------------------------------------------------------===//
242 //===----------------------------------------------------------------------===//
244 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
245 /// token the parser is looking at. getNextToken reads another token from the
246 /// lexer and updates CurTok with its results.
248 static int getNextToken() { return CurTok
= gettok(); }
250 /// BinopPrecedence - This holds the precedence for each binary operator that is
252 static std::map
<char, int> BinopPrecedence
;
254 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
255 static int GetTokPrecedence() {
256 if (!isascii(CurTok
))
259 // Make sure it's a declared binop.
260 int TokPrec
= BinopPrecedence
[CurTok
];
266 /// LogError* - These are little helper functions for error handling.
267 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
268 fprintf(stderr
, "Error: %s\n", Str
);
272 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
277 static std::unique_ptr
<ExprAST
> ParseExpression();
279 /// numberexpr ::= number
280 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
281 auto Result
= llvm::make_unique
<NumberExprAST
>(NumVal
);
282 getNextToken(); // consume the number
283 return std::move(Result
);
286 /// parenexpr ::= '(' expression ')'
287 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
288 getNextToken(); // eat (.
289 auto V
= ParseExpression();
294 return LogError("expected ')'");
295 getNextToken(); // eat ).
301 /// ::= identifier '(' expression* ')'
302 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
303 std::string IdName
= IdentifierStr
;
305 getNextToken(); // eat identifier.
307 if (CurTok
!= '(') // Simple variable ref.
308 return llvm::make_unique
<VariableExprAST
>(IdName
);
311 getNextToken(); // eat (
312 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
315 if (auto Arg
= ParseExpression())
316 Args
.push_back(std::move(Arg
));
324 return LogError("Expected ')' or ',' in argument list");
332 return llvm::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
335 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
336 static std::unique_ptr
<ExprAST
> ParseIfExpr() {
337 getNextToken(); // eat the if.
340 auto Cond
= ParseExpression();
344 if (CurTok
!= tok_then
)
345 return LogError("expected then");
346 getNextToken(); // eat the then
348 auto Then
= ParseExpression();
352 if (CurTok
!= tok_else
)
353 return LogError("expected else");
357 auto Else
= ParseExpression();
361 return llvm::make_unique
<IfExprAST
>(std::move(Cond
), std::move(Then
),
365 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
366 static std::unique_ptr
<ExprAST
> ParseForExpr() {
367 getNextToken(); // eat the for.
369 if (CurTok
!= tok_identifier
)
370 return LogError("expected identifier after for");
372 std::string IdName
= IdentifierStr
;
373 getNextToken(); // eat identifier.
376 return LogError("expected '=' after for");
377 getNextToken(); // eat '='.
379 auto Start
= ParseExpression();
383 return LogError("expected ',' after for start value");
386 auto End
= ParseExpression();
390 // The step value is optional.
391 std::unique_ptr
<ExprAST
> Step
;
394 Step
= ParseExpression();
399 if (CurTok
!= tok_in
)
400 return LogError("expected 'in' after for");
401 getNextToken(); // eat 'in'.
403 auto Body
= ParseExpression();
407 return llvm::make_unique
<ForExprAST
>(IdName
, std::move(Start
), std::move(End
),
408 std::move(Step
), std::move(Body
));
412 /// ::= identifierexpr
417 static std::unique_ptr
<ExprAST
> ParsePrimary() {
420 return LogError("unknown token when expecting an expression");
422 return ParseIdentifierExpr();
424 return ParseNumberExpr();
426 return ParseParenExpr();
428 return ParseIfExpr();
430 return ParseForExpr();
435 /// ::= ('+' primary)*
436 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
437 std::unique_ptr
<ExprAST
> LHS
) {
438 // If this is a binop, find its precedence.
440 int TokPrec
= GetTokPrecedence();
442 // If this is a binop that binds at least as tightly as the current binop,
443 // consume it, otherwise we are done.
444 if (TokPrec
< ExprPrec
)
447 // Okay, we know this is a binop.
449 getNextToken(); // eat binop
451 // Parse the primary expression after the binary operator.
452 auto RHS
= ParsePrimary();
456 // If BinOp binds less tightly with RHS than the operator after RHS, let
457 // the pending operator take RHS as its LHS.
458 int NextPrec
= GetTokPrecedence();
459 if (TokPrec
< NextPrec
) {
460 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
467 llvm::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
), std::move(RHS
));
472 /// ::= primary binoprhs
474 static std::unique_ptr
<ExprAST
> ParseExpression() {
475 auto LHS
= ParsePrimary();
479 return ParseBinOpRHS(0, std::move(LHS
));
483 /// ::= id '(' id* ')'
484 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
485 if (CurTok
!= tok_identifier
)
486 return LogErrorP("Expected function name in prototype");
488 std::string FnName
= IdentifierStr
;
492 return LogErrorP("Expected '(' in prototype");
494 std::vector
<std::string
> ArgNames
;
495 while (getNextToken() == tok_identifier
)
496 ArgNames
.push_back(IdentifierStr
);
498 return LogErrorP("Expected ')' in prototype");
501 getNextToken(); // eat ')'.
503 return llvm::make_unique
<PrototypeAST
>(FnName
, std::move(ArgNames
));
506 /// definition ::= 'def' prototype expression
507 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
508 getNextToken(); // eat def.
509 auto Proto
= ParsePrototype();
513 if (auto E
= ParseExpression())
514 return llvm::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
518 /// toplevelexpr ::= expression
519 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
520 if (auto E
= ParseExpression()) {
521 // Make an anonymous proto.
522 auto Proto
= llvm::make_unique
<PrototypeAST
>("__anon_expr",
523 std::vector
<std::string
>());
524 return llvm::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
529 /// external ::= 'extern' prototype
530 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
531 getNextToken(); // eat extern.
532 return ParsePrototype();
535 //===----------------------------------------------------------------------===//
537 //===----------------------------------------------------------------------===//
539 static LLVMContext TheContext
;
540 static IRBuilder
<> Builder(TheContext
);
541 static std::unique_ptr
<Module
> TheModule
;
542 static std::map
<std::string
, Value
*> NamedValues
;
543 static std::unique_ptr
<legacy::FunctionPassManager
> TheFPM
;
544 static std::unique_ptr
<KaleidoscopeJIT
> TheJIT
;
545 static std::map
<std::string
, std::unique_ptr
<PrototypeAST
>> FunctionProtos
;
547 Value
*LogErrorV(const char *Str
) {
552 Function
*getFunction(std::string Name
) {
553 // First, see if the function has already been added to the current module.
554 if (auto *F
= TheModule
->getFunction(Name
))
557 // If not, check whether we can codegen the declaration from some existing
559 auto FI
= FunctionProtos
.find(Name
);
560 if (FI
!= FunctionProtos
.end())
561 return FI
->second
->codegen();
563 // If no existing prototype exists, return null.
567 Value
*NumberExprAST::codegen() {
568 return ConstantFP::get(TheContext
, APFloat(Val
));
571 Value
*VariableExprAST::codegen() {
572 // Look this variable up in the function.
573 Value
*V
= NamedValues
[Name
];
575 return LogErrorV("Unknown variable name");
579 Value
*BinaryExprAST::codegen() {
580 Value
*L
= LHS
->codegen();
581 Value
*R
= RHS
->codegen();
587 return Builder
.CreateFAdd(L
, R
, "addtmp");
589 return Builder
.CreateFSub(L
, R
, "subtmp");
591 return Builder
.CreateFMul(L
, R
, "multmp");
593 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
594 // Convert bool 0/1 to double 0.0 or 1.0
595 return Builder
.CreateUIToFP(L
, Type::getDoubleTy(TheContext
), "booltmp");
597 return LogErrorV("invalid binary operator");
601 Value
*CallExprAST::codegen() {
602 // Look up the name in the global module table.
603 Function
*CalleeF
= getFunction(Callee
);
605 return LogErrorV("Unknown function referenced");
607 // If argument mismatch error.
608 if (CalleeF
->arg_size() != Args
.size())
609 return LogErrorV("Incorrect # arguments passed");
611 std::vector
<Value
*> ArgsV
;
612 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
613 ArgsV
.push_back(Args
[i
]->codegen());
618 return Builder
.CreateCall(CalleeF
, ArgsV
, "calltmp");
621 Value
*IfExprAST::codegen() {
622 Value
*CondV
= Cond
->codegen();
626 // Convert condition to a bool by comparing non-equal to 0.0.
627 CondV
= Builder
.CreateFCmpONE(
628 CondV
, ConstantFP::get(TheContext
, APFloat(0.0)), "ifcond");
630 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
632 // Create blocks for the then and else cases. Insert the 'then' block at the
633 // end of the function.
634 BasicBlock
*ThenBB
= BasicBlock::Create(TheContext
, "then", TheFunction
);
635 BasicBlock
*ElseBB
= BasicBlock::Create(TheContext
, "else");
636 BasicBlock
*MergeBB
= BasicBlock::Create(TheContext
, "ifcont");
638 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
641 Builder
.SetInsertPoint(ThenBB
);
643 Value
*ThenV
= Then
->codegen();
647 Builder
.CreateBr(MergeBB
);
648 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
649 ThenBB
= Builder
.GetInsertBlock();
652 TheFunction
->getBasicBlockList().push_back(ElseBB
);
653 Builder
.SetInsertPoint(ElseBB
);
655 Value
*ElseV
= Else
->codegen();
659 Builder
.CreateBr(MergeBB
);
660 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
661 ElseBB
= Builder
.GetInsertBlock();
664 TheFunction
->getBasicBlockList().push_back(MergeBB
);
665 Builder
.SetInsertPoint(MergeBB
);
666 PHINode
*PN
= Builder
.CreatePHI(Type::getDoubleTy(TheContext
), 2, "iftmp");
668 PN
->addIncoming(ThenV
, ThenBB
);
669 PN
->addIncoming(ElseV
, ElseBB
);
673 // Output for-loop as:
678 // variable = phi [start, loopheader], [nextvariable, loopend]
684 // nextvariable = variable + step
686 // br endcond, loop, endloop
688 Value
*ForExprAST::codegen() {
689 // Emit the start code first, without 'variable' in scope.
690 Value
*StartVal
= Start
->codegen();
694 // Make the new basic block for the loop header, inserting after current
696 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
697 BasicBlock
*PreheaderBB
= Builder
.GetInsertBlock();
698 BasicBlock
*LoopBB
= BasicBlock::Create(TheContext
, "loop", TheFunction
);
700 // Insert an explicit fall through from the current block to the LoopBB.
701 Builder
.CreateBr(LoopBB
);
703 // Start insertion in LoopBB.
704 Builder
.SetInsertPoint(LoopBB
);
706 // Start the PHI node with an entry for Start.
708 Builder
.CreatePHI(Type::getDoubleTy(TheContext
), 2, VarName
);
709 Variable
->addIncoming(StartVal
, PreheaderBB
);
711 // Within the loop, the variable is defined equal to the PHI node. If it
712 // shadows an existing variable, we have to restore it, so save it now.
713 Value
*OldVal
= NamedValues
[VarName
];
714 NamedValues
[VarName
] = Variable
;
716 // Emit the body of the loop. This, like any other expr, can change the
717 // current BB. Note that we ignore the value computed by the body, but don't
719 if (!Body
->codegen())
722 // Emit the step value.
723 Value
*StepVal
= nullptr;
725 StepVal
= Step
->codegen();
729 // If not specified, use 1.0.
730 StepVal
= ConstantFP::get(TheContext
, APFloat(1.0));
733 Value
*NextVar
= Builder
.CreateFAdd(Variable
, StepVal
, "nextvar");
735 // Compute the end condition.
736 Value
*EndCond
= End
->codegen();
740 // Convert condition to a bool by comparing non-equal to 0.0.
741 EndCond
= Builder
.CreateFCmpONE(
742 EndCond
, ConstantFP::get(TheContext
, APFloat(0.0)), "loopcond");
744 // Create the "after loop" block and insert it.
745 BasicBlock
*LoopEndBB
= Builder
.GetInsertBlock();
746 BasicBlock
*AfterBB
=
747 BasicBlock::Create(TheContext
, "afterloop", TheFunction
);
749 // Insert the conditional branch into the end of LoopEndBB.
750 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
752 // Any new code will be inserted in AfterBB.
753 Builder
.SetInsertPoint(AfterBB
);
755 // Add a new entry to the PHI node for the backedge.
756 Variable
->addIncoming(NextVar
, LoopEndBB
);
758 // Restore the unshadowed variable.
760 NamedValues
[VarName
] = OldVal
;
762 NamedValues
.erase(VarName
);
764 // for expr always returns 0.0.
765 return Constant::getNullValue(Type::getDoubleTy(TheContext
));
768 Function
*PrototypeAST::codegen() {
769 // Make the function type: double(double,double) etc.
770 std::vector
<Type
*> Doubles(Args
.size(), Type::getDoubleTy(TheContext
));
772 FunctionType::get(Type::getDoubleTy(TheContext
), Doubles
, false);
775 Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
.get());
777 // Set names for all arguments.
779 for (auto &Arg
: F
->args())
780 Arg
.setName(Args
[Idx
++]);
785 Function
*FunctionAST::codegen() {
786 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
787 // reference to it for use below.
789 FunctionProtos
[Proto
->getName()] = std::move(Proto
);
790 Function
*TheFunction
= getFunction(P
.getName());
794 // Create a new basic block to start insertion into.
795 BasicBlock
*BB
= BasicBlock::Create(TheContext
, "entry", TheFunction
);
796 Builder
.SetInsertPoint(BB
);
798 // Record the function arguments in the NamedValues map.
800 for (auto &Arg
: TheFunction
->args())
801 NamedValues
[Arg
.getName()] = &Arg
;
803 if (Value
*RetVal
= Body
->codegen()) {
804 // Finish off the function.
805 Builder
.CreateRet(RetVal
);
807 // Validate the generated code, checking for consistency.
808 verifyFunction(*TheFunction
);
810 // Run the optimizer on the function.
811 TheFPM
->run(*TheFunction
);
816 // Error reading body, remove function.
817 TheFunction
->eraseFromParent();
821 //===----------------------------------------------------------------------===//
822 // Top-Level parsing and JIT Driver
823 //===----------------------------------------------------------------------===//
825 static void InitializeModuleAndPassManager() {
826 // Open a new module.
827 TheModule
= llvm::make_unique
<Module
>("my cool jit", TheContext
);
828 TheModule
->setDataLayout(TheJIT
->getTargetMachine().createDataLayout());
830 // Create a new pass manager attached to it.
831 TheFPM
= llvm::make_unique
<legacy::FunctionPassManager
>(TheModule
.get());
833 // Do simple "peephole" optimizations and bit-twiddling optzns.
834 TheFPM
->add(createInstructionCombiningPass());
835 // Reassociate expressions.
836 TheFPM
->add(createReassociatePass());
837 // Eliminate Common SubExpressions.
838 TheFPM
->add(createGVNPass());
839 // Simplify the control flow graph (deleting unreachable blocks, etc).
840 TheFPM
->add(createCFGSimplificationPass());
842 TheFPM
->doInitialization();
845 static void HandleDefinition() {
846 if (auto FnAST
= ParseDefinition()) {
847 if (auto *FnIR
= FnAST
->codegen()) {
848 fprintf(stderr
, "Read function definition:");
850 fprintf(stderr
, "\n");
851 TheJIT
->addModule(std::move(TheModule
));
852 InitializeModuleAndPassManager();
855 // Skip token for error recovery.
860 static void HandleExtern() {
861 if (auto ProtoAST
= ParseExtern()) {
862 if (auto *FnIR
= ProtoAST
->codegen()) {
863 fprintf(stderr
, "Read extern: ");
865 fprintf(stderr
, "\n");
866 FunctionProtos
[ProtoAST
->getName()] = std::move(ProtoAST
);
869 // Skip token for error recovery.
874 static void HandleTopLevelExpression() {
875 // Evaluate a top-level expression into an anonymous function.
876 if (auto FnAST
= ParseTopLevelExpr()) {
877 if (FnAST
->codegen()) {
878 // JIT the module containing the anonymous expression, keeping a handle so
879 // we can free it later.
880 auto H
= TheJIT
->addModule(std::move(TheModule
));
881 InitializeModuleAndPassManager();
883 // Search the JIT for the __anon_expr symbol.
884 auto ExprSymbol
= TheJIT
->findSymbol("__anon_expr");
885 assert(ExprSymbol
&& "Function not found");
887 // Get the symbol's address and cast it to the right type (takes no
888 // arguments, returns a double) so we can call it as a native function.
889 double (*FP
)() = (double (*)())(intptr_t)cantFail(ExprSymbol
.getAddress());
890 fprintf(stderr
, "Evaluated to %f\n", FP());
892 // Delete the anonymous expression module from the JIT.
893 TheJIT
->removeModule(H
);
896 // Skip token for error recovery.
901 /// top ::= definition | external | expression | ';'
902 static void MainLoop() {
904 fprintf(stderr
, "ready> ");
908 case ';': // ignore top-level semicolons.
918 HandleTopLevelExpression();
924 //===----------------------------------------------------------------------===//
925 // "Library" functions that can be "extern'd" from user code.
926 //===----------------------------------------------------------------------===//
929 #define DLLEXPORT __declspec(dllexport)
934 /// putchard - putchar that takes a double and returns 0.
935 extern "C" DLLEXPORT
double putchard(double X
) {
936 fputc((char)X
, stderr
);
940 /// printd - printf that takes a double prints it as "%f\n", returning 0.
941 extern "C" DLLEXPORT
double printd(double X
) {
942 fprintf(stderr
, "%f\n", X
);
946 //===----------------------------------------------------------------------===//
948 //===----------------------------------------------------------------------===//
951 InitializeNativeTarget();
952 InitializeNativeTargetAsmPrinter();
953 InitializeNativeTargetAsmParser();
955 // Install standard binary operators.
956 // 1 is lowest precedence.
957 BinopPrecedence
['<'] = 10;
958 BinopPrecedence
['+'] = 20;
959 BinopPrecedence
['-'] = 20;
960 BinopPrecedence
['*'] = 40; // highest.
962 // Prime the first token.
963 fprintf(stderr
, "ready> ");
966 TheJIT
= llvm::make_unique
<KaleidoscopeJIT
>();
968 InitializeModuleAndPassManager();
970 // Run the main "interpreter loop" now.