1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
3 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
4 #include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
5 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
6 #include "llvm/IR/DataLayout.h"
7 #include "llvm/IR/DerivedTypes.h"
8 #include "llvm/IR/IRBuilder.h"
9 #include "llvm/IR/LLVMContext.h"
10 #include "llvm/IR/LegacyPassManager.h"
11 #include "llvm/IR/Module.h"
12 #include "llvm/IR/Verifier.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Transforms/Scalar.h"
24 using namespace llvm::orc;
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31 // of these for known things.
36 tok_def = -2, tok_extern = -3,
39 tok_identifier = -4, tok_number = -5,
42 tok_if = -6, tok_then = -7, tok_else = -8,
43 tok_for = -9, tok_in = -10,
46 tok_binary = -11, tok_unary = -12,
52 static std::string IdentifierStr; // Filled in if tok_identifier
53 static double NumVal; // Filled in if tok_number
55 /// gettok - Return the next token from standard input.
57 static int LastChar = ' ';
59 // Skip any whitespace.
60 while (isspace(LastChar))
63 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
64 IdentifierStr = LastChar;
65 while (isalnum((LastChar = getchar())))
66 IdentifierStr += LastChar;
68 if (IdentifierStr == "def") return tok_def;
69 if (IdentifierStr == "extern") return tok_extern;
70 if (IdentifierStr == "if") return tok_if;
71 if (IdentifierStr == "then") return tok_then;
72 if (IdentifierStr == "else") return tok_else;
73 if (IdentifierStr == "for") return tok_for;
74 if (IdentifierStr == "in") return tok_in;
75 if (IdentifierStr == "binary") return tok_binary;
76 if (IdentifierStr == "unary") return tok_unary;
77 if (IdentifierStr == "var") return tok_var;
78 return tok_identifier;
81 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
86 } while (isdigit(LastChar) || LastChar == '.');
88 NumVal = strtod(NumStr.c_str(), 0);
92 if (LastChar == '#') {
93 // Comment until end of line.
94 do LastChar = getchar();
95 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
101 // Check for end of file. Don't eat the EOF.
105 // Otherwise, just return the character as its ascii value.
106 int ThisChar = LastChar;
107 LastChar = getchar();
111 //===----------------------------------------------------------------------===//
112 // Abstract Syntax Tree (aka Parse Tree)
113 //===----------------------------------------------------------------------===//
117 /// ExprAST - Base class for all expression nodes.
119 virtual ~ExprAST() {}
120 virtual Value *IRGen(IRGenContext &C) const = 0;
123 /// NumberExprAST - Expression class for numeric literals like "1.0".
124 struct NumberExprAST : public ExprAST {
125 NumberExprAST(double Val) : Val(Val) {}
126 Value *IRGen(IRGenContext &C) const override;
131 /// VariableExprAST - Expression class for referencing a variable, like "a".
132 struct VariableExprAST : public ExprAST {
133 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
134 Value *IRGen(IRGenContext &C) const override;
139 /// UnaryExprAST - Expression class for a unary operator.
140 struct UnaryExprAST : public ExprAST {
141 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
142 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
144 Value *IRGen(IRGenContext &C) const override;
147 std::unique_ptr<ExprAST> Operand;
150 /// BinaryExprAST - Expression class for a binary operator.
151 struct BinaryExprAST : public ExprAST {
152 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
153 std::unique_ptr<ExprAST> RHS)
154 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
156 Value *IRGen(IRGenContext &C) const override;
159 std::unique_ptr<ExprAST> LHS, RHS;
162 /// CallExprAST - Expression class for function calls.
163 struct CallExprAST : public ExprAST {
164 CallExprAST(std::string CalleeName,
165 std::vector<std::unique_ptr<ExprAST>> Args)
166 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
168 Value *IRGen(IRGenContext &C) const override;
170 std::string CalleeName;
171 std::vector<std::unique_ptr<ExprAST>> Args;
174 /// IfExprAST - Expression class for if/then/else.
175 struct IfExprAST : public ExprAST {
176 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
177 std::unique_ptr<ExprAST> Else)
178 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
179 Value *IRGen(IRGenContext &C) const override;
181 std::unique_ptr<ExprAST> Cond, Then, Else;
184 /// ForExprAST - Expression class for for/in.
185 struct ForExprAST : public ExprAST {
186 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
187 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
188 std::unique_ptr<ExprAST> Body)
189 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
190 Step(std::move(Step)), Body(std::move(Body)) {}
192 Value *IRGen(IRGenContext &C) const override;
195 std::unique_ptr<ExprAST> Start, End, Step, Body;
198 /// VarExprAST - Expression class for var/in
199 struct VarExprAST : public ExprAST {
200 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
201 typedef std::vector<Binding> BindingList;
203 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
204 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
206 Value *IRGen(IRGenContext &C) const override;
208 BindingList VarBindings;
209 std::unique_ptr<ExprAST> Body;
212 /// PrototypeAST - This class represents the "prototype" for a function,
213 /// which captures its argument names as well as if it is an operator.
214 struct PrototypeAST {
215 PrototypeAST(std::string Name, std::vector<std::string> Args,
216 bool IsOperator = false, unsigned Precedence = 0)
217 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
218 Precedence(Precedence) {}
220 Function *IRGen(IRGenContext &C) const;
221 void CreateArgumentAllocas(Function *F, IRGenContext &C);
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];
232 std::vector<std::string> Args;
234 unsigned Precedence; // Precedence if a binary op.
237 /// FunctionAST - This class represents a function definition itself.
239 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
240 std::unique_ptr<ExprAST> Body)
241 : Proto(std::move(Proto)), Body(std::move(Body)) {}
243 Function *IRGen(IRGenContext &C) const;
245 std::unique_ptr<PrototypeAST> Proto;
246 std::unique_ptr<ExprAST> Body;
249 //===----------------------------------------------------------------------===//
251 //===----------------------------------------------------------------------===//
253 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
254 /// token the parser is looking at. getNextToken reads another token from the
255 /// lexer and updates CurTok with its results.
257 static int getNextToken() {
258 return CurTok = gettok();
261 /// BinopPrecedence - This holds the precedence for each binary operator that is
263 static std::map<char, int> BinopPrecedence;
265 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
266 static int GetTokPrecedence() {
267 if (!isascii(CurTok))
270 // Make sure it's a declared binop.
271 int TokPrec = BinopPrecedence[CurTok];
272 if (TokPrec <= 0) return -1;
276 template <typename T>
277 std::unique_ptr<T> ErrorU(const std::string &Str) {
278 std::cerr << "Error: " << Str << "\n";
282 template <typename T>
283 T* ErrorP(const std::string &Str) {
284 std::cerr << "Error: " << Str << "\n";
288 static std::unique_ptr<ExprAST> ParseExpression();
292 /// ::= identifier '(' expression* ')'
293 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
294 std::string IdName = IdentifierStr;
296 getNextToken(); // eat identifier.
298 if (CurTok != '(') // Simple variable ref.
299 return llvm::make_unique<VariableExprAST>(IdName);
302 getNextToken(); // eat (
303 std::vector<std::unique_ptr<ExprAST>> Args;
306 auto Arg = ParseExpression();
307 if (!Arg) return nullptr;
308 Args.push_back(std::move(Arg));
310 if (CurTok == ')') break;
313 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
321 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
324 /// numberexpr ::= number
325 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
326 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
327 getNextToken(); // consume the number
331 /// parenexpr ::= '(' expression ')'
332 static std::unique_ptr<ExprAST> ParseParenExpr() {
333 getNextToken(); // eat (.
334 auto V = ParseExpression();
339 return ErrorU<ExprAST>("expected ')'");
340 getNextToken(); // eat ).
344 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
345 static std::unique_ptr<ExprAST> ParseIfExpr() {
346 getNextToken(); // eat the if.
349 auto Cond = ParseExpression();
353 if (CurTok != tok_then)
354 return ErrorU<ExprAST>("expected then");
355 getNextToken(); // eat the then
357 auto Then = ParseExpression();
361 if (CurTok != tok_else)
362 return ErrorU<ExprAST>("expected else");
366 auto Else = ParseExpression();
370 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
374 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
375 static std::unique_ptr<ForExprAST> ParseForExpr() {
376 getNextToken(); // eat the for.
378 if (CurTok != tok_identifier)
379 return ErrorU<ForExprAST>("expected identifier after for");
381 std::string IdName = IdentifierStr;
382 getNextToken(); // eat identifier.
385 return ErrorU<ForExprAST>("expected '=' after for");
386 getNextToken(); // eat '='.
389 auto Start = ParseExpression();
393 return ErrorU<ForExprAST>("expected ',' after for start value");
396 auto End = ParseExpression();
400 // The step value is optional.
401 std::unique_ptr<ExprAST> Step;
404 Step = ParseExpression();
409 if (CurTok != tok_in)
410 return ErrorU<ForExprAST>("expected 'in' after for");
411 getNextToken(); // eat 'in'.
413 auto Body = ParseExpression();
417 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
418 std::move(Step), std::move(Body));
421 /// varexpr ::= 'var' identifier ('=' expression)?
422 // (',' identifier ('=' expression)?)* 'in' expression
423 static std::unique_ptr<VarExprAST> ParseVarExpr() {
424 getNextToken(); // eat the var.
426 VarExprAST::BindingList VarBindings;
428 // At least one variable name is required.
429 if (CurTok != tok_identifier)
430 return ErrorU<VarExprAST>("expected identifier after var");
433 std::string Name = IdentifierStr;
434 getNextToken(); // eat identifier.
436 // Read the optional initializer.
437 std::unique_ptr<ExprAST> Init;
439 getNextToken(); // eat the '='.
441 Init = ParseExpression();
446 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
448 // End of var list, exit loop.
449 if (CurTok != ',') break;
450 getNextToken(); // eat the ','.
452 if (CurTok != tok_identifier)
453 return ErrorU<VarExprAST>("expected identifier list after var");
456 // At this point, we have to have 'in'.
457 if (CurTok != tok_in)
458 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
459 getNextToken(); // eat 'in'.
461 auto Body = ParseExpression();
465 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
469 /// ::= identifierexpr
475 static std::unique_ptr<ExprAST> ParsePrimary() {
477 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
478 case tok_identifier: return ParseIdentifierExpr();
479 case tok_number: return ParseNumberExpr();
480 case '(': return ParseParenExpr();
481 case tok_if: return ParseIfExpr();
482 case tok_for: return ParseForExpr();
483 case tok_var: return ParseVarExpr();
490 static std::unique_ptr<ExprAST> ParseUnary() {
491 // If the current token is not an operator, it must be a primary expr.
492 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
493 return ParsePrimary();
495 // If this is a unary operator, read it.
498 if (auto Operand = ParseUnary())
499 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
505 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
506 std::unique_ptr<ExprAST> LHS) {
507 // If this is a binop, find its precedence.
509 int TokPrec = GetTokPrecedence();
511 // If this is a binop that binds at least as tightly as the current binop,
512 // consume it, otherwise we are done.
513 if (TokPrec < ExprPrec)
516 // Okay, we know this is a binop.
518 getNextToken(); // eat binop
520 // Parse the unary expression after the binary operator.
521 auto RHS = ParseUnary();
525 // If BinOp binds less tightly with RHS than the operator after RHS, let
526 // the pending operator take RHS as its LHS.
527 int NextPrec = GetTokPrecedence();
528 if (TokPrec < NextPrec) {
529 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
535 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
540 /// ::= unary binoprhs
542 static std::unique_ptr<ExprAST> ParseExpression() {
543 auto LHS = ParseUnary();
547 return ParseBinOpRHS(0, std::move(LHS));
551 /// ::= id '(' id* ')'
552 /// ::= binary LETTER number? (id, id)
553 /// ::= unary LETTER (id)
554 static std::unique_ptr<PrototypeAST> ParsePrototype() {
557 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
558 unsigned BinaryPrecedence = 30;
562 return ErrorU<PrototypeAST>("Expected function name in prototype");
564 FnName = IdentifierStr;
570 if (!isascii(CurTok))
571 return ErrorU<PrototypeAST>("Expected unary operator");
573 FnName += (char)CurTok;
579 if (!isascii(CurTok))
580 return ErrorU<PrototypeAST>("Expected binary operator");
582 FnName += (char)CurTok;
586 // Read the precedence if present.
587 if (CurTok == tok_number) {
588 if (NumVal < 1 || NumVal > 100)
589 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
590 BinaryPrecedence = (unsigned)NumVal;
597 return ErrorU<PrototypeAST>("Expected '(' in prototype");
599 std::vector<std::string> ArgNames;
600 while (getNextToken() == tok_identifier)
601 ArgNames.push_back(IdentifierStr);
603 return ErrorU<PrototypeAST>("Expected ')' in prototype");
606 getNextToken(); // eat ')'.
608 // Verify right number of names for operator.
609 if (Kind && ArgNames.size() != Kind)
610 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
612 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
616 /// definition ::= 'def' prototype expression
617 static std::unique_ptr<FunctionAST> ParseDefinition() {
618 getNextToken(); // eat def.
619 auto Proto = ParsePrototype();
623 if (auto Body = ParseExpression())
624 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
628 /// toplevelexpr ::= expression
629 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
630 if (auto E = ParseExpression()) {
631 // Make an anonymous proto.
633 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
634 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
639 /// external ::= 'extern' prototype
640 static std::unique_ptr<PrototypeAST> ParseExtern() {
641 getNextToken(); // eat extern.
642 return ParsePrototype();
645 //===----------------------------------------------------------------------===//
647 //===----------------------------------------------------------------------===//
649 // FIXME: Obviously we can do better than this
650 std::string GenerateUniqueName(const std::string &Root) {
652 std::ostringstream NameStream;
653 NameStream << Root << ++i;
654 return NameStream.str();
657 std::string MakeLegalFunctionName(std::string Name)
660 assert(!Name.empty() && "Base name must not be empty");
662 // Start with what we have
665 // Look for a numberic first character
666 if (NewName.find_first_of("0123456789") == 0) {
667 NewName.insert(0, 1, 'n');
670 // Replace illegal characters with their ASCII equivalent
671 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
673 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
674 std::ostringstream NumStream;
675 NumStream << (int)NewName.at(pos);
676 NewName = NewName.replace(pos, 1, NumStream.str());
682 class SessionContext {
684 SessionContext(LLVMContext &C) : Context(C) {}
685 LLVMContext& getLLVMContext() const { return Context; }
686 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
687 PrototypeAST* getPrototypeAST(const std::string &Name);
688 std::map<std::string, std::unique_ptr<FunctionAST>> FunctionDefs;
690 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
691 LLVMContext &Context;
692 PrototypeMap Prototypes;
695 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
696 Prototypes[P->Name] = std::move(P);
699 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
700 PrototypeMap::iterator I = Prototypes.find(Name);
701 if (I != Prototypes.end())
702 return I->second.get();
709 IRGenContext(SessionContext &S)
711 M(new Module(GenerateUniqueName("jit_module_"),
712 Session.getLLVMContext())),
713 Builder(Session.getLLVMContext()) {}
715 SessionContext& getSession() { return Session; }
716 Module& getM() const { return *M; }
717 std::unique_ptr<Module> takeM() { return std::move(M); }
718 IRBuilder<>& getBuilder() { return Builder; }
719 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
720 Function* getPrototype(const std::string &Name);
722 std::map<std::string, AllocaInst*> NamedValues;
724 SessionContext &Session;
725 std::unique_ptr<Module> M;
729 Function* IRGenContext::getPrototype(const std::string &Name) {
730 if (Function *ExistingProto = M->getFunction(Name))
731 return ExistingProto;
732 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
733 return ProtoAST->IRGen(*this);
737 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
738 /// the function. This is used for mutable variables etc.
739 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
740 const std::string &VarName) {
741 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
742 TheFunction->getEntryBlock().begin());
743 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
747 Value *NumberExprAST::IRGen(IRGenContext &C) const {
748 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
751 Value *VariableExprAST::IRGen(IRGenContext &C) const {
752 // Look this variable up in the function.
753 Value *V = C.NamedValues[Name];
756 return ErrorP<Value>("Unknown variable name '" + Name + "'");
759 return C.getBuilder().CreateLoad(V, Name.c_str());
762 Value *UnaryExprAST::IRGen(IRGenContext &C) const {
763 if (Value *OperandV = Operand->IRGen(C)) {
764 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
765 if (Function *F = C.getPrototype(FnName))
766 return C.getBuilder().CreateCall(F, OperandV, "unop");
767 return ErrorP<Value>("Unknown unary operator");
770 // Could not codegen operand - return null.
774 Value *BinaryExprAST::IRGen(IRGenContext &C) const {
775 // Special case '=' because we don't want to emit the LHS as an expression.
777 // Assignment requires the LHS to be an identifier.
778 auto LHSVar = static_cast<VariableExprAST&>(*LHS);
780 Value *Val = RHS->IRGen(C);
781 if (!Val) return nullptr;
784 if (auto Variable = C.NamedValues[LHSVar.Name]) {
785 C.getBuilder().CreateStore(Val, Variable);
788 return ErrorP<Value>("Unknown variable name");
791 Value *L = LHS->IRGen(C);
792 Value *R = RHS->IRGen(C);
793 if (!L || !R) return nullptr;
796 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
797 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
798 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
799 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
801 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
802 // Convert bool 0/1 to double 0.0 or 1.0
803 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
808 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
810 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
811 if (Function *F = C.getPrototype(FnName)) {
812 Value *Ops[] = { L, R };
813 return C.getBuilder().CreateCall(F, Ops, "binop");
816 return ErrorP<Value>("Unknown binary operator");
819 Value *CallExprAST::IRGen(IRGenContext &C) const {
820 // Look up the name in the global module table.
821 if (auto CalleeF = C.getPrototype(CalleeName)) {
822 // If argument mismatch error.
823 if (CalleeF->arg_size() != Args.size())
824 return ErrorP<Value>("Incorrect # arguments passed");
826 std::vector<Value*> ArgsV;
827 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
828 ArgsV.push_back(Args[i]->IRGen(C));
829 if (!ArgsV.back()) return nullptr;
832 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
835 return ErrorP<Value>("Unknown function referenced");
838 Value *IfExprAST::IRGen(IRGenContext &C) const {
839 Value *CondV = Cond->IRGen(C);
840 if (!CondV) return nullptr;
842 // Convert condition to a bool by comparing equal to 0.0.
844 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
845 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
847 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
849 // Create blocks for the then and else cases. Insert the 'then' block at the
850 // end of the function.
851 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
852 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
853 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
855 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
858 C.getBuilder().SetInsertPoint(ThenBB);
860 Value *ThenV = Then->IRGen(C);
861 if (!ThenV) return nullptr;
863 C.getBuilder().CreateBr(MergeBB);
864 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
865 ThenBB = C.getBuilder().GetInsertBlock();
868 TheFunction->getBasicBlockList().push_back(ElseBB);
869 C.getBuilder().SetInsertPoint(ElseBB);
871 Value *ElseV = Else->IRGen(C);
872 if (!ElseV) return nullptr;
874 C.getBuilder().CreateBr(MergeBB);
875 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
876 ElseBB = C.getBuilder().GetInsertBlock();
879 TheFunction->getBasicBlockList().push_back(MergeBB);
880 C.getBuilder().SetInsertPoint(MergeBB);
881 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
884 PN->addIncoming(ThenV, ThenBB);
885 PN->addIncoming(ElseV, ElseBB);
889 Value *ForExprAST::IRGen(IRGenContext &C) const {
891 // var = alloca double
894 // store start -> var
905 // nextvar = curvar + step
906 // store nextvar -> var
907 // br endcond, loop, endloop
910 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
912 // Create an alloca for the variable in the entry block.
913 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
915 // Emit the start code first, without 'variable' in scope.
916 Value *StartVal = Start->IRGen(C);
917 if (!StartVal) return nullptr;
919 // Store the value into the alloca.
920 C.getBuilder().CreateStore(StartVal, Alloca);
922 // Make the new basic block for the loop header, inserting after current
924 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
926 // Insert an explicit fall through from the current block to the LoopBB.
927 C.getBuilder().CreateBr(LoopBB);
929 // Start insertion in LoopBB.
930 C.getBuilder().SetInsertPoint(LoopBB);
932 // Within the loop, the variable is defined equal to the PHI node. If it
933 // shadows an existing variable, we have to restore it, so save it now.
934 AllocaInst *OldVal = C.NamedValues[VarName];
935 C.NamedValues[VarName] = Alloca;
937 // Emit the body of the loop. This, like any other expr, can change the
938 // current BB. Note that we ignore the value computed by the body, but don't
943 // Emit the step value.
946 StepVal = Step->IRGen(C);
947 if (!StepVal) return nullptr;
949 // If not specified, use 1.0.
950 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
953 // Compute the end condition.
954 Value *EndCond = End->IRGen(C);
955 if (EndCond == 0) return EndCond;
957 // Reload, increment, and restore the alloca. This handles the case where
958 // the body of the loop mutates the variable.
959 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
960 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
961 C.getBuilder().CreateStore(NextVar, Alloca);
963 // Convert condition to a bool by comparing equal to 0.0.
964 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
965 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
968 // Create the "after loop" block and insert it.
969 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
971 // Insert the conditional branch into the end of LoopEndBB.
972 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
974 // Any new code will be inserted in AfterBB.
975 C.getBuilder().SetInsertPoint(AfterBB);
977 // Restore the unshadowed variable.
979 C.NamedValues[VarName] = OldVal;
981 C.NamedValues.erase(VarName);
984 // for expr always returns 0.0.
985 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
988 Value *VarExprAST::IRGen(IRGenContext &C) const {
989 std::vector<AllocaInst *> OldBindings;
991 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
993 // Register all variables and emit their initializer.
994 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
995 auto &VarName = VarBindings[i].first;
996 auto &Init = VarBindings[i].second;
998 // Emit the initializer before adding the variable to scope, this prevents
999 // the initializer from referencing the variable itself, and permits stuff
1002 // var a = a in ... # refers to outer 'a'.
1005 InitVal = Init->IRGen(C);
1006 if (!InitVal) return nullptr;
1007 } else // If not specified, use 0.0.
1008 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1010 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1011 C.getBuilder().CreateStore(InitVal, Alloca);
1013 // Remember the old variable binding so that we can restore the binding when
1015 OldBindings.push_back(C.NamedValues[VarName]);
1017 // Remember this binding.
1018 C.NamedValues[VarName] = Alloca;
1021 // Codegen the body, now that all vars are in scope.
1022 Value *BodyVal = Body->IRGen(C);
1023 if (!BodyVal) return nullptr;
1025 // Pop all our variables from scope.
1026 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1027 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1029 // Return the body computation.
1033 Function *PrototypeAST::IRGen(IRGenContext &C) const {
1034 std::string FnName = MakeLegalFunctionName(Name);
1036 // Make the function type: double(double,double) etc.
1037 std::vector<Type*> Doubles(Args.size(),
1038 Type::getDoubleTy(getGlobalContext()));
1039 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1041 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1044 // If F conflicted, there was already something named 'FnName'. If it has a
1045 // body, don't allow redefinition or reextern.
1046 if (F->getName() != FnName) {
1047 // Delete the one we just made and get the existing one.
1048 F->eraseFromParent();
1049 F = C.getM().getFunction(Name);
1051 // If F already has a body, reject this.
1053 ErrorP<Function>("redefinition of function");
1057 // If F took a different number of args, reject.
1058 if (F->arg_size() != Args.size()) {
1059 ErrorP<Function>("redefinition of function with different # args");
1064 // Set names for all arguments.
1066 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1068 AI->setName(Args[Idx]);
1073 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1074 /// argument in the symbol table so that references to it will succeed.
1075 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1076 Function::arg_iterator AI = F->arg_begin();
1077 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1078 // Create an alloca for this variable.
1079 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1081 // Store the initial value into the alloca.
1082 C.getBuilder().CreateStore(AI, Alloca);
1084 // Add arguments to variable symbol table.
1085 C.NamedValues[Args[Idx]] = Alloca;
1089 Function *FunctionAST::IRGen(IRGenContext &C) const {
1090 C.NamedValues.clear();
1092 Function *TheFunction = Proto->IRGen(C);
1096 // If this is an operator, install it.
1097 if (Proto->isBinaryOp())
1098 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1100 // Create a new basic block to start insertion into.
1101 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1102 C.getBuilder().SetInsertPoint(BB);
1104 // Add all arguments to the symbol table and create their allocas.
1105 Proto->CreateArgumentAllocas(TheFunction, C);
1107 if (Value *RetVal = Body->IRGen(C)) {
1108 // Finish off the function.
1109 C.getBuilder().CreateRet(RetVal);
1111 // Validate the generated code, checking for consistency.
1112 verifyFunction(*TheFunction);
1117 // Error reading body, remove function.
1118 TheFunction->eraseFromParent();
1120 if (Proto->isBinaryOp())
1121 BinopPrecedence.erase(Proto->getOperatorName());
1125 //===----------------------------------------------------------------------===//
1126 // Top-Level parsing and JIT Driver
1127 //===----------------------------------------------------------------------===//
1129 static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1130 const FunctionAST &F) {
1132 auto LF = F.IRGen(C);
1135 #ifndef MINIMAL_STDERR_OUTPUT
1136 fprintf(stderr, "Read function definition:");
1142 class KaleidoscopeJIT {
1144 typedef ObjectLinkingLayer<> ObjLayerT;
1145 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1146 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1148 typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1150 std::string Mangle(const std::string &Name) {
1151 std::string MangledName;
1153 raw_string_ostream MangledNameStream(MangledName);
1154 Mang.getNameWithPrefix(MangledNameStream, Name);
1159 KaleidoscopeJIT(SessionContext &Session)
1160 : TM(EngineBuilder().selectTarget()),
1161 Mang(TM->getDataLayout()), Session(Session),
1162 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
1163 LazyEmitLayer(CompileLayer) {}
1165 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1166 if (!M->getDataLayout())
1167 M->setDataLayout(TM->getDataLayout());
1169 // The LazyEmitLayer takes lists of modules, rather than single modules, so
1170 // we'll just build a single-element list.
1171 std::vector<std::unique_ptr<Module>> S;
1172 S.push_back(std::move(M));
1174 // We need a memory manager to allocate memory and resolve symbols for this
1175 // new module. Create one that resolves symbols by looking back into the JIT.
1176 auto MM = createLookasideRTDyldMM<SectionMemoryManager>(
1177 [&](const std::string &Name) -> uint64_t {
1178 // First try to find 'Name' within the JIT.
1179 if (auto Symbol = findMangledSymbol(Name))
1180 return Symbol.getAddress();
1182 // If we don't find 'Name' in the JIT, see if we have some AST
1184 auto DefI = Session.FunctionDefs.find(Name);
1185 if (DefI == Session.FunctionDefs.end())
1188 // We have AST for 'Name'. IRGen it, add it to the JIT, and
1189 // return the address for it.
1190 // FIXME: What happens if IRGen fails?
1191 addModule(IRGen(Session, *DefI->second));
1193 // Remove the function definition's AST now that we've
1194 // finished with it.
1195 Session.FunctionDefs.erase(DefI);
1197 return findMangledSymbol(Name).getAddress();
1199 [](const std::string &S) { return 0; } );
1201 return LazyEmitLayer.addModuleSet(std::move(S), std::move(MM));
1204 void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1206 JITSymbol findMangledSymbol(const std::string &Name) {
1207 return LazyEmitLayer.findSymbol(Name, false);
1210 JITSymbol findSymbol(const std::string &Name) {
1211 return findMangledSymbol(Mangle(Name));
1216 std::unique_ptr<TargetMachine> TM;
1218 SessionContext &Session;
1220 ObjLayerT ObjectLayer;
1221 CompileLayerT CompileLayer;
1222 LazyEmitLayerT LazyEmitLayer;
1225 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1226 if (auto F = ParseDefinition()) {
1227 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1228 S.FunctionDefs[J.Mangle(F->Proto->Name)] = std::move(F);
1230 // Skip token for error recovery.
1235 static void HandleExtern(SessionContext &S) {
1236 if (auto P = ParseExtern())
1237 S.addPrototypeAST(std::move(P));
1239 // Skip token for error recovery.
1244 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1245 // Evaluate a top-level expression into an anonymous function.
1246 if (auto F = ParseTopLevelExpr()) {
1248 if (auto ExprFunc = F->IRGen(C)) {
1249 #ifndef MINIMAL_STDERR_OUTPUT
1250 std::cerr << "Expression function:\n";
1253 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1254 // this module as soon as we've executed Function ExprFunc.
1255 auto H = J.addModule(C.takeM());
1257 // Get the address of the JIT'd function in memory.
1258 auto ExprSymbol = J.findSymbol("__anon_expr");
1260 // Cast it to the right type (takes no arguments, returns a double) so we
1261 // can call it as a native function.
1262 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1263 #ifdef MINIMAL_STDERR_OUTPUT
1266 std::cerr << "Evaluated to " << FP() << "\n";
1269 // Remove the function.
1273 // Skip token for error recovery.
1278 /// top ::= definition | external | expression | ';'
1279 static void MainLoop() {
1280 SessionContext S(getGlobalContext());
1281 KaleidoscopeJIT J(S);
1285 case tok_eof: return;
1286 case ';': getNextToken(); continue; // ignore top-level semicolons.
1287 case tok_def: HandleDefinition(S, J); break;
1288 case tok_extern: HandleExtern(S); break;
1289 default: HandleTopLevelExpression(S, J); break;
1291 #ifndef MINIMAL_STDERR_OUTPUT
1292 std::cerr << "ready> ";
1297 //===----------------------------------------------------------------------===//
1298 // "Library" functions that can be "extern'd" from user code.
1299 //===----------------------------------------------------------------------===//
1301 /// putchard - putchar that takes a double and returns 0.
1303 double putchard(double X) {
1308 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1310 double printd(double X) {
1321 //===----------------------------------------------------------------------===//
1322 // Main driver code.
1323 //===----------------------------------------------------------------------===//
1326 InitializeNativeTarget();
1327 InitializeNativeTargetAsmPrinter();
1328 InitializeNativeTargetAsmParser();
1330 // Install standard binary operators.
1331 // 1 is lowest precedence.
1332 BinopPrecedence['='] = 2;
1333 BinopPrecedence['<'] = 10;
1334 BinopPrecedence['+'] = 20;
1335 BinopPrecedence['-'] = 20;
1336 BinopPrecedence['/'] = 40;
1337 BinopPrecedence['*'] = 40; // highest.
1339 // Prime the first token.
1340 #ifndef MINIMAL_STDERR_OUTPUT
1341 std::cerr << "ready> ";
1345 std::cerr << std::fixed;
1347 // Run the main "interpreter loop" now.