1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/Passes.h"
3 #include "llvm/IR/IRBuilder.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/LegacyPassManager.h"
6 #include "llvm/IR/Module.h"
7 #include "llvm/IR/Verifier.h"
8 #include "llvm/Support/TargetSelect.h"
9 #include "llvm/Transforms/Scalar.h"
15 #include "../include/KaleidoscopeJIT.h"
18 using namespace llvm::orc;
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
49 static std::string IdentifierStr; // Filled in if tok_identifier
50 static double NumVal; // Filled in if tok_number
52 /// gettok - Return the next token from standard input.
54 static int LastChar = ' ';
56 // Skip any whitespace.
57 while (isspace(LastChar))
60 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
61 IdentifierStr = LastChar;
62 while (isalnum((LastChar = getchar())))
63 IdentifierStr += LastChar;
65 if (IdentifierStr == "def")
67 if (IdentifierStr == "extern")
69 if (IdentifierStr == "if")
71 if (IdentifierStr == "then")
73 if (IdentifierStr == "else")
75 if (IdentifierStr == "for")
77 if (IdentifierStr == "in")
79 if (IdentifierStr == "binary")
81 if (IdentifierStr == "unary")
83 return tok_identifier;
86 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
91 } while (isdigit(LastChar) || LastChar == '.');
93 NumVal = strtod(NumStr.c_str(), 0);
97 if (LastChar == '#') {
98 // Comment until end of line.
100 LastChar = getchar();
101 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
107 // Check for end of file. Don't eat the EOF.
111 // Otherwise, just return the character as its ascii value.
112 int ThisChar = LastChar;
113 LastChar = getchar();
117 //===----------------------------------------------------------------------===//
118 // Abstract Syntax Tree (aka Parse Tree)
119 //===----------------------------------------------------------------------===//
121 /// ExprAST - Base class for all expression nodes.
124 virtual ~ExprAST() {}
125 virtual Value *codegen() = 0;
128 /// NumberExprAST - Expression class for numeric literals like "1.0".
129 class NumberExprAST : public ExprAST {
133 NumberExprAST(double Val) : Val(Val) {}
134 Value *codegen() override;
137 /// VariableExprAST - Expression class for referencing a variable, like "a".
138 class VariableExprAST : public ExprAST {
142 VariableExprAST(const std::string &Name) : Name(Name) {}
143 Value *codegen() override;
146 /// UnaryExprAST - Expression class for a unary operator.
147 class UnaryExprAST : public ExprAST {
149 std::unique_ptr<ExprAST> Operand;
152 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
153 : Opcode(Opcode), Operand(std::move(Operand)) {}
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)) {}
166 Value *codegen() override;
169 /// CallExprAST - Expression class for function calls.
170 class CallExprAST : public ExprAST {
172 std::vector<std::unique_ptr<ExprAST>> Args;
175 CallExprAST(const std::string &Callee,
176 std::vector<std::unique_ptr<ExprAST>> Args)
177 : Callee(Callee), Args(std::move(Args)) {}
178 Value *codegen() override;
181 /// IfExprAST - Expression class for if/then/else.
182 class IfExprAST : public ExprAST {
183 std::unique_ptr<ExprAST> Cond, Then, Else;
186 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
187 std::unique_ptr<ExprAST> Else)
188 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
189 Value *codegen() override;
192 /// ForExprAST - Expression class for for/in.
193 class ForExprAST : public ExprAST {
195 std::unique_ptr<ExprAST> Start, End, Step, Body;
198 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
199 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
200 std::unique_ptr<ExprAST> Body)
201 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
202 Step(std::move(Step)), Body(std::move(Body)) {}
203 Value *codegen() override;
206 /// PrototypeAST - This class represents the "prototype" for a function,
207 /// which captures its name, and its argument names (thus implicitly the number
208 /// of arguments the function takes), as well as if it is an operator.
211 std::vector<std::string> Args;
213 unsigned Precedence; // Precedence if a binary op.
216 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
217 bool IsOperator = false, unsigned Prec = 0)
218 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
221 const std::string &getName() const { return Name; }
223 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
224 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
226 char getOperatorName() const {
227 assert(isUnaryOp() || isBinaryOp());
228 return Name[Name.size() - 1];
231 unsigned getBinaryPrecedence() const { return Precedence; }
234 /// FunctionAST - This class represents a function definition itself.
236 std::unique_ptr<PrototypeAST> Proto;
237 std::unique_ptr<ExprAST> Body;
240 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
241 std::unique_ptr<ExprAST> Body)
242 : Proto(std::move(Proto)), Body(std::move(Body)) {}
245 } // end anonymous namespace
247 //===----------------------------------------------------------------------===//
249 //===----------------------------------------------------------------------===//
251 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
252 /// token the parser is looking at. getNextToken reads another token from the
253 /// lexer and updates CurTok with its results.
255 static int getNextToken() { return CurTok = gettok(); }
257 /// BinopPrecedence - This holds the precedence for each binary operator that is
259 static std::map<char, int> BinopPrecedence;
261 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
262 static int GetTokPrecedence() {
263 if (!isascii(CurTok))
266 // Make sure it's a declared binop.
267 int TokPrec = BinopPrecedence[CurTok];
273 /// Error* - These are little helper functions for error handling.
274 std::unique_ptr<ExprAST> Error(const char *Str) {
275 fprintf(stderr, "Error: %s\n", Str);
278 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
283 static std::unique_ptr<ExprAST> ParseExpression();
285 /// numberexpr ::= number
286 static std::unique_ptr<ExprAST> ParseNumberExpr() {
287 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
288 getNextToken(); // consume the number
289 return std::move(Result);
292 /// parenexpr ::= '(' expression ')'
293 static std::unique_ptr<ExprAST> ParseParenExpr() {
294 getNextToken(); // eat (.
295 auto V = ParseExpression();
300 return Error("expected ')'");
301 getNextToken(); // eat ).
307 /// ::= identifier '(' expression* ')'
308 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
309 std::string IdName = IdentifierStr;
311 getNextToken(); // eat identifier.
313 if (CurTok != '(') // Simple variable ref.
314 return llvm::make_unique<VariableExprAST>(IdName);
317 getNextToken(); // eat (
318 std::vector<std::unique_ptr<ExprAST>> Args;
321 if (auto Arg = ParseExpression())
322 Args.push_back(std::move(Arg));
330 return Error("Expected ')' or ',' in argument list");
338 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
341 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
342 static std::unique_ptr<ExprAST> ParseIfExpr() {
343 getNextToken(); // eat the if.
346 auto Cond = ParseExpression();
350 if (CurTok != tok_then)
351 return Error("expected then");
352 getNextToken(); // eat the then
354 auto Then = ParseExpression();
358 if (CurTok != tok_else)
359 return Error("expected else");
363 auto Else = ParseExpression();
367 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
371 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
372 static std::unique_ptr<ExprAST> ParseForExpr() {
373 getNextToken(); // eat the for.
375 if (CurTok != tok_identifier)
376 return Error("expected identifier after for");
378 std::string IdName = IdentifierStr;
379 getNextToken(); // eat identifier.
382 return Error("expected '=' after for");
383 getNextToken(); // eat '='.
385 auto Start = ParseExpression();
389 return Error("expected ',' after for start value");
392 auto End = ParseExpression();
396 // The step value is optional.
397 std::unique_ptr<ExprAST> Step;
400 Step = ParseExpression();
405 if (CurTok != tok_in)
406 return Error("expected 'in' after for");
407 getNextToken(); // eat 'in'.
409 auto Body = ParseExpression();
413 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
414 std::move(Step), std::move(Body));
418 /// ::= identifierexpr
423 static std::unique_ptr<ExprAST> ParsePrimary() {
426 return Error("unknown token when expecting an expression");
428 return ParseIdentifierExpr();
430 return ParseNumberExpr();
432 return ParseParenExpr();
434 return ParseIfExpr();
436 return ParseForExpr();
443 static std::unique_ptr<ExprAST> ParseUnary() {
444 // If the current token is not an operator, it must be a primary expr.
445 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
446 return ParsePrimary();
448 // If this is a unary operator, read it.
451 if (auto Operand = ParseUnary())
452 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
458 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
459 std::unique_ptr<ExprAST> LHS) {
460 // If this is a binop, find its precedence.
462 int TokPrec = GetTokPrecedence();
464 // If this is a binop that binds at least as tightly as the current binop,
465 // consume it, otherwise we are done.
466 if (TokPrec < ExprPrec)
469 // Okay, we know this is a binop.
471 getNextToken(); // eat binop
473 // Parse the unary expression after the binary operator.
474 auto RHS = ParseUnary();
478 // If BinOp binds less tightly with RHS than the operator after RHS, let
479 // the pending operator take RHS as its LHS.
480 int NextPrec = GetTokPrecedence();
481 if (TokPrec < NextPrec) {
482 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
489 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
494 /// ::= unary binoprhs
496 static std::unique_ptr<ExprAST> ParseExpression() {
497 auto LHS = ParseUnary();
501 return ParseBinOpRHS(0, std::move(LHS));
505 /// ::= id '(' id* ')'
506 /// ::= binary LETTER number? (id, id)
507 /// ::= unary LETTER (id)
508 static std::unique_ptr<PrototypeAST> ParsePrototype() {
511 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
512 unsigned BinaryPrecedence = 30;
516 return ErrorP("Expected function name in prototype");
518 FnName = IdentifierStr;
524 if (!isascii(CurTok))
525 return ErrorP("Expected unary operator");
527 FnName += (char)CurTok;
533 if (!isascii(CurTok))
534 return ErrorP("Expected binary operator");
536 FnName += (char)CurTok;
540 // Read the precedence if present.
541 if (CurTok == tok_number) {
542 if (NumVal < 1 || NumVal > 100)
543 return ErrorP("Invalid precedecnce: must be 1..100");
544 BinaryPrecedence = (unsigned)NumVal;
551 return ErrorP("Expected '(' in prototype");
553 std::vector<std::string> ArgNames;
554 while (getNextToken() == tok_identifier)
555 ArgNames.push_back(IdentifierStr);
557 return ErrorP("Expected ')' in prototype");
560 getNextToken(); // eat ')'.
562 // Verify right number of names for operator.
563 if (Kind && ArgNames.size() != Kind)
564 return ErrorP("Invalid number of operands for operator");
566 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
570 /// definition ::= 'def' prototype expression
571 static std::unique_ptr<FunctionAST> ParseDefinition() {
572 getNextToken(); // eat def.
573 auto Proto = ParsePrototype();
577 if (auto E = ParseExpression())
578 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
582 /// toplevelexpr ::= expression
583 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
584 if (auto E = ParseExpression()) {
585 // Make an anonymous proto.
586 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
587 std::vector<std::string>());
588 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
593 /// external ::= 'extern' prototype
594 static std::unique_ptr<PrototypeAST> ParseExtern() {
595 getNextToken(); // eat extern.
596 return ParsePrototype();
599 //===----------------------------------------------------------------------===//
601 //===----------------------------------------------------------------------===//
603 static std::unique_ptr<Module> TheModule;
604 static IRBuilder<> Builder(getGlobalContext());
605 static std::map<std::string, Value *> NamedValues;
606 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
607 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
608 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
610 Value *ErrorV(const char *Str) {
615 Function *getFunction(std::string Name) {
616 // First, see if the function has already been added to the current module.
617 if (auto *F = TheModule->getFunction(Name))
620 // If not, check whether we can codegen the declaration from some existing
622 auto FI = FunctionProtos.find(Name);
623 if (FI != FunctionProtos.end())
624 return FI->second->codegen();
626 // If no existing prototype exists, return null.
630 Value *NumberExprAST::codegen() {
631 return ConstantFP::get(getGlobalContext(), APFloat(Val));
634 Value *VariableExprAST::codegen() {
635 // Look this variable up in the function.
636 Value *V = NamedValues[Name];
638 return ErrorV("Unknown variable name");
642 Value *UnaryExprAST::codegen() {
643 Value *OperandV = Operand->codegen();
647 Function *F = getFunction(std::string("unary") + Opcode);
649 return ErrorV("Unknown unary operator");
651 return Builder.CreateCall(F, OperandV, "unop");
654 Value *BinaryExprAST::codegen() {
655 Value *L = LHS->codegen();
656 Value *R = RHS->codegen();
662 return Builder.CreateFAdd(L, R, "addtmp");
664 return Builder.CreateFSub(L, R, "subtmp");
666 return Builder.CreateFMul(L, R, "multmp");
668 L = Builder.CreateFCmpULT(L, R, "cmptmp");
669 // Convert bool 0/1 to double 0.0 or 1.0
670 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
676 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
678 Function *F = getFunction(std::string("binary") + Op);
679 assert(F && "binary operator not found!");
681 Value *Ops[] = {L, R};
682 return Builder.CreateCall(F, Ops, "binop");
685 Value *CallExprAST::codegen() {
686 // Look up the name in the global module table.
687 Function *CalleeF = getFunction(Callee);
689 return ErrorV("Unknown function referenced");
691 // If argument mismatch error.
692 if (CalleeF->arg_size() != Args.size())
693 return ErrorV("Incorrect # arguments passed");
695 std::vector<Value *> ArgsV;
696 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
697 ArgsV.push_back(Args[i]->codegen());
702 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
705 Value *IfExprAST::codegen() {
706 Value *CondV = Cond->codegen();
710 // Convert condition to a bool by comparing equal to 0.0.
711 CondV = Builder.CreateFCmpONE(
712 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
714 Function *TheFunction = Builder.GetInsertBlock()->getParent();
716 // Create blocks for the then and else cases. Insert the 'then' block at the
717 // end of the function.
719 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
720 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
721 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
723 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
726 Builder.SetInsertPoint(ThenBB);
728 Value *ThenV = Then->codegen();
732 Builder.CreateBr(MergeBB);
733 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
734 ThenBB = Builder.GetInsertBlock();
737 TheFunction->getBasicBlockList().push_back(ElseBB);
738 Builder.SetInsertPoint(ElseBB);
740 Value *ElseV = Else->codegen();
744 Builder.CreateBr(MergeBB);
745 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
746 ElseBB = Builder.GetInsertBlock();
749 TheFunction->getBasicBlockList().push_back(MergeBB);
750 Builder.SetInsertPoint(MergeBB);
752 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
754 PN->addIncoming(ThenV, ThenBB);
755 PN->addIncoming(ElseV, ElseBB);
759 // Output for-loop as:
764 // variable = phi [start, loopheader], [nextvariable, loopend]
770 // nextvariable = variable + step
772 // br endcond, loop, endloop
774 Value *ForExprAST::codegen() {
775 // Emit the start code first, without 'variable' in scope.
776 Value *StartVal = Start->codegen();
780 // Make the new basic block for the loop header, inserting after current
782 Function *TheFunction = Builder.GetInsertBlock()->getParent();
783 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
785 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
787 // Insert an explicit fall through from the current block to the LoopBB.
788 Builder.CreateBr(LoopBB);
790 // Start insertion in LoopBB.
791 Builder.SetInsertPoint(LoopBB);
793 // Start the PHI node with an entry for Start.
794 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
796 Variable->addIncoming(StartVal, PreheaderBB);
798 // Within the loop, the variable is defined equal to the PHI node. If it
799 // shadows an existing variable, we have to restore it, so save it now.
800 Value *OldVal = NamedValues[VarName];
801 NamedValues[VarName] = Variable;
803 // Emit the body of the loop. This, like any other expr, can change the
804 // current BB. Note that we ignore the value computed by the body, but don't
806 if (!Body->codegen())
809 // Emit the step value.
810 Value *StepVal = nullptr;
812 StepVal = Step->codegen();
816 // If not specified, use 1.0.
817 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
820 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
822 // Compute the end condition.
823 Value *EndCond = End->codegen();
827 // Convert condition to a bool by comparing equal to 0.0.
828 EndCond = Builder.CreateFCmpONE(
829 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
831 // Create the "after loop" block and insert it.
832 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
833 BasicBlock *AfterBB =
834 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
836 // Insert the conditional branch into the end of LoopEndBB.
837 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
839 // Any new code will be inserted in AfterBB.
840 Builder.SetInsertPoint(AfterBB);
842 // Add a new entry to the PHI node for the backedge.
843 Variable->addIncoming(NextVar, LoopEndBB);
845 // Restore the unshadowed variable.
847 NamedValues[VarName] = OldVal;
849 NamedValues.erase(VarName);
851 // for expr always returns 0.0.
852 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
855 Function *PrototypeAST::codegen() {
856 // Make the function type: double(double,double) etc.
857 std::vector<Type *> Doubles(Args.size(),
858 Type::getDoubleTy(getGlobalContext()));
860 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
863 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
865 // Set names for all arguments.
867 for (auto &Arg : F->args())
868 Arg.setName(Args[Idx++]);
873 Function *FunctionAST::codegen() {
874 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
875 // reference to it for use below.
877 FunctionProtos[Proto->getName()] = std::move(Proto);
878 Function *TheFunction = getFunction(P.getName());
882 // If this is an operator, install it.
884 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
886 // Create a new basic block to start insertion into.
887 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
888 Builder.SetInsertPoint(BB);
890 // Record the function arguments in the NamedValues map.
892 for (auto &Arg : TheFunction->args())
893 NamedValues[Arg.getName()] = &Arg;
895 if (Value *RetVal = Body->codegen()) {
896 // Finish off the function.
897 Builder.CreateRet(RetVal);
899 // Validate the generated code, checking for consistency.
900 verifyFunction(*TheFunction);
902 // Run the optimizer on the function.
903 TheFPM->run(*TheFunction);
908 // Error reading body, remove function.
909 TheFunction->eraseFromParent();
912 BinopPrecedence.erase(Proto->getOperatorName());
916 //===----------------------------------------------------------------------===//
917 // Top-Level parsing and JIT Driver
918 //===----------------------------------------------------------------------===//
920 static void InitializeModuleAndPassManager() {
921 // Open a new module.
922 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
923 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
925 // Create a new pass manager attached to it.
926 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
928 // Do simple "peephole" optimizations and bit-twiddling optzns.
929 TheFPM->add(createInstructionCombiningPass());
930 // Reassociate expressions.
931 TheFPM->add(createReassociatePass());
932 // Eliminate Common SubExpressions.
933 TheFPM->add(createGVNPass());
934 // Simplify the control flow graph (deleting unreachable blocks, etc).
935 TheFPM->add(createCFGSimplificationPass());
937 TheFPM->doInitialization();
940 static void HandleDefinition() {
941 if (auto FnAST = ParseDefinition()) {
942 if (auto *FnIR = FnAST->codegen()) {
943 fprintf(stderr, "Read function definition:");
945 TheJIT->addModule(std::move(TheModule));
946 InitializeModuleAndPassManager();
949 // Skip token for error recovery.
954 static void HandleExtern() {
955 if (auto ProtoAST = ParseExtern()) {
956 if (auto *FnIR = ProtoAST->codegen()) {
957 fprintf(stderr, "Read extern: ");
959 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
962 // Skip token for error recovery.
967 static void HandleTopLevelExpression() {
968 // Evaluate a top-level expression into an anonymous function.
969 if (auto FnAST = ParseTopLevelExpr()) {
970 if (FnAST->codegen()) {
972 // JIT the module containing the anonymous expression, keeping a handle so
973 // we can free it later.
974 auto H = TheJIT->addModule(std::move(TheModule));
975 InitializeModuleAndPassManager();
977 // Search the JIT for the __anon_expr symbol.
978 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
979 assert(ExprSymbol && "Function not found");
981 // Get the symbol's address and cast it to the right type (takes no
982 // arguments, returns a double) so we can call it as a native function.
983 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
984 fprintf(stderr, "Evaluated to %f\n", FP());
986 // Delete the anonymous expression module from the JIT.
987 TheJIT->removeModule(H);
990 // Skip token for error recovery.
995 /// top ::= definition | external | expression | ';'
996 static void MainLoop() {
998 fprintf(stderr, "ready> ");
1002 case ';': // ignore top-level semicolons.
1012 HandleTopLevelExpression();
1018 //===----------------------------------------------------------------------===//
1019 // "Library" functions that can be "extern'd" from user code.
1020 //===----------------------------------------------------------------------===//
1022 /// putchard - putchar that takes a double and returns 0.
1023 extern "C" double putchard(double X) {
1024 fputc((char)X, stderr);
1028 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1029 extern "C" double printd(double X) {
1030 fprintf(stderr, "%f\n", X);
1034 //===----------------------------------------------------------------------===//
1035 // Main driver code.
1036 //===----------------------------------------------------------------------===//
1039 InitializeNativeTarget();
1040 InitializeNativeTargetAsmPrinter();
1041 InitializeNativeTargetAsmParser();
1043 // Install standard binary operators.
1044 // 1 is lowest precedence.
1045 BinopPrecedence['<'] = 10;
1046 BinopPrecedence['+'] = 20;
1047 BinopPrecedence['-'] = 20;
1048 BinopPrecedence['*'] = 40; // highest.
1050 // Prime the first token.
1051 fprintf(stderr, "ready> ");
1054 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1056 InitializeModuleAndPassManager();
1058 // Run the main "interpreter loop" now.