1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/IR/IRBuilder.h"
5 #include "llvm/IR/LLVMContext.h"
6 #include "llvm/IR/LegacyPassManager.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/Support/TargetSelect.h"
10 #include "llvm/Transforms/Scalar.h"
16 #include "../include/KaleidoscopeJIT.h"
19 using namespace llvm::orc;
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26 // of these for known things.
50 static std::string IdentifierStr; // Filled in if tok_identifier
51 static double NumVal; // Filled in if tok_number
53 /// gettok - Return the next token from standard input.
55 static int LastChar = ' ';
57 // Skip any whitespace.
58 while (isspace(LastChar))
61 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
62 IdentifierStr = LastChar;
63 while (isalnum((LastChar = getchar())))
64 IdentifierStr += LastChar;
66 if (IdentifierStr == "def")
68 if (IdentifierStr == "extern")
70 if (IdentifierStr == "if")
72 if (IdentifierStr == "then")
74 if (IdentifierStr == "else")
76 if (IdentifierStr == "for")
78 if (IdentifierStr == "in")
80 if (IdentifierStr == "binary")
82 if (IdentifierStr == "unary")
84 return tok_identifier;
87 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
92 } while (isdigit(LastChar) || LastChar == '.');
94 NumVal = strtod(NumStr.c_str(), 0);
98 if (LastChar == '#') {
99 // Comment until end of line.
101 LastChar = getchar();
102 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
108 // Check for end of file. Don't eat the EOF.
112 // Otherwise, just return the character as its ascii value.
113 int ThisChar = LastChar;
114 LastChar = getchar();
118 //===----------------------------------------------------------------------===//
119 // Abstract Syntax Tree (aka Parse Tree)
120 //===----------------------------------------------------------------------===//
122 /// ExprAST - Base class for all expression nodes.
125 virtual ~ExprAST() {}
126 virtual Value *codegen() = 0;
129 /// NumberExprAST - Expression class for numeric literals like "1.0".
130 class NumberExprAST : public ExprAST {
134 NumberExprAST(double Val) : Val(Val) {}
135 Value *codegen() override;
138 /// VariableExprAST - Expression class for referencing a variable, like "a".
139 class VariableExprAST : public ExprAST {
143 VariableExprAST(const std::string &Name) : Name(Name) {}
144 Value *codegen() override;
147 /// UnaryExprAST - Expression class for a unary operator.
148 class UnaryExprAST : public ExprAST {
150 std::unique_ptr<ExprAST> Operand;
153 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
154 : Opcode(Opcode), Operand(std::move(Operand)) {}
155 Value *codegen() override;
158 /// BinaryExprAST - Expression class for a binary operator.
159 class BinaryExprAST : public ExprAST {
161 std::unique_ptr<ExprAST> LHS, RHS;
164 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
165 std::unique_ptr<ExprAST> RHS)
166 : 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)) {}
179 Value *codegen() override;
182 /// IfExprAST - Expression class for if/then/else.
183 class IfExprAST : public ExprAST {
184 std::unique_ptr<ExprAST> Cond, Then, Else;
187 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
188 std::unique_ptr<ExprAST> Else)
189 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
190 Value *codegen() override;
193 /// ForExprAST - Expression class for for/in.
194 class ForExprAST : public ExprAST {
196 std::unique_ptr<ExprAST> Start, End, Step, Body;
199 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
200 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
201 std::unique_ptr<ExprAST> Body)
202 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
203 Step(std::move(Step)), Body(std::move(Body)) {}
204 Value *codegen() override;
207 /// PrototypeAST - This class represents the "prototype" for a function,
208 /// which captures its name, and its argument names (thus implicitly the number
209 /// of arguments the function takes), as well as if it is an operator.
212 std::vector<std::string> Args;
214 unsigned Precedence; // Precedence if a binary op.
217 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
218 bool IsOperator = false, unsigned Prec = 0)
219 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
222 const std::string &getName() const { return Name; }
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; }
235 /// FunctionAST - This class represents a function definition itself.
237 std::unique_ptr<PrototypeAST> Proto;
238 std::unique_ptr<ExprAST> Body;
241 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
242 std::unique_ptr<ExprAST> Body)
243 : Proto(std::move(Proto)), Body(std::move(Body)) {}
246 } // end anonymous namespace
248 //===----------------------------------------------------------------------===//
250 //===----------------------------------------------------------------------===//
252 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
253 /// token the parser is looking at. getNextToken reads another token from the
254 /// lexer and updates CurTok with its results.
256 static int getNextToken() { return CurTok = gettok(); }
258 /// BinopPrecedence - This holds the precedence for each binary operator that is
260 static std::map<char, int> BinopPrecedence;
262 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
263 static int GetTokPrecedence() {
264 if (!isascii(CurTok))
267 // Make sure it's a declared binop.
268 int TokPrec = BinopPrecedence[CurTok];
274 /// Error* - These are little helper functions for error handling.
275 std::unique_ptr<ExprAST> Error(const char *Str) {
276 fprintf(stderr, "Error: %s\n", Str);
279 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
284 static std::unique_ptr<ExprAST> ParseExpression();
286 /// numberexpr ::= number
287 static std::unique_ptr<ExprAST> ParseNumberExpr() {
288 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
289 getNextToken(); // consume the number
290 return std::move(Result);
293 /// parenexpr ::= '(' expression ')'
294 static std::unique_ptr<ExprAST> ParseParenExpr() {
295 getNextToken(); // eat (.
296 auto V = ParseExpression();
301 return Error("expected ')'");
302 getNextToken(); // eat ).
308 /// ::= identifier '(' expression* ')'
309 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
310 std::string IdName = IdentifierStr;
312 getNextToken(); // eat identifier.
314 if (CurTok != '(') // Simple variable ref.
315 return llvm::make_unique<VariableExprAST>(IdName);
318 getNextToken(); // eat (
319 std::vector<std::unique_ptr<ExprAST>> Args;
322 if (auto Arg = ParseExpression())
323 Args.push_back(std::move(Arg));
331 return Error("Expected ')' or ',' in argument list");
339 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
342 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
343 static std::unique_ptr<ExprAST> ParseIfExpr() {
344 getNextToken(); // eat the if.
347 auto Cond = ParseExpression();
351 if (CurTok != tok_then)
352 return Error("expected then");
353 getNextToken(); // eat the then
355 auto Then = ParseExpression();
359 if (CurTok != tok_else)
360 return Error("expected else");
364 auto Else = ParseExpression();
368 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
372 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
373 static std::unique_ptr<ExprAST> ParseForExpr() {
374 getNextToken(); // eat the for.
376 if (CurTok != tok_identifier)
377 return Error("expected identifier after for");
379 std::string IdName = IdentifierStr;
380 getNextToken(); // eat identifier.
383 return Error("expected '=' after for");
384 getNextToken(); // eat '='.
386 auto Start = ParseExpression();
390 return Error("expected ',' after for start value");
393 auto End = ParseExpression();
397 // The step value is optional.
398 std::unique_ptr<ExprAST> Step;
401 Step = ParseExpression();
406 if (CurTok != tok_in)
407 return Error("expected 'in' after for");
408 getNextToken(); // eat 'in'.
410 auto Body = ParseExpression();
414 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
415 std::move(Step), std::move(Body));
419 /// ::= identifierexpr
424 static std::unique_ptr<ExprAST> ParsePrimary() {
427 return Error("unknown token when expecting an expression");
429 return ParseIdentifierExpr();
431 return ParseNumberExpr();
433 return ParseParenExpr();
435 return ParseIfExpr();
437 return ParseForExpr();
444 static std::unique_ptr<ExprAST> ParseUnary() {
445 // If the current token is not an operator, it must be a primary expr.
446 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
447 return ParsePrimary();
449 // If this is a unary operator, read it.
452 if (auto Operand = ParseUnary())
453 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
459 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
460 std::unique_ptr<ExprAST> LHS) {
461 // If this is a binop, find its precedence.
463 int TokPrec = GetTokPrecedence();
465 // If this is a binop that binds at least as tightly as the current binop,
466 // consume it, otherwise we are done.
467 if (TokPrec < ExprPrec)
470 // Okay, we know this is a binop.
472 getNextToken(); // eat binop
474 // Parse the unary expression after the binary operator.
475 auto RHS = ParseUnary();
479 // If BinOp binds less tightly with RHS than the operator after RHS, let
480 // the pending operator take RHS as its LHS.
481 int NextPrec = GetTokPrecedence();
482 if (TokPrec < NextPrec) {
483 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
490 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
495 /// ::= unary binoprhs
497 static std::unique_ptr<ExprAST> ParseExpression() {
498 auto LHS = ParseUnary();
502 return ParseBinOpRHS(0, std::move(LHS));
506 /// ::= id '(' id* ')'
507 /// ::= binary LETTER number? (id, id)
508 /// ::= unary LETTER (id)
509 static std::unique_ptr<PrototypeAST> ParsePrototype() {
512 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
513 unsigned BinaryPrecedence = 30;
517 return ErrorP("Expected function name in prototype");
519 FnName = IdentifierStr;
525 if (!isascii(CurTok))
526 return ErrorP("Expected unary operator");
528 FnName += (char)CurTok;
534 if (!isascii(CurTok))
535 return ErrorP("Expected binary operator");
537 FnName += (char)CurTok;
541 // Read the precedence if present.
542 if (CurTok == tok_number) {
543 if (NumVal < 1 || NumVal > 100)
544 return ErrorP("Invalid precedecnce: must be 1..100");
545 BinaryPrecedence = (unsigned)NumVal;
552 return ErrorP("Expected '(' in prototype");
554 std::vector<std::string> ArgNames;
555 while (getNextToken() == tok_identifier)
556 ArgNames.push_back(IdentifierStr);
558 return ErrorP("Expected ')' in prototype");
561 getNextToken(); // eat ')'.
563 // Verify right number of names for operator.
564 if (Kind && ArgNames.size() != Kind)
565 return ErrorP("Invalid number of operands for operator");
567 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
571 /// definition ::= 'def' prototype expression
572 static std::unique_ptr<FunctionAST> ParseDefinition() {
573 getNextToken(); // eat def.
574 auto Proto = ParsePrototype();
578 if (auto E = ParseExpression())
579 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
583 /// toplevelexpr ::= expression
584 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
585 if (auto E = ParseExpression()) {
586 // Make an anonymous proto.
587 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
588 std::vector<std::string>());
589 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
594 /// external ::= 'extern' prototype
595 static std::unique_ptr<PrototypeAST> ParseExtern() {
596 getNextToken(); // eat extern.
597 return ParsePrototype();
600 //===----------------------------------------------------------------------===//
602 //===----------------------------------------------------------------------===//
604 static std::unique_ptr<Module> TheModule;
605 static IRBuilder<> Builder(getGlobalContext());
606 static std::map<std::string, Value *> NamedValues;
607 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
608 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
609 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
611 Value *ErrorV(const char *Str) {
616 Function *getFunction(std::string Name) {
617 // First, see if the function has already been added to the current module.
618 if (auto *F = TheModule->getFunction(Name))
621 // If not, check whether we can codegen the declaration from some existing
623 auto FI = FunctionProtos.find(Name);
624 if (FI != FunctionProtos.end())
625 return FI->second->codegen();
627 // If no existing prototype exists, return null.
631 Value *NumberExprAST::codegen() {
632 return ConstantFP::get(getGlobalContext(), APFloat(Val));
635 Value *VariableExprAST::codegen() {
636 // Look this variable up in the function.
637 Value *V = NamedValues[Name];
639 return ErrorV("Unknown variable name");
643 Value *UnaryExprAST::codegen() {
644 Value *OperandV = Operand->codegen();
648 Function *F = getFunction(std::string("unary") + Opcode);
650 return ErrorV("Unknown unary operator");
652 return Builder.CreateCall(F, OperandV, "unop");
655 Value *BinaryExprAST::codegen() {
656 Value *L = LHS->codegen();
657 Value *R = RHS->codegen();
663 return Builder.CreateFAdd(L, R, "addtmp");
665 return Builder.CreateFSub(L, R, "subtmp");
667 return Builder.CreateFMul(L, R, "multmp");
669 L = Builder.CreateFCmpULT(L, R, "cmptmp");
670 // Convert bool 0/1 to double 0.0 or 1.0
671 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
677 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
679 Function *F = getFunction(std::string("binary") + Op);
680 assert(F && "binary operator not found!");
682 Value *Ops[] = {L, R};
683 return Builder.CreateCall(F, Ops, "binop");
686 Value *CallExprAST::codegen() {
687 // Look up the name in the global module table.
688 Function *CalleeF = getFunction(Callee);
690 return ErrorV("Unknown function referenced");
692 // If argument mismatch error.
693 if (CalleeF->arg_size() != Args.size())
694 return ErrorV("Incorrect # arguments passed");
696 std::vector<Value *> ArgsV;
697 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
698 ArgsV.push_back(Args[i]->codegen());
703 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
706 Value *IfExprAST::codegen() {
707 Value *CondV = Cond->codegen();
711 // Convert condition to a bool by comparing equal to 0.0.
712 CondV = Builder.CreateFCmpONE(
713 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
715 Function *TheFunction = Builder.GetInsertBlock()->getParent();
717 // Create blocks for the then and else cases. Insert the 'then' block at the
718 // end of the function.
720 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
721 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
722 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
724 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
727 Builder.SetInsertPoint(ThenBB);
729 Value *ThenV = Then->codegen();
733 Builder.CreateBr(MergeBB);
734 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
735 ThenBB = Builder.GetInsertBlock();
738 TheFunction->getBasicBlockList().push_back(ElseBB);
739 Builder.SetInsertPoint(ElseBB);
741 Value *ElseV = Else->codegen();
745 Builder.CreateBr(MergeBB);
746 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
747 ElseBB = Builder.GetInsertBlock();
750 TheFunction->getBasicBlockList().push_back(MergeBB);
751 Builder.SetInsertPoint(MergeBB);
753 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
755 PN->addIncoming(ThenV, ThenBB);
756 PN->addIncoming(ElseV, ElseBB);
760 // Output for-loop as:
765 // variable = phi [start, loopheader], [nextvariable, loopend]
771 // nextvariable = variable + step
773 // br endcond, loop, endloop
775 Value *ForExprAST::codegen() {
776 // Emit the start code first, without 'variable' in scope.
777 Value *StartVal = Start->codegen();
781 // Make the new basic block for the loop header, inserting after current
783 Function *TheFunction = Builder.GetInsertBlock()->getParent();
784 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
786 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
788 // Insert an explicit fall through from the current block to the LoopBB.
789 Builder.CreateBr(LoopBB);
791 // Start insertion in LoopBB.
792 Builder.SetInsertPoint(LoopBB);
794 // Start the PHI node with an entry for Start.
795 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
797 Variable->addIncoming(StartVal, PreheaderBB);
799 // Within the loop, the variable is defined equal to the PHI node. If it
800 // shadows an existing variable, we have to restore it, so save it now.
801 Value *OldVal = NamedValues[VarName];
802 NamedValues[VarName] = Variable;
804 // Emit the body of the loop. This, like any other expr, can change the
805 // current BB. Note that we ignore the value computed by the body, but don't
807 if (!Body->codegen())
810 // Emit the step value.
811 Value *StepVal = nullptr;
813 StepVal = Step->codegen();
817 // If not specified, use 1.0.
818 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
821 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
823 // Compute the end condition.
824 Value *EndCond = End->codegen();
828 // Convert condition to a bool by comparing equal to 0.0.
829 EndCond = Builder.CreateFCmpONE(
830 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
832 // Create the "after loop" block and insert it.
833 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
834 BasicBlock *AfterBB =
835 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
837 // Insert the conditional branch into the end of LoopEndBB.
838 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
840 // Any new code will be inserted in AfterBB.
841 Builder.SetInsertPoint(AfterBB);
843 // Add a new entry to the PHI node for the backedge.
844 Variable->addIncoming(NextVar, LoopEndBB);
846 // Restore the unshadowed variable.
848 NamedValues[VarName] = OldVal;
850 NamedValues.erase(VarName);
852 // for expr always returns 0.0.
853 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
856 Function *PrototypeAST::codegen() {
857 // Make the function type: double(double,double) etc.
858 std::vector<Type *> Doubles(Args.size(),
859 Type::getDoubleTy(getGlobalContext()));
861 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
864 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
866 // Set names for all arguments.
868 for (auto &Arg : F->args())
869 Arg.setName(Args[Idx++]);
874 Function *FunctionAST::codegen() {
875 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
876 // reference to it for use below.
878 FunctionProtos[Proto->getName()] = std::move(Proto);
879 Function *TheFunction = getFunction(P.getName());
883 // If this is an operator, install it.
885 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
887 // Create a new basic block to start insertion into.
888 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
889 Builder.SetInsertPoint(BB);
891 // Record the function arguments in the NamedValues map.
893 for (auto &Arg : TheFunction->args())
894 NamedValues[Arg.getName()] = &Arg;
896 if (Value *RetVal = Body->codegen()) {
897 // Finish off the function.
898 Builder.CreateRet(RetVal);
900 // Validate the generated code, checking for consistency.
901 verifyFunction(*TheFunction);
903 // Run the optimizer on the function.
904 TheFPM->run(*TheFunction);
909 // Error reading body, remove function.
910 TheFunction->eraseFromParent();
913 BinopPrecedence.erase(Proto->getOperatorName());
917 //===----------------------------------------------------------------------===//
918 // Top-Level parsing and JIT Driver
919 //===----------------------------------------------------------------------===//
921 static void InitializeModuleAndPassManager() {
922 // Open a new module.
923 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
924 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
926 // Create a new pass manager attached to it.
927 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
929 // Provide basic AliasAnalysis support for GVN.
930 TheFPM->add(createBasicAliasAnalysisPass());
931 // Do simple "peephole" optimizations and bit-twiddling optzns.
932 TheFPM->add(createInstructionCombiningPass());
933 // Reassociate expressions.
934 TheFPM->add(createReassociatePass());
935 // Eliminate Common SubExpressions.
936 TheFPM->add(createGVNPass());
937 // Simplify the control flow graph (deleting unreachable blocks, etc).
938 TheFPM->add(createCFGSimplificationPass());
940 TheFPM->doInitialization();
943 static void HandleDefinition() {
944 if (auto FnAST = ParseDefinition()) {
945 if (auto *FnIR = FnAST->codegen()) {
946 fprintf(stderr, "Read function definition:");
948 TheJIT->addModule(std::move(TheModule));
949 InitializeModuleAndPassManager();
952 // Skip token for error recovery.
957 static void HandleExtern() {
958 if (auto ProtoAST = ParseExtern()) {
959 if (auto *FnIR = ProtoAST->codegen()) {
960 fprintf(stderr, "Read extern: ");
962 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
965 // Skip token for error recovery.
970 static void HandleTopLevelExpression() {
971 // Evaluate a top-level expression into an anonymous function.
972 if (auto FnAST = ParseTopLevelExpr()) {
973 if (FnAST->codegen()) {
975 // JIT the module containing the anonymous expression, keeping a handle so
976 // we can free it later.
977 auto H = TheJIT->addModule(std::move(TheModule));
978 InitializeModuleAndPassManager();
980 // Search the JIT for the __anon_expr symbol.
981 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
982 assert(ExprSymbol && "Function not found");
984 // Get the symbol's address and cast it to the right type (takes no
985 // arguments, returns a double) so we can call it as a native function.
986 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
987 fprintf(stderr, "Evaluated to %f\n", FP());
989 // Delete the anonymous expression module from the JIT.
990 TheJIT->removeModule(H);
993 // Skip token for error recovery.
998 /// top ::= definition | external | expression | ';'
999 static void MainLoop() {
1001 fprintf(stderr, "ready> ");
1005 case ';': // ignore top-level semicolons.
1015 HandleTopLevelExpression();
1021 //===----------------------------------------------------------------------===//
1022 // "Library" functions that can be "extern'd" from user code.
1023 //===----------------------------------------------------------------------===//
1025 /// putchard - putchar that takes a double and returns 0.
1026 extern "C" double putchard(double X) {
1031 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1032 extern "C" double printd(double X) {
1037 //===----------------------------------------------------------------------===//
1038 // Main driver code.
1039 //===----------------------------------------------------------------------===//
1042 InitializeNativeTarget();
1043 InitializeNativeTargetAsmPrinter();
1044 InitializeNativeTargetAsmParser();
1046 // Install standard binary operators.
1047 // 1 is lowest precedence.
1048 BinopPrecedence['<'] = 10;
1049 BinopPrecedence['+'] = 20;
1050 BinopPrecedence['-'] = 20;
1051 BinopPrecedence['*'] = 40; // highest.
1053 // Prime the first token.
1054 fprintf(stderr, "ready> ");
1057 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1059 InitializeModuleAndPassManager();
1061 // Run the main "interpreter loop" now.