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/ExecutionEngine/Orc/OrcTargetSupport.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LegacyPassManager.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
30 // of these for known things.
35 tok_def = -2, tok_extern = -3,
38 tok_identifier = -4, tok_number = -5,
41 tok_if = -6, tok_then = -7, tok_else = -8,
42 tok_for = -9, tok_in = -10,
45 tok_binary = -11, tok_unary = -12,
51 static std::string IdentifierStr; // Filled in if tok_identifier
52 static double NumVal; // Filled in if tok_number
54 /// gettok - Return the next token from standard input.
56 static int LastChar = ' ';
58 // Skip any whitespace.
59 while (isspace(LastChar))
62 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
63 IdentifierStr = LastChar;
64 while (isalnum((LastChar = getchar())))
65 IdentifierStr += LastChar;
67 if (IdentifierStr == "def") return tok_def;
68 if (IdentifierStr == "extern") return tok_extern;
69 if (IdentifierStr == "if") return tok_if;
70 if (IdentifierStr == "then") return tok_then;
71 if (IdentifierStr == "else") return tok_else;
72 if (IdentifierStr == "for") return tok_for;
73 if (IdentifierStr == "in") return tok_in;
74 if (IdentifierStr == "binary") return tok_binary;
75 if (IdentifierStr == "unary") return tok_unary;
76 if (IdentifierStr == "var") return tok_var;
77 return tok_identifier;
80 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
85 } while (isdigit(LastChar) || LastChar == '.');
87 NumVal = strtod(NumStr.c_str(), 0);
91 if (LastChar == '#') {
92 // Comment until end of line.
93 do LastChar = getchar();
94 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
100 // Check for end of file. Don't eat the EOF.
104 // Otherwise, just return the character as its ascii value.
105 int ThisChar = LastChar;
106 LastChar = getchar();
110 //===----------------------------------------------------------------------===//
111 // Abstract Syntax Tree (aka Parse Tree)
112 //===----------------------------------------------------------------------===//
116 /// ExprAST - Base class for all expression nodes.
118 virtual ~ExprAST() {}
119 virtual Value *IRGen(IRGenContext &C) const = 0;
122 /// NumberExprAST - Expression class for numeric literals like "1.0".
123 struct NumberExprAST : public ExprAST {
124 NumberExprAST(double Val) : Val(Val) {}
125 Value *IRGen(IRGenContext &C) const override;
130 /// VariableExprAST - Expression class for referencing a variable, like "a".
131 struct VariableExprAST : public ExprAST {
132 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
133 Value *IRGen(IRGenContext &C) const override;
138 /// UnaryExprAST - Expression class for a unary operator.
139 struct UnaryExprAST : public ExprAST {
140 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
141 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
143 Value *IRGen(IRGenContext &C) const override;
146 std::unique_ptr<ExprAST> Operand;
149 /// BinaryExprAST - Expression class for a binary operator.
150 struct BinaryExprAST : public ExprAST {
151 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
152 std::unique_ptr<ExprAST> RHS)
153 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
155 Value *IRGen(IRGenContext &C) const override;
158 std::unique_ptr<ExprAST> LHS, RHS;
161 /// CallExprAST - Expression class for function calls.
162 struct CallExprAST : public ExprAST {
163 CallExprAST(std::string CalleeName,
164 std::vector<std::unique_ptr<ExprAST>> Args)
165 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
167 Value *IRGen(IRGenContext &C) const override;
169 std::string CalleeName;
170 std::vector<std::unique_ptr<ExprAST>> Args;
173 /// IfExprAST - Expression class for if/then/else.
174 struct IfExprAST : public ExprAST {
175 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
176 std::unique_ptr<ExprAST> Else)
177 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
178 Value *IRGen(IRGenContext &C) const override;
180 std::unique_ptr<ExprAST> Cond, Then, Else;
183 /// ForExprAST - Expression class for for/in.
184 struct ForExprAST : public ExprAST {
185 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
186 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
187 std::unique_ptr<ExprAST> Body)
188 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
189 Step(std::move(Step)), Body(std::move(Body)) {}
191 Value *IRGen(IRGenContext &C) const override;
194 std::unique_ptr<ExprAST> Start, End, Step, Body;
197 /// VarExprAST - Expression class for var/in
198 struct VarExprAST : public ExprAST {
199 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
200 typedef std::vector<Binding> BindingList;
202 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
203 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
205 Value *IRGen(IRGenContext &C) const override;
207 BindingList VarBindings;
208 std::unique_ptr<ExprAST> Body;
211 /// PrototypeAST - This class represents the "prototype" for a function,
212 /// which captures its argument names as well as if it is an operator.
213 struct PrototypeAST {
214 PrototypeAST(std::string Name, std::vector<std::string> Args,
215 bool IsOperator = false, unsigned Precedence = 0)
216 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
217 Precedence(Precedence) {}
219 Function *IRGen(IRGenContext &C) const;
220 void CreateArgumentAllocas(Function *F, IRGenContext &C);
222 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
223 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
225 char getOperatorName() const {
226 assert(isUnaryOp() || isBinaryOp());
227 return Name[Name.size()-1];
231 std::vector<std::string> Args;
233 unsigned Precedence; // Precedence if a binary op.
236 /// FunctionAST - This class represents a function definition itself.
238 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
239 std::unique_ptr<ExprAST> Body)
240 : Proto(std::move(Proto)), Body(std::move(Body)) {}
242 Function *IRGen(IRGenContext &C) const;
244 std::unique_ptr<PrototypeAST> Proto;
245 std::unique_ptr<ExprAST> Body;
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() {
257 return CurTok = gettok();
260 /// BinopPrecedence - This holds the precedence for each binary operator that is
262 static std::map<char, int> BinopPrecedence;
264 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
265 static int GetTokPrecedence() {
266 if (!isascii(CurTok))
269 // Make sure it's a declared binop.
270 int TokPrec = BinopPrecedence[CurTok];
271 if (TokPrec <= 0) return -1;
275 template <typename T>
276 std::unique_ptr<T> ErrorU(const std::string &Str) {
277 std::cerr << "Error: " << Str << "\n";
281 template <typename T>
282 T* ErrorP(const std::string &Str) {
283 std::cerr << "Error: " << Str << "\n";
287 static std::unique_ptr<ExprAST> ParseExpression();
291 /// ::= identifier '(' expression* ')'
292 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
293 std::string IdName = IdentifierStr;
295 getNextToken(); // eat identifier.
297 if (CurTok != '(') // Simple variable ref.
298 return llvm::make_unique<VariableExprAST>(IdName);
301 getNextToken(); // eat (
302 std::vector<std::unique_ptr<ExprAST>> Args;
305 auto Arg = ParseExpression();
306 if (!Arg) return nullptr;
307 Args.push_back(std::move(Arg));
309 if (CurTok == ')') break;
312 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
320 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
323 /// numberexpr ::= number
324 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
325 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
326 getNextToken(); // consume the number
330 /// parenexpr ::= '(' expression ')'
331 static std::unique_ptr<ExprAST> ParseParenExpr() {
332 getNextToken(); // eat (.
333 auto V = ParseExpression();
338 return ErrorU<ExprAST>("expected ')'");
339 getNextToken(); // eat ).
343 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
344 static std::unique_ptr<ExprAST> ParseIfExpr() {
345 getNextToken(); // eat the if.
348 auto Cond = ParseExpression();
352 if (CurTok != tok_then)
353 return ErrorU<ExprAST>("expected then");
354 getNextToken(); // eat the then
356 auto Then = ParseExpression();
360 if (CurTok != tok_else)
361 return ErrorU<ExprAST>("expected else");
365 auto Else = ParseExpression();
369 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
373 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
374 static std::unique_ptr<ForExprAST> ParseForExpr() {
375 getNextToken(); // eat the for.
377 if (CurTok != tok_identifier)
378 return ErrorU<ForExprAST>("expected identifier after for");
380 std::string IdName = IdentifierStr;
381 getNextToken(); // eat identifier.
384 return ErrorU<ForExprAST>("expected '=' after for");
385 getNextToken(); // eat '='.
388 auto Start = ParseExpression();
392 return ErrorU<ForExprAST>("expected ',' after for start value");
395 auto End = ParseExpression();
399 // The step value is optional.
400 std::unique_ptr<ExprAST> Step;
403 Step = ParseExpression();
408 if (CurTok != tok_in)
409 return ErrorU<ForExprAST>("expected 'in' after for");
410 getNextToken(); // eat 'in'.
412 auto Body = ParseExpression();
416 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
417 std::move(Step), std::move(Body));
420 /// varexpr ::= 'var' identifier ('=' expression)?
421 // (',' identifier ('=' expression)?)* 'in' expression
422 static std::unique_ptr<VarExprAST> ParseVarExpr() {
423 getNextToken(); // eat the var.
425 VarExprAST::BindingList VarBindings;
427 // At least one variable name is required.
428 if (CurTok != tok_identifier)
429 return ErrorU<VarExprAST>("expected identifier after var");
432 std::string Name = IdentifierStr;
433 getNextToken(); // eat identifier.
435 // Read the optional initializer.
436 std::unique_ptr<ExprAST> Init;
438 getNextToken(); // eat the '='.
440 Init = ParseExpression();
445 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
447 // End of var list, exit loop.
448 if (CurTok != ',') break;
449 getNextToken(); // eat the ','.
451 if (CurTok != tok_identifier)
452 return ErrorU<VarExprAST>("expected identifier list after var");
455 // At this point, we have to have 'in'.
456 if (CurTok != tok_in)
457 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
458 getNextToken(); // eat 'in'.
460 auto Body = ParseExpression();
464 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
468 /// ::= identifierexpr
474 static std::unique_ptr<ExprAST> ParsePrimary() {
476 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
477 case tok_identifier: return ParseIdentifierExpr();
478 case tok_number: return ParseNumberExpr();
479 case '(': return ParseParenExpr();
480 case tok_if: return ParseIfExpr();
481 case tok_for: return ParseForExpr();
482 case tok_var: return ParseVarExpr();
489 static std::unique_ptr<ExprAST> ParseUnary() {
490 // If the current token is not an operator, it must be a primary expr.
491 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
492 return ParsePrimary();
494 // If this is a unary operator, read it.
497 if (auto Operand = ParseUnary())
498 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
504 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
505 std::unique_ptr<ExprAST> LHS) {
506 // If this is a binop, find its precedence.
508 int TokPrec = GetTokPrecedence();
510 // If this is a binop that binds at least as tightly as the current binop,
511 // consume it, otherwise we are done.
512 if (TokPrec < ExprPrec)
515 // Okay, we know this is a binop.
517 getNextToken(); // eat binop
519 // Parse the unary expression after the binary operator.
520 auto RHS = ParseUnary();
524 // If BinOp binds less tightly with RHS than the operator after RHS, let
525 // the pending operator take RHS as its LHS.
526 int NextPrec = GetTokPrecedence();
527 if (TokPrec < NextPrec) {
528 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
534 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
539 /// ::= unary binoprhs
541 static std::unique_ptr<ExprAST> ParseExpression() {
542 auto LHS = ParseUnary();
546 return ParseBinOpRHS(0, std::move(LHS));
550 /// ::= id '(' id* ')'
551 /// ::= binary LETTER number? (id, id)
552 /// ::= unary LETTER (id)
553 static std::unique_ptr<PrototypeAST> ParsePrototype() {
556 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
557 unsigned BinaryPrecedence = 30;
561 return ErrorU<PrototypeAST>("Expected function name in prototype");
563 FnName = IdentifierStr;
569 if (!isascii(CurTok))
570 return ErrorU<PrototypeAST>("Expected unary operator");
572 FnName += (char)CurTok;
578 if (!isascii(CurTok))
579 return ErrorU<PrototypeAST>("Expected binary operator");
581 FnName += (char)CurTok;
585 // Read the precedence if present.
586 if (CurTok == tok_number) {
587 if (NumVal < 1 || NumVal > 100)
588 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
589 BinaryPrecedence = (unsigned)NumVal;
596 return ErrorU<PrototypeAST>("Expected '(' in prototype");
598 std::vector<std::string> ArgNames;
599 while (getNextToken() == tok_identifier)
600 ArgNames.push_back(IdentifierStr);
602 return ErrorU<PrototypeAST>("Expected ')' in prototype");
605 getNextToken(); // eat ')'.
607 // Verify right number of names for operator.
608 if (Kind && ArgNames.size() != Kind)
609 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
611 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
615 /// definition ::= 'def' prototype expression
616 static std::unique_ptr<FunctionAST> ParseDefinition() {
617 getNextToken(); // eat def.
618 auto Proto = ParsePrototype();
622 if (auto Body = ParseExpression())
623 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
627 /// toplevelexpr ::= expression
628 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
629 if (auto E = ParseExpression()) {
630 // Make an anonymous proto.
632 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
633 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
638 /// external ::= 'extern' prototype
639 static std::unique_ptr<PrototypeAST> ParseExtern() {
640 getNextToken(); // eat extern.
641 return ParsePrototype();
644 //===----------------------------------------------------------------------===//
646 //===----------------------------------------------------------------------===//
648 // FIXME: Obviously we can do better than this
649 std::string GenerateUniqueName(const std::string &Root) {
651 std::ostringstream NameStream;
652 NameStream << Root << ++i;
653 return NameStream.str();
656 std::string MakeLegalFunctionName(std::string Name)
659 assert(!Name.empty() && "Base name must not be empty");
661 // Start with what we have
664 // Look for a numberic first character
665 if (NewName.find_first_of("0123456789") == 0) {
666 NewName.insert(0, 1, 'n');
669 // Replace illegal characters with their ASCII equivalent
670 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
672 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
673 std::ostringstream NumStream;
674 NumStream << (int)NewName.at(pos);
675 NewName = NewName.replace(pos, 1, NumStream.str());
681 class SessionContext {
683 SessionContext(LLVMContext &C) : Context(C) {}
684 LLVMContext& getLLVMContext() const { return Context; }
685 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
686 PrototypeAST* getPrototypeAST(const std::string &Name);
687 std::map<std::string, std::unique_ptr<FunctionAST>> FunctionDefs;
689 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
690 LLVMContext &Context;
691 PrototypeMap Prototypes;
694 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
695 Prototypes[P->Name] = std::move(P);
698 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
699 PrototypeMap::iterator I = Prototypes.find(Name);
700 if (I != Prototypes.end())
701 return I->second.get();
708 IRGenContext(SessionContext &S)
710 M(new Module(GenerateUniqueName("jit_module_"),
711 Session.getLLVMContext())),
712 Builder(Session.getLLVMContext()) {}
714 SessionContext& getSession() { return Session; }
715 Module& getM() const { return *M; }
716 std::unique_ptr<Module> takeM() { return std::move(M); }
717 IRBuilder<>& getBuilder() { return Builder; }
718 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
719 Function* getPrototype(const std::string &Name);
721 std::map<std::string, AllocaInst*> NamedValues;
723 SessionContext &Session;
724 std::unique_ptr<Module> M;
728 Function* IRGenContext::getPrototype(const std::string &Name) {
729 if (Function *ExistingProto = M->getFunction(Name))
730 return ExistingProto;
731 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
732 return ProtoAST->IRGen(*this);
736 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
737 /// the function. This is used for mutable variables etc.
738 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
739 const std::string &VarName) {
740 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
741 TheFunction->getEntryBlock().begin());
742 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
746 Value *NumberExprAST::IRGen(IRGenContext &C) const {
747 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
750 Value *VariableExprAST::IRGen(IRGenContext &C) const {
751 // Look this variable up in the function.
752 Value *V = C.NamedValues[Name];
755 return ErrorP<Value>("Unknown variable name '" + Name + "'");
758 return C.getBuilder().CreateLoad(V, Name.c_str());
761 Value *UnaryExprAST::IRGen(IRGenContext &C) const {
762 if (Value *OperandV = Operand->IRGen(C)) {
763 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
764 if (Function *F = C.getPrototype(FnName))
765 return C.getBuilder().CreateCall(F, OperandV, "unop");
766 return ErrorP<Value>("Unknown unary operator");
769 // Could not codegen operand - return null.
773 Value *BinaryExprAST::IRGen(IRGenContext &C) const {
774 // Special case '=' because we don't want to emit the LHS as an expression.
776 // Assignment requires the LHS to be an identifier.
777 auto LHSVar = static_cast<VariableExprAST&>(*LHS);
779 Value *Val = RHS->IRGen(C);
780 if (!Val) return nullptr;
783 if (auto Variable = C.NamedValues[LHSVar.Name]) {
784 C.getBuilder().CreateStore(Val, Variable);
787 return ErrorP<Value>("Unknown variable name");
790 Value *L = LHS->IRGen(C);
791 Value *R = RHS->IRGen(C);
792 if (!L || !R) return nullptr;
795 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
796 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
797 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
798 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
800 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
801 // Convert bool 0/1 to double 0.0 or 1.0
802 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
807 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
809 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
810 if (Function *F = C.getPrototype(FnName)) {
811 Value *Ops[] = { L, R };
812 return C.getBuilder().CreateCall(F, Ops, "binop");
815 return ErrorP<Value>("Unknown binary operator");
818 Value *CallExprAST::IRGen(IRGenContext &C) const {
819 // Look up the name in the global module table.
820 if (auto CalleeF = C.getPrototype(CalleeName)) {
821 // If argument mismatch error.
822 if (CalleeF->arg_size() != Args.size())
823 return ErrorP<Value>("Incorrect # arguments passed");
825 std::vector<Value*> ArgsV;
826 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
827 ArgsV.push_back(Args[i]->IRGen(C));
828 if (!ArgsV.back()) return nullptr;
831 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
834 return ErrorP<Value>("Unknown function referenced");
837 Value *IfExprAST::IRGen(IRGenContext &C) const {
838 Value *CondV = Cond->IRGen(C);
839 if (!CondV) return nullptr;
841 // Convert condition to a bool by comparing equal to 0.0.
843 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
844 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
846 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
848 // Create blocks for the then and else cases. Insert the 'then' block at the
849 // end of the function.
850 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
851 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
852 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
854 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
857 C.getBuilder().SetInsertPoint(ThenBB);
859 Value *ThenV = Then->IRGen(C);
860 if (!ThenV) return nullptr;
862 C.getBuilder().CreateBr(MergeBB);
863 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
864 ThenBB = C.getBuilder().GetInsertBlock();
867 TheFunction->getBasicBlockList().push_back(ElseBB);
868 C.getBuilder().SetInsertPoint(ElseBB);
870 Value *ElseV = Else->IRGen(C);
871 if (!ElseV) return nullptr;
873 C.getBuilder().CreateBr(MergeBB);
874 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
875 ElseBB = C.getBuilder().GetInsertBlock();
878 TheFunction->getBasicBlockList().push_back(MergeBB);
879 C.getBuilder().SetInsertPoint(MergeBB);
880 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
883 PN->addIncoming(ThenV, ThenBB);
884 PN->addIncoming(ElseV, ElseBB);
888 Value *ForExprAST::IRGen(IRGenContext &C) const {
890 // var = alloca double
893 // store start -> var
904 // nextvar = curvar + step
905 // store nextvar -> var
906 // br endcond, loop, endloop
909 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
911 // Create an alloca for the variable in the entry block.
912 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
914 // Emit the start code first, without 'variable' in scope.
915 Value *StartVal = Start->IRGen(C);
916 if (!StartVal) return nullptr;
918 // Store the value into the alloca.
919 C.getBuilder().CreateStore(StartVal, Alloca);
921 // Make the new basic block for the loop header, inserting after current
923 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
925 // Insert an explicit fall through from the current block to the LoopBB.
926 C.getBuilder().CreateBr(LoopBB);
928 // Start insertion in LoopBB.
929 C.getBuilder().SetInsertPoint(LoopBB);
931 // Within the loop, the variable is defined equal to the PHI node. If it
932 // shadows an existing variable, we have to restore it, so save it now.
933 AllocaInst *OldVal = C.NamedValues[VarName];
934 C.NamedValues[VarName] = Alloca;
936 // Emit the body of the loop. This, like any other expr, can change the
937 // current BB. Note that we ignore the value computed by the body, but don't
942 // Emit the step value.
945 StepVal = Step->IRGen(C);
946 if (!StepVal) return nullptr;
948 // If not specified, use 1.0.
949 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
952 // Compute the end condition.
953 Value *EndCond = End->IRGen(C);
954 if (EndCond == 0) return EndCond;
956 // Reload, increment, and restore the alloca. This handles the case where
957 // the body of the loop mutates the variable.
958 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
959 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
960 C.getBuilder().CreateStore(NextVar, Alloca);
962 // Convert condition to a bool by comparing equal to 0.0.
963 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
964 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
967 // Create the "after loop" block and insert it.
968 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
970 // Insert the conditional branch into the end of LoopEndBB.
971 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
973 // Any new code will be inserted in AfterBB.
974 C.getBuilder().SetInsertPoint(AfterBB);
976 // Restore the unshadowed variable.
978 C.NamedValues[VarName] = OldVal;
980 C.NamedValues.erase(VarName);
983 // for expr always returns 0.0.
984 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
987 Value *VarExprAST::IRGen(IRGenContext &C) const {
988 std::vector<AllocaInst *> OldBindings;
990 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
992 // Register all variables and emit their initializer.
993 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
994 auto &VarName = VarBindings[i].first;
995 auto &Init = VarBindings[i].second;
997 // Emit the initializer before adding the variable to scope, this prevents
998 // the initializer from referencing the variable itself, and permits stuff
1001 // var a = a in ... # refers to outer 'a'.
1004 InitVal = Init->IRGen(C);
1005 if (!InitVal) return nullptr;
1006 } else // If not specified, use 0.0.
1007 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1009 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1010 C.getBuilder().CreateStore(InitVal, Alloca);
1012 // Remember the old variable binding so that we can restore the binding when
1014 OldBindings.push_back(C.NamedValues[VarName]);
1016 // Remember this binding.
1017 C.NamedValues[VarName] = Alloca;
1020 // Codegen the body, now that all vars are in scope.
1021 Value *BodyVal = Body->IRGen(C);
1022 if (!BodyVal) return nullptr;
1024 // Pop all our variables from scope.
1025 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1026 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1028 // Return the body computation.
1032 Function *PrototypeAST::IRGen(IRGenContext &C) const {
1033 std::string FnName = MakeLegalFunctionName(Name);
1035 // Make the function type: double(double,double) etc.
1036 std::vector<Type*> Doubles(Args.size(),
1037 Type::getDoubleTy(getGlobalContext()));
1038 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1040 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1043 // If F conflicted, there was already something named 'FnName'. If it has a
1044 // body, don't allow redefinition or reextern.
1045 if (F->getName() != FnName) {
1046 // Delete the one we just made and get the existing one.
1047 F->eraseFromParent();
1048 F = C.getM().getFunction(Name);
1050 // If F already has a body, reject this.
1052 ErrorP<Function>("redefinition of function");
1056 // If F took a different number of args, reject.
1057 if (F->arg_size() != Args.size()) {
1058 ErrorP<Function>("redefinition of function with different # args");
1063 // Set names for all arguments.
1065 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1067 AI->setName(Args[Idx]);
1072 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1073 /// argument in the symbol table so that references to it will succeed.
1074 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1075 Function::arg_iterator AI = F->arg_begin();
1076 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1077 // Create an alloca for this variable.
1078 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1080 // Store the initial value into the alloca.
1081 C.getBuilder().CreateStore(AI, Alloca);
1083 // Add arguments to variable symbol table.
1084 C.NamedValues[Args[Idx]] = Alloca;
1088 Function *FunctionAST::IRGen(IRGenContext &C) const {
1089 C.NamedValues.clear();
1091 Function *TheFunction = Proto->IRGen(C);
1095 // If this is an operator, install it.
1096 if (Proto->isBinaryOp())
1097 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1099 // Create a new basic block to start insertion into.
1100 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1101 C.getBuilder().SetInsertPoint(BB);
1103 // Add all arguments to the symbol table and create their allocas.
1104 Proto->CreateArgumentAllocas(TheFunction, C);
1106 if (Value *RetVal = Body->IRGen(C)) {
1107 // Finish off the function.
1108 C.getBuilder().CreateRet(RetVal);
1110 // Validate the generated code, checking for consistency.
1111 verifyFunction(*TheFunction);
1116 // Error reading body, remove function.
1117 TheFunction->eraseFromParent();
1119 if (Proto->isBinaryOp())
1120 BinopPrecedence.erase(Proto->getOperatorName());
1124 //===----------------------------------------------------------------------===//
1125 // Top-Level parsing and JIT Driver
1126 //===----------------------------------------------------------------------===//
1128 static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1129 const FunctionAST &F) {
1131 auto LF = F.IRGen(C);
1134 #ifndef MINIMAL_STDERR_OUTPUT
1135 fprintf(stderr, "Read function definition:");
1142 static void EarthShatteringKaboom() {
1143 fprintf(stderr, "Earth shattering kaboom.");
1147 class KaleidoscopeJIT {
1149 typedef ObjectLinkingLayer<> ObjLayerT;
1150 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1151 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1153 typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1155 std::string Mangle(const std::string &Name) {
1156 std::string MangledName;
1158 raw_string_ostream MangledNameStream(MangledName);
1159 Mang.getNameWithPrefix(MangledNameStream, Name);
1164 KaleidoscopeJIT(SessionContext &Session)
1165 : TM(EngineBuilder().selectTarget()),
1166 Mang(TM->getDataLayout()), Session(Session),
1168 [](){ return llvm::make_unique<SectionMemoryManager>(); }),
1169 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
1170 LazyEmitLayer(CompileLayer),
1171 CompileCallbacks(LazyEmitLayer, Session.getLLVMContext(),
1172 reinterpret_cast<uintptr_t>(EarthShatteringKaboom),
1175 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1176 if (!M->getDataLayout())
1177 M->setDataLayout(TM->getDataLayout());
1179 // The LazyEmitLayer takes lists of modules, rather than single modules, so
1180 // we'll just build a single-element list.
1181 std::vector<std::unique_ptr<Module>> S;
1182 S.push_back(std::move(M));
1184 // We need a memory manager to allocate memory and resolve symbols for this
1185 // new module. Create one that resolves symbols by looking back into the JIT.
1186 auto MM = createLookasideRTDyldMM<SectionMemoryManager>(
1187 [&](const std::string &Name) -> uint64_t {
1188 // First try to find 'Name' within the JIT.
1189 if (auto Symbol = findMangledSymbol(Name))
1190 return Symbol.getAddress();
1192 // If we don't find 'Name' in the JIT, see if we have some AST
1194 auto DefI = Session.FunctionDefs.find(Name);
1195 if (DefI == Session.FunctionDefs.end())
1198 // We have AST for 'Name'. IRGen it, add it to the JIT, and
1199 // return the address for it.
1200 // FIXME: What happens if IRGen fails?
1201 addModule(IRGen(Session, *DefI->second));
1203 // Remove the function definition's AST now that we've
1204 // finished with it.
1205 Session.FunctionDefs.erase(DefI);
1207 return findMangledSymbol(Name).getAddress();
1209 [](const std::string &S) { return 0; } );
1211 return LazyEmitLayer.addModuleSet(std::move(S), std::move(MM));
1214 void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1216 JITSymbol findMangledSymbol(const std::string &Name) {
1217 return LazyEmitLayer.findSymbol(Name, true);
1220 JITSymbol findSymbol(const std::string &Name) {
1221 return findMangledSymbol(Mangle(Name));
1224 JITSymbol findMangledSymbolIn(LazyEmitLayerT::ModuleSetHandleT H,
1225 const std::string &Name) {
1226 return LazyEmitLayer.findSymbolIn(H, Name, true);
1229 JITSymbol findSymbolIn(LazyEmitLayerT::ModuleSetHandleT H,
1230 const std::string &Name) {
1231 return findMangledSymbolIn(H, Mangle(Name));
1234 void addFunctionDefinition(std::unique_ptr<FunctionAST> FnAST) {
1235 // Step 1) IRGen a prototype for this function:
1236 IRGenContext C(Session);
1237 Function *F = FnAST->Proto->IRGen(C);
1238 C.getM().setDataLayout(TM->getDataLayout());
1240 // Step 2) Create a compile callback that will be used to compile this
1241 // function when it is first called.
1243 CompileCallbacks.getCompileCallback(*F->getFunctionType());
1245 // Step 3) Create a stub that will indirectly call the body of this
1246 // function. Initialize the function pointer for the indirection to
1247 // point at the compile callback.
1248 std::string BodyPtrName = (F->getName() + "$address").str();
1249 GlobalVariable *FunctionBodyPointer =
1250 createImplPointer(*F, BodyPtrName, CallbackInfo.getAddress());
1251 makeStub(*F, *FunctionBodyPointer);
1253 // Step 3) Add the module to the JIT.
1254 auto H = addModule(C.takeM());
1256 // Step 4) Set the compile and update actions for the callback. The compile
1257 // action will IRGen and Codegen the function. The update action
1258 // will update FunctionBodyPointer to point at the newly compiled
1259 // function pointer.
1261 // FIXME: Use generalized capture for FnAST when we get C++14 support.
1262 FunctionAST *FnASTPtr = FnAST.release();
1263 CallbackInfo.setCompileAction([this,FnASTPtr](){
1264 std::unique_ptr<FunctionAST> Fn(FnASTPtr);
1265 auto H = addModule(IRGen(Session, *Fn));
1266 return findSymbolIn(H, Fn->Proto->Name).getAddress();
1268 CallbackInfo.setUpdateAction(
1269 CompileCallbacks.getLocalFPUpdater(H, BodyPtrName));
1274 std::unique_ptr<TargetMachine> TM;
1276 SessionContext &Session;
1278 ObjLayerT ObjectLayer;
1279 CompileLayerT CompileLayer;
1280 LazyEmitLayerT LazyEmitLayer;
1282 JITCompileCallbackManager<LazyEmitLayerT, OrcX86_64> CompileCallbacks;
1285 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1286 if (auto F = ParseDefinition()) {
1287 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1288 J.addFunctionDefinition(std::move(F));
1290 // Skip token for error recovery.
1295 static void HandleExtern(SessionContext &S) {
1296 if (auto P = ParseExtern())
1297 S.addPrototypeAST(std::move(P));
1299 // Skip token for error recovery.
1304 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1305 // Evaluate a top-level expression into an anonymous function.
1306 if (auto F = ParseTopLevelExpr()) {
1308 if (auto ExprFunc = F->IRGen(C)) {
1309 #ifndef MINIMAL_STDERR_OUTPUT
1310 std::cerr << "Expression function:\n";
1313 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1314 // this module as soon as we've executed Function ExprFunc.
1315 auto H = J.addModule(C.takeM());
1317 // Get the address of the JIT'd function in memory.
1318 auto ExprSymbol = J.findSymbol("__anon_expr");
1320 // Cast it to the right type (takes no arguments, returns a double) so we
1321 // can call it as a native function.
1322 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1323 #ifdef MINIMAL_STDERR_OUTPUT
1326 std::cerr << "Evaluated to " << FP() << "\n";
1329 // Remove the function.
1333 // Skip token for error recovery.
1338 /// top ::= definition | external | expression | ';'
1339 static void MainLoop() {
1340 SessionContext S(getGlobalContext());
1341 KaleidoscopeJIT J(S);
1345 case tok_eof: return;
1346 case ';': getNextToken(); continue; // ignore top-level semicolons.
1347 case tok_def: HandleDefinition(S, J); break;
1348 case tok_extern: HandleExtern(S); break;
1349 default: HandleTopLevelExpression(S, J); break;
1351 #ifndef MINIMAL_STDERR_OUTPUT
1352 std::cerr << "ready> ";
1357 //===----------------------------------------------------------------------===//
1358 // "Library" functions that can be "extern'd" from user code.
1359 //===----------------------------------------------------------------------===//
1361 /// putchard - putchar that takes a double and returns 0.
1363 double putchard(double X) {
1368 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1370 double printd(double X) {
1381 //===----------------------------------------------------------------------===//
1382 // Main driver code.
1383 //===----------------------------------------------------------------------===//
1386 InitializeNativeTarget();
1387 InitializeNativeTargetAsmPrinter();
1388 InitializeNativeTargetAsmParser();
1390 // Install standard binary operators.
1391 // 1 is lowest precedence.
1392 BinopPrecedence['='] = 2;
1393 BinopPrecedence['<'] = 10;
1394 BinopPrecedence['+'] = 20;
1395 BinopPrecedence['-'] = 20;
1396 BinopPrecedence['/'] = 40;
1397 BinopPrecedence['*'] = 40; // highest.
1399 // Prime the first token.
1400 #ifndef MINIMAL_STDERR_OUTPUT
1401 std::cerr << "ready> ";
1405 std::cerr << std::fixed;
1407 // Run the main "interpreter loop" now.