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/LambdaResolver.h"
5 #include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
6 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
7 #include "llvm/ExecutionEngine/Orc/OrcTargetSupport.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/LLVMContext.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/TargetSelect.h"
16 #include "llvm/Transforms/Scalar.h"
26 using namespace llvm::orc;
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
33 // of these for known things.
38 tok_def = -2, tok_extern = -3,
41 tok_identifier = -4, tok_number = -5,
44 tok_if = -6, tok_then = -7, tok_else = -8,
45 tok_for = -9, tok_in = -10,
48 tok_binary = -11, tok_unary = -12,
54 static std::string IdentifierStr; // Filled in if tok_identifier
55 static double NumVal; // Filled in if tok_number
57 /// gettok - Return the next token from standard input.
59 static int LastChar = ' ';
61 // Skip any whitespace.
62 while (isspace(LastChar))
65 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
66 IdentifierStr = LastChar;
67 while (isalnum((LastChar = getchar())))
68 IdentifierStr += LastChar;
70 if (IdentifierStr == "def") return tok_def;
71 if (IdentifierStr == "extern") return tok_extern;
72 if (IdentifierStr == "if") return tok_if;
73 if (IdentifierStr == "then") return tok_then;
74 if (IdentifierStr == "else") return tok_else;
75 if (IdentifierStr == "for") return tok_for;
76 if (IdentifierStr == "in") return tok_in;
77 if (IdentifierStr == "binary") return tok_binary;
78 if (IdentifierStr == "unary") return tok_unary;
79 if (IdentifierStr == "var") return tok_var;
80 return tok_identifier;
83 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
88 } while (isdigit(LastChar) || LastChar == '.');
90 NumVal = strtod(NumStr.c_str(), 0);
94 if (LastChar == '#') {
95 // Comment until end of line.
96 do LastChar = getchar();
97 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
103 // Check for end of file. Don't eat the EOF.
107 // Otherwise, just return the character as its ascii value.
108 int ThisChar = LastChar;
109 LastChar = getchar();
113 //===----------------------------------------------------------------------===//
114 // Abstract Syntax Tree (aka Parse Tree)
115 //===----------------------------------------------------------------------===//
119 /// ExprAST - Base class for all expression nodes.
121 virtual ~ExprAST() {}
122 virtual Value *IRGen(IRGenContext &C) const = 0;
125 /// NumberExprAST - Expression class for numeric literals like "1.0".
126 struct NumberExprAST : public ExprAST {
127 NumberExprAST(double Val) : Val(Val) {}
128 Value *IRGen(IRGenContext &C) const override;
133 /// VariableExprAST - Expression class for referencing a variable, like "a".
134 struct VariableExprAST : public ExprAST {
135 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
136 Value *IRGen(IRGenContext &C) const override;
141 /// UnaryExprAST - Expression class for a unary operator.
142 struct UnaryExprAST : public ExprAST {
143 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
144 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
146 Value *IRGen(IRGenContext &C) const override;
149 std::unique_ptr<ExprAST> Operand;
152 /// BinaryExprAST - Expression class for a binary operator.
153 struct BinaryExprAST : public ExprAST {
154 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
155 std::unique_ptr<ExprAST> RHS)
156 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
158 Value *IRGen(IRGenContext &C) const override;
161 std::unique_ptr<ExprAST> LHS, RHS;
164 /// CallExprAST - Expression class for function calls.
165 struct CallExprAST : public ExprAST {
166 CallExprAST(std::string CalleeName,
167 std::vector<std::unique_ptr<ExprAST>> Args)
168 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
170 Value *IRGen(IRGenContext &C) const override;
172 std::string CalleeName;
173 std::vector<std::unique_ptr<ExprAST>> Args;
176 /// IfExprAST - Expression class for if/then/else.
177 struct IfExprAST : public ExprAST {
178 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
179 std::unique_ptr<ExprAST> Else)
180 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
181 Value *IRGen(IRGenContext &C) const override;
183 std::unique_ptr<ExprAST> Cond, Then, Else;
186 /// ForExprAST - Expression class for for/in.
187 struct ForExprAST : public ExprAST {
188 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
189 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
190 std::unique_ptr<ExprAST> Body)
191 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
192 Step(std::move(Step)), Body(std::move(Body)) {}
194 Value *IRGen(IRGenContext &C) const override;
197 std::unique_ptr<ExprAST> Start, End, Step, Body;
200 /// VarExprAST - Expression class for var/in
201 struct VarExprAST : public ExprAST {
202 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
203 typedef std::vector<Binding> BindingList;
205 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
206 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
208 Value *IRGen(IRGenContext &C) const override;
210 BindingList VarBindings;
211 std::unique_ptr<ExprAST> Body;
214 /// PrototypeAST - This class represents the "prototype" for a function,
215 /// which captures its argument names as well as if it is an operator.
216 struct PrototypeAST {
217 PrototypeAST(std::string Name, std::vector<std::string> Args,
218 bool IsOperator = false, unsigned Precedence = 0)
219 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
220 Precedence(Precedence) {}
222 Function *IRGen(IRGenContext &C) const;
223 void CreateArgumentAllocas(Function *F, IRGenContext &C);
225 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
226 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
228 char getOperatorName() const {
229 assert(isUnaryOp() || isBinaryOp());
230 return Name[Name.size()-1];
234 std::vector<std::string> Args;
236 unsigned Precedence; // Precedence if a binary op.
239 /// FunctionAST - This class represents a function definition itself.
241 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
242 std::unique_ptr<ExprAST> Body)
243 : Proto(std::move(Proto)), Body(std::move(Body)) {}
245 Function *IRGen(IRGenContext &C) const;
247 std::unique_ptr<PrototypeAST> Proto;
248 std::unique_ptr<ExprAST> Body;
251 //===----------------------------------------------------------------------===//
253 //===----------------------------------------------------------------------===//
255 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
256 /// token the parser is looking at. getNextToken reads another token from the
257 /// lexer and updates CurTok with its results.
259 static int getNextToken() {
260 return CurTok = gettok();
263 /// BinopPrecedence - This holds the precedence for each binary operator that is
265 static std::map<char, int> BinopPrecedence;
267 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
268 static int GetTokPrecedence() {
269 if (!isascii(CurTok))
272 // Make sure it's a declared binop.
273 int TokPrec = BinopPrecedence[CurTok];
274 if (TokPrec <= 0) return -1;
278 template <typename T>
279 std::unique_ptr<T> ErrorU(const std::string &Str) {
280 std::cerr << "Error: " << Str << "\n";
284 template <typename T>
285 T* ErrorP(const std::string &Str) {
286 std::cerr << "Error: " << Str << "\n";
290 static std::unique_ptr<ExprAST> ParseExpression();
294 /// ::= identifier '(' expression* ')'
295 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
296 std::string IdName = IdentifierStr;
298 getNextToken(); // eat identifier.
300 if (CurTok != '(') // Simple variable ref.
301 return llvm::make_unique<VariableExprAST>(IdName);
304 getNextToken(); // eat (
305 std::vector<std::unique_ptr<ExprAST>> Args;
308 auto Arg = ParseExpression();
309 if (!Arg) return nullptr;
310 Args.push_back(std::move(Arg));
312 if (CurTok == ')') break;
315 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
323 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
326 /// numberexpr ::= number
327 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
328 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
329 getNextToken(); // consume the number
333 /// parenexpr ::= '(' expression ')'
334 static std::unique_ptr<ExprAST> ParseParenExpr() {
335 getNextToken(); // eat (.
336 auto V = ParseExpression();
341 return ErrorU<ExprAST>("expected ')'");
342 getNextToken(); // eat ).
346 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
347 static std::unique_ptr<ExprAST> ParseIfExpr() {
348 getNextToken(); // eat the if.
351 auto Cond = ParseExpression();
355 if (CurTok != tok_then)
356 return ErrorU<ExprAST>("expected then");
357 getNextToken(); // eat the then
359 auto Then = ParseExpression();
363 if (CurTok != tok_else)
364 return ErrorU<ExprAST>("expected else");
368 auto Else = ParseExpression();
372 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
376 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
377 static std::unique_ptr<ForExprAST> ParseForExpr() {
378 getNextToken(); // eat the for.
380 if (CurTok != tok_identifier)
381 return ErrorU<ForExprAST>("expected identifier after for");
383 std::string IdName = IdentifierStr;
384 getNextToken(); // eat identifier.
387 return ErrorU<ForExprAST>("expected '=' after for");
388 getNextToken(); // eat '='.
391 auto Start = ParseExpression();
395 return ErrorU<ForExprAST>("expected ',' after for start value");
398 auto End = ParseExpression();
402 // The step value is optional.
403 std::unique_ptr<ExprAST> Step;
406 Step = ParseExpression();
411 if (CurTok != tok_in)
412 return ErrorU<ForExprAST>("expected 'in' after for");
413 getNextToken(); // eat 'in'.
415 auto Body = ParseExpression();
419 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
420 std::move(Step), std::move(Body));
423 /// varexpr ::= 'var' identifier ('=' expression)?
424 // (',' identifier ('=' expression)?)* 'in' expression
425 static std::unique_ptr<VarExprAST> ParseVarExpr() {
426 getNextToken(); // eat the var.
428 VarExprAST::BindingList VarBindings;
430 // At least one variable name is required.
431 if (CurTok != tok_identifier)
432 return ErrorU<VarExprAST>("expected identifier after var");
435 std::string Name = IdentifierStr;
436 getNextToken(); // eat identifier.
438 // Read the optional initializer.
439 std::unique_ptr<ExprAST> Init;
441 getNextToken(); // eat the '='.
443 Init = ParseExpression();
448 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
450 // End of var list, exit loop.
451 if (CurTok != ',') break;
452 getNextToken(); // eat the ','.
454 if (CurTok != tok_identifier)
455 return ErrorU<VarExprAST>("expected identifier list after var");
458 // At this point, we have to have 'in'.
459 if (CurTok != tok_in)
460 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
461 getNextToken(); // eat 'in'.
463 auto Body = ParseExpression();
467 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
471 /// ::= identifierexpr
477 static std::unique_ptr<ExprAST> ParsePrimary() {
479 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
480 case tok_identifier: return ParseIdentifierExpr();
481 case tok_number: return ParseNumberExpr();
482 case '(': return ParseParenExpr();
483 case tok_if: return ParseIfExpr();
484 case tok_for: return ParseForExpr();
485 case tok_var: return ParseVarExpr();
492 static std::unique_ptr<ExprAST> ParseUnary() {
493 // If the current token is not an operator, it must be a primary expr.
494 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
495 return ParsePrimary();
497 // If this is a unary operator, read it.
500 if (auto Operand = ParseUnary())
501 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
507 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
508 std::unique_ptr<ExprAST> LHS) {
509 // If this is a binop, find its precedence.
511 int TokPrec = GetTokPrecedence();
513 // If this is a binop that binds at least as tightly as the current binop,
514 // consume it, otherwise we are done.
515 if (TokPrec < ExprPrec)
518 // Okay, we know this is a binop.
520 getNextToken(); // eat binop
522 // Parse the unary expression after the binary operator.
523 auto RHS = ParseUnary();
527 // If BinOp binds less tightly with RHS than the operator after RHS, let
528 // the pending operator take RHS as its LHS.
529 int NextPrec = GetTokPrecedence();
530 if (TokPrec < NextPrec) {
531 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
537 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
542 /// ::= unary binoprhs
544 static std::unique_ptr<ExprAST> ParseExpression() {
545 auto LHS = ParseUnary();
549 return ParseBinOpRHS(0, std::move(LHS));
553 /// ::= id '(' id* ')'
554 /// ::= binary LETTER number? (id, id)
555 /// ::= unary LETTER (id)
556 static std::unique_ptr<PrototypeAST> ParsePrototype() {
559 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
560 unsigned BinaryPrecedence = 30;
564 return ErrorU<PrototypeAST>("Expected function name in prototype");
566 FnName = IdentifierStr;
572 if (!isascii(CurTok))
573 return ErrorU<PrototypeAST>("Expected unary operator");
575 FnName += (char)CurTok;
581 if (!isascii(CurTok))
582 return ErrorU<PrototypeAST>("Expected binary operator");
584 FnName += (char)CurTok;
588 // Read the precedence if present.
589 if (CurTok == tok_number) {
590 if (NumVal < 1 || NumVal > 100)
591 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
592 BinaryPrecedence = (unsigned)NumVal;
599 return ErrorU<PrototypeAST>("Expected '(' in prototype");
601 std::vector<std::string> ArgNames;
602 while (getNextToken() == tok_identifier)
603 ArgNames.push_back(IdentifierStr);
605 return ErrorU<PrototypeAST>("Expected ')' in prototype");
608 getNextToken(); // eat ')'.
610 // Verify right number of names for operator.
611 if (Kind && ArgNames.size() != Kind)
612 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
614 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
618 /// definition ::= 'def' prototype expression
619 static std::unique_ptr<FunctionAST> ParseDefinition() {
620 getNextToken(); // eat def.
621 auto Proto = ParsePrototype();
625 if (auto Body = ParseExpression())
626 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
630 /// toplevelexpr ::= expression
631 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
632 if (auto E = ParseExpression()) {
633 // Make an anonymous proto.
635 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
636 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
641 /// external ::= 'extern' prototype
642 static std::unique_ptr<PrototypeAST> ParseExtern() {
643 getNextToken(); // eat extern.
644 return ParsePrototype();
647 //===----------------------------------------------------------------------===//
649 //===----------------------------------------------------------------------===//
651 // FIXME: Obviously we can do better than this
652 std::string GenerateUniqueName(const std::string &Root) {
654 std::ostringstream NameStream;
655 NameStream << Root << ++i;
656 return NameStream.str();
659 std::string MakeLegalFunctionName(std::string Name)
662 assert(!Name.empty() && "Base name must not be empty");
664 // Start with what we have
667 // Look for a numberic first character
668 if (NewName.find_first_of("0123456789") == 0) {
669 NewName.insert(0, 1, 'n');
672 // Replace illegal characters with their ASCII equivalent
673 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
675 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
676 std::ostringstream NumStream;
677 NumStream << (int)NewName.at(pos);
678 NewName = NewName.replace(pos, 1, NumStream.str());
684 class SessionContext {
686 SessionContext(LLVMContext &C)
687 : Context(C), TM(EngineBuilder().selectTarget()) {}
688 LLVMContext& getLLVMContext() const { return Context; }
689 TargetMachine& getTarget() { return *TM; }
690 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
691 PrototypeAST* getPrototypeAST(const std::string &Name);
693 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
695 LLVMContext &Context;
696 std::unique_ptr<TargetMachine> TM;
698 PrototypeMap Prototypes;
701 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
702 Prototypes[P->Name] = std::move(P);
705 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
706 PrototypeMap::iterator I = Prototypes.find(Name);
707 if (I != Prototypes.end())
708 return I->second.get();
715 IRGenContext(SessionContext &S)
717 M(new Module(GenerateUniqueName("jit_module_"),
718 Session.getLLVMContext())),
719 Builder(Session.getLLVMContext()) {
720 M->setDataLayout(Session.getTarget().createDataLayout());
723 SessionContext& getSession() { return Session; }
724 Module& getM() const { return *M; }
725 std::unique_ptr<Module> takeM() { return std::move(M); }
726 IRBuilder<>& getBuilder() { return Builder; }
727 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
728 Function* getPrototype(const std::string &Name);
730 std::map<std::string, AllocaInst*> NamedValues;
732 SessionContext &Session;
733 std::unique_ptr<Module> M;
737 Function* IRGenContext::getPrototype(const std::string &Name) {
738 if (Function *ExistingProto = M->getFunction(Name))
739 return ExistingProto;
740 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
741 return ProtoAST->IRGen(*this);
745 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
746 /// the function. This is used for mutable variables etc.
747 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
748 const std::string &VarName) {
749 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
750 TheFunction->getEntryBlock().begin());
751 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
755 Value *NumberExprAST::IRGen(IRGenContext &C) const {
756 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
759 Value *VariableExprAST::IRGen(IRGenContext &C) const {
760 // Look this variable up in the function.
761 Value *V = C.NamedValues[Name];
764 return ErrorP<Value>("Unknown variable name '" + Name + "'");
767 return C.getBuilder().CreateLoad(V, Name.c_str());
770 Value *UnaryExprAST::IRGen(IRGenContext &C) const {
771 if (Value *OperandV = Operand->IRGen(C)) {
772 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
773 if (Function *F = C.getPrototype(FnName))
774 return C.getBuilder().CreateCall(F, OperandV, "unop");
775 return ErrorP<Value>("Unknown unary operator");
778 // Could not codegen operand - return null.
782 Value *BinaryExprAST::IRGen(IRGenContext &C) const {
783 // Special case '=' because we don't want to emit the LHS as an expression.
785 // Assignment requires the LHS to be an identifier.
786 auto LHSVar = static_cast<VariableExprAST&>(*LHS);
788 Value *Val = RHS->IRGen(C);
789 if (!Val) return nullptr;
792 if (auto Variable = C.NamedValues[LHSVar.Name]) {
793 C.getBuilder().CreateStore(Val, Variable);
796 return ErrorP<Value>("Unknown variable name");
799 Value *L = LHS->IRGen(C);
800 Value *R = RHS->IRGen(C);
801 if (!L || !R) return nullptr;
804 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
805 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
806 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
807 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
809 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
810 // Convert bool 0/1 to double 0.0 or 1.0
811 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
816 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
818 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
819 if (Function *F = C.getPrototype(FnName)) {
820 Value *Ops[] = { L, R };
821 return C.getBuilder().CreateCall(F, Ops, "binop");
824 return ErrorP<Value>("Unknown binary operator");
827 Value *CallExprAST::IRGen(IRGenContext &C) const {
828 // Look up the name in the global module table.
829 if (auto CalleeF = C.getPrototype(CalleeName)) {
830 // If argument mismatch error.
831 if (CalleeF->arg_size() != Args.size())
832 return ErrorP<Value>("Incorrect # arguments passed");
834 std::vector<Value*> ArgsV;
835 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
836 ArgsV.push_back(Args[i]->IRGen(C));
837 if (!ArgsV.back()) return nullptr;
840 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
843 return ErrorP<Value>("Unknown function referenced");
846 Value *IfExprAST::IRGen(IRGenContext &C) const {
847 Value *CondV = Cond->IRGen(C);
848 if (!CondV) return nullptr;
850 // Convert condition to a bool by comparing equal to 0.0.
852 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
853 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
855 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
857 // Create blocks for the then and else cases. Insert the 'then' block at the
858 // end of the function.
859 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
860 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
861 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
863 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
866 C.getBuilder().SetInsertPoint(ThenBB);
868 Value *ThenV = Then->IRGen(C);
869 if (!ThenV) return nullptr;
871 C.getBuilder().CreateBr(MergeBB);
872 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
873 ThenBB = C.getBuilder().GetInsertBlock();
876 TheFunction->getBasicBlockList().push_back(ElseBB);
877 C.getBuilder().SetInsertPoint(ElseBB);
879 Value *ElseV = Else->IRGen(C);
880 if (!ElseV) return nullptr;
882 C.getBuilder().CreateBr(MergeBB);
883 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
884 ElseBB = C.getBuilder().GetInsertBlock();
887 TheFunction->getBasicBlockList().push_back(MergeBB);
888 C.getBuilder().SetInsertPoint(MergeBB);
889 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
892 PN->addIncoming(ThenV, ThenBB);
893 PN->addIncoming(ElseV, ElseBB);
897 Value *ForExprAST::IRGen(IRGenContext &C) const {
899 // var = alloca double
902 // store start -> var
913 // nextvar = curvar + step
914 // store nextvar -> var
915 // br endcond, loop, endloop
918 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
920 // Create an alloca for the variable in the entry block.
921 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
923 // Emit the start code first, without 'variable' in scope.
924 Value *StartVal = Start->IRGen(C);
925 if (!StartVal) return nullptr;
927 // Store the value into the alloca.
928 C.getBuilder().CreateStore(StartVal, Alloca);
930 // Make the new basic block for the loop header, inserting after current
932 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
934 // Insert an explicit fall through from the current block to the LoopBB.
935 C.getBuilder().CreateBr(LoopBB);
937 // Start insertion in LoopBB.
938 C.getBuilder().SetInsertPoint(LoopBB);
940 // Within the loop, the variable is defined equal to the PHI node. If it
941 // shadows an existing variable, we have to restore it, so save it now.
942 AllocaInst *OldVal = C.NamedValues[VarName];
943 C.NamedValues[VarName] = Alloca;
945 // Emit the body of the loop. This, like any other expr, can change the
946 // current BB. Note that we ignore the value computed by the body, but don't
951 // Emit the step value.
954 StepVal = Step->IRGen(C);
955 if (!StepVal) return nullptr;
957 // If not specified, use 1.0.
958 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
961 // Compute the end condition.
962 Value *EndCond = End->IRGen(C);
963 if (EndCond == 0) return EndCond;
965 // Reload, increment, and restore the alloca. This handles the case where
966 // the body of the loop mutates the variable.
967 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
968 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
969 C.getBuilder().CreateStore(NextVar, Alloca);
971 // Convert condition to a bool by comparing equal to 0.0.
972 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
973 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
976 // Create the "after loop" block and insert it.
977 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
979 // Insert the conditional branch into the end of LoopEndBB.
980 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
982 // Any new code will be inserted in AfterBB.
983 C.getBuilder().SetInsertPoint(AfterBB);
985 // Restore the unshadowed variable.
987 C.NamedValues[VarName] = OldVal;
989 C.NamedValues.erase(VarName);
992 // for expr always returns 0.0.
993 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
996 Value *VarExprAST::IRGen(IRGenContext &C) const {
997 std::vector<AllocaInst *> OldBindings;
999 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
1001 // Register all variables and emit their initializer.
1002 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
1003 auto &VarName = VarBindings[i].first;
1004 auto &Init = VarBindings[i].second;
1006 // Emit the initializer before adding the variable to scope, this prevents
1007 // the initializer from referencing the variable itself, and permits stuff
1010 // var a = a in ... # refers to outer 'a'.
1013 InitVal = Init->IRGen(C);
1014 if (!InitVal) return nullptr;
1015 } else // If not specified, use 0.0.
1016 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1018 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1019 C.getBuilder().CreateStore(InitVal, Alloca);
1021 // Remember the old variable binding so that we can restore the binding when
1023 OldBindings.push_back(C.NamedValues[VarName]);
1025 // Remember this binding.
1026 C.NamedValues[VarName] = Alloca;
1029 // Codegen the body, now that all vars are in scope.
1030 Value *BodyVal = Body->IRGen(C);
1031 if (!BodyVal) return nullptr;
1033 // Pop all our variables from scope.
1034 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1035 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1037 // Return the body computation.
1041 Function *PrototypeAST::IRGen(IRGenContext &C) const {
1042 std::string FnName = MakeLegalFunctionName(Name);
1044 // Make the function type: double(double,double) etc.
1045 std::vector<Type*> Doubles(Args.size(),
1046 Type::getDoubleTy(getGlobalContext()));
1047 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1049 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1052 // If F conflicted, there was already something named 'FnName'. If it has a
1053 // body, don't allow redefinition or reextern.
1054 if (F->getName() != FnName) {
1055 // Delete the one we just made and get the existing one.
1056 F->eraseFromParent();
1057 F = C.getM().getFunction(Name);
1059 // If F already has a body, reject this.
1061 ErrorP<Function>("redefinition of function");
1065 // If F took a different number of args, reject.
1066 if (F->arg_size() != Args.size()) {
1067 ErrorP<Function>("redefinition of function with different # args");
1072 // Set names for all arguments.
1074 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1076 AI->setName(Args[Idx]);
1081 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1082 /// argument in the symbol table so that references to it will succeed.
1083 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1084 Function::arg_iterator AI = F->arg_begin();
1085 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1086 // Create an alloca for this variable.
1087 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1089 // Store the initial value into the alloca.
1090 C.getBuilder().CreateStore(AI, Alloca);
1092 // Add arguments to variable symbol table.
1093 C.NamedValues[Args[Idx]] = Alloca;
1097 Function *FunctionAST::IRGen(IRGenContext &C) const {
1098 C.NamedValues.clear();
1100 Function *TheFunction = Proto->IRGen(C);
1104 // If this is an operator, install it.
1105 if (Proto->isBinaryOp())
1106 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1108 // Create a new basic block to start insertion into.
1109 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1110 C.getBuilder().SetInsertPoint(BB);
1112 // Add all arguments to the symbol table and create their allocas.
1113 Proto->CreateArgumentAllocas(TheFunction, C);
1115 if (Value *RetVal = Body->IRGen(C)) {
1116 // Finish off the function.
1117 C.getBuilder().CreateRet(RetVal);
1119 // Validate the generated code, checking for consistency.
1120 verifyFunction(*TheFunction);
1125 // Error reading body, remove function.
1126 TheFunction->eraseFromParent();
1128 if (Proto->isBinaryOp())
1129 BinopPrecedence.erase(Proto->getOperatorName());
1133 //===----------------------------------------------------------------------===//
1134 // Top-Level parsing and JIT Driver
1135 //===----------------------------------------------------------------------===//
1137 static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1138 const FunctionAST &F) {
1140 auto LF = F.IRGen(C);
1143 #ifndef MINIMAL_STDERR_OUTPUT
1144 fprintf(stderr, "Read function definition:");
1150 template <typename T>
1151 static std::vector<T> singletonSet(T t) {
1153 Vec.push_back(std::move(t));
1157 static void EarthShatteringKaboom() {
1158 fprintf(stderr, "Earth shattering kaboom.");
1162 class KaleidoscopeJIT {
1164 typedef ObjectLinkingLayer<> ObjLayerT;
1165 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1166 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1167 typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1169 KaleidoscopeJIT(SessionContext &Session)
1171 CompileLayer(ObjectLayer, SimpleCompiler(Session.getTarget())),
1172 LazyEmitLayer(CompileLayer),
1173 CompileCallbacks(LazyEmitLayer, CCMgrMemMgr, Session.getLLVMContext(),
1174 reinterpret_cast<uintptr_t>(EarthShatteringKaboom),
1177 std::string mangle(const std::string &Name) {
1178 std::string MangledName;
1180 raw_string_ostream MangledNameStream(MangledName);
1181 Mangler::getNameWithPrefix(MangledNameStream, Name,
1182 Session.getTarget().createDataLayout());
1187 void addFunctionAST(std::unique_ptr<FunctionAST> FnAST) {
1188 std::cerr << "Adding AST: " << FnAST->Proto->Name << "\n";
1189 FunctionDefs[mangle(FnAST->Proto->Name)] = std::move(FnAST);
1192 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1193 // We need a memory manager to allocate memory and resolve symbols for this
1194 // new module. Create one that resolves symbols by looking back into the
1196 auto Resolver = createLambdaResolver(
1197 [&](const std::string &Name) {
1198 // First try to find 'Name' within the JIT.
1199 if (auto Symbol = findSymbol(Name))
1200 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
1203 // If we don't already have a definition of 'Name' then search
1205 return searchFunctionASTs(Name);
1207 [](const std::string &S) { return nullptr; } );
1209 return LazyEmitLayer.addModuleSet(singletonSet(std::move(M)),
1210 make_unique<SectionMemoryManager>(),
1211 std::move(Resolver));
1214 void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1216 JITSymbol findSymbol(const std::string &Name) {
1217 return LazyEmitLayer.findSymbol(Name, false);
1220 JITSymbol findSymbolIn(ModuleHandleT H, const std::string &Name) {
1221 return LazyEmitLayer.findSymbolIn(H, Name, false);
1224 JITSymbol findUnmangledSymbol(const std::string &Name) {
1225 return findSymbol(mangle(Name));
1228 JITSymbol findUnmangledSymbolIn(ModuleHandleT H, const std::string &Name) {
1229 return findSymbolIn(H, mangle(Name));
1234 // This method searches the FunctionDefs map for a definition of 'Name'. If it
1235 // finds one it generates a stub for it and returns the address of the stub.
1236 RuntimeDyld::SymbolInfo searchFunctionASTs(const std::string &Name) {
1237 auto DefI = FunctionDefs.find(Name);
1238 if (DefI == FunctionDefs.end())
1241 // Return the address of the stub.
1242 // Take the FunctionAST out of the map.
1243 auto FnAST = std::move(DefI->second);
1244 FunctionDefs.erase(DefI);
1246 // IRGen the AST, add it to the JIT, and return the address for it.
1247 auto H = irGenStub(std::move(FnAST));
1248 auto Sym = findSymbolIn(H, Name);
1249 return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
1252 // This method will take the AST for a function definition and IR-gen a stub
1253 // for that function that will, on first call, IR-gen the actual body of the
1255 ModuleHandleT irGenStub(std::unique_ptr<FunctionAST> FnAST) {
1256 // Step 1) IRGen a prototype for the stub. This will have the same type as
1258 IRGenContext C(Session);
1259 Function *F = FnAST->Proto->IRGen(C);
1261 // Step 2) Get a compile callback that can be used to compile the body of
1262 // the function. The resulting CallbackInfo type will let us set the
1263 // compile and update actions for the callback, and get a pointer to
1264 // the jit trampoline that we need to call to trigger those actions.
1266 CompileCallbacks.getCompileCallback(F->getContext());
1268 // Step 3) Create a stub that will indirectly call the body of this
1269 // function once it is compiled. Initially, set the function
1270 // pointer for the indirection to point at the trampoline.
1271 std::string BodyPtrName = (F->getName() + "$address").str();
1272 GlobalVariable *FunctionBodyPointer =
1273 createImplPointer(*F->getType(), *F->getParent(), BodyPtrName,
1274 createIRTypedAddress(*F->getFunctionType(),
1275 CallbackInfo.getAddress()));
1276 makeStub(*F, *FunctionBodyPointer);
1278 // Step 4) Add the module containing the stub to the JIT.
1279 auto StubH = addModule(C.takeM());
1281 // Step 5) Set the compile and update actions.
1283 // The compile action will IRGen the function and add it to the JIT, then
1284 // request its address, which will trigger codegen. Since we don't need the
1285 // AST after this, we pass ownership of the AST into the compile action:
1286 // compile actions (and update actions) are deleted after they're run, so
1287 // this will free the AST for us.
1289 // The update action will update FunctionBodyPointer to point at the newly
1290 // compiled function.
1291 std::shared_ptr<FunctionAST> Fn = std::move(FnAST);
1292 CallbackInfo.setCompileAction([this, Fn, BodyPtrName, StubH]() {
1293 auto H = addModule(IRGen(Session, *Fn));
1294 auto BodySym = findUnmangledSymbolIn(H, Fn->Proto->Name);
1295 auto BodyPtrSym = findUnmangledSymbolIn(StubH, BodyPtrName);
1296 assert(BodySym && "Missing function body.");
1297 assert(BodyPtrSym && "Missing function pointer.");
1298 auto BodyAddr = BodySym.getAddress();
1299 auto BodyPtr = reinterpret_cast<void*>(
1300 static_cast<uintptr_t>(BodyPtrSym.getAddress()));
1301 memcpy(BodyPtr, &BodyAddr, sizeof(uintptr_t));
1308 SessionContext &Session;
1309 SectionMemoryManager CCMgrMemMgr;
1310 ObjLayerT ObjectLayer;
1311 CompileLayerT CompileLayer;
1312 LazyEmitLayerT LazyEmitLayer;
1314 std::map<std::string, std::unique_ptr<FunctionAST>> FunctionDefs;
1316 JITCompileCallbackManager<LazyEmitLayerT, OrcX86_64> CompileCallbacks;
1319 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1320 if (auto F = ParseDefinition()) {
1321 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1322 J.addFunctionAST(std::move(F));
1324 // Skip token for error recovery.
1329 static void HandleExtern(SessionContext &S) {
1330 if (auto P = ParseExtern())
1331 S.addPrototypeAST(std::move(P));
1333 // Skip token for error recovery.
1338 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1339 // Evaluate a top-level expression into an anonymous function.
1340 if (auto F = ParseTopLevelExpr()) {
1342 if (auto ExprFunc = F->IRGen(C)) {
1343 #ifndef MINIMAL_STDERR_OUTPUT
1344 std::cerr << "Expression function:\n";
1347 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1348 // this module as soon as we've executed Function ExprFunc.
1349 auto H = J.addModule(C.takeM());
1351 // Get the address of the JIT'd function in memory.
1352 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
1354 // Cast it to the right type (takes no arguments, returns a double) so we
1355 // can call it as a native function.
1356 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1357 #ifdef MINIMAL_STDERR_OUTPUT
1360 std::cerr << "Evaluated to " << FP() << "\n";
1363 // Remove the function.
1367 // Skip token for error recovery.
1372 /// top ::= definition | external | expression | ';'
1373 static void MainLoop() {
1374 SessionContext S(getGlobalContext());
1375 KaleidoscopeJIT J(S);
1379 case tok_eof: return;
1380 case ';': getNextToken(); continue; // ignore top-level semicolons.
1381 case tok_def: HandleDefinition(S, J); break;
1382 case tok_extern: HandleExtern(S); break;
1383 default: HandleTopLevelExpression(S, J); break;
1385 #ifndef MINIMAL_STDERR_OUTPUT
1386 std::cerr << "ready> ";
1391 //===----------------------------------------------------------------------===//
1392 // "Library" functions that can be "extern'd" from user code.
1393 //===----------------------------------------------------------------------===//
1395 /// putchard - putchar that takes a double and returns 0.
1397 double putchard(double X) {
1402 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1404 double printd(double X) {
1415 //===----------------------------------------------------------------------===//
1416 // Main driver code.
1417 //===----------------------------------------------------------------------===//
1420 InitializeNativeTarget();
1421 InitializeNativeTargetAsmPrinter();
1422 InitializeNativeTargetAsmParser();
1424 // Install standard binary operators.
1425 // 1 is lowest precedence.
1426 BinopPrecedence['='] = 2;
1427 BinopPrecedence['<'] = 10;
1428 BinopPrecedence['+'] = 20;
1429 BinopPrecedence['-'] = 20;
1430 BinopPrecedence['/'] = 40;
1431 BinopPrecedence['*'] = 40; // highest.
1433 // Prime the first token.
1434 #ifndef MINIMAL_STDERR_OUTPUT
1435 std::cerr << "ready> ";
1439 std::cerr << std::fixed;
1441 // Run the main "interpreter loop" now.