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/Module.h"
11 #include "llvm/IR/Verifier.h"
12 #include "llvm/PassManager.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Transforms/Scalar.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
29 // of these for known things.
34 tok_def = -2, tok_extern = -3,
37 tok_identifier = -4, tok_number = -5,
40 tok_if = -6, tok_then = -7, tok_else = -8,
41 tok_for = -9, tok_in = -10,
44 tok_binary = -11, tok_unary = -12,
50 static std::string IdentifierStr; // Filled in if tok_identifier
51 static double NumVal; // Filled in if tok_number
53 /// gettok - Return the next token from standard input.
55 static int LastChar = ' ';
57 // Skip any whitespace.
58 while (isspace(LastChar))
61 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
62 IdentifierStr = LastChar;
63 while (isalnum((LastChar = getchar())))
64 IdentifierStr += LastChar;
66 if (IdentifierStr == "def") return tok_def;
67 if (IdentifierStr == "extern") return tok_extern;
68 if (IdentifierStr == "if") return tok_if;
69 if (IdentifierStr == "then") return tok_then;
70 if (IdentifierStr == "else") return tok_else;
71 if (IdentifierStr == "for") return tok_for;
72 if (IdentifierStr == "in") return tok_in;
73 if (IdentifierStr == "binary") return tok_binary;
74 if (IdentifierStr == "unary") return tok_unary;
75 if (IdentifierStr == "var") return tok_var;
76 return tok_identifier;
79 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
84 } while (isdigit(LastChar) || LastChar == '.');
86 NumVal = strtod(NumStr.c_str(), 0);
90 if (LastChar == '#') {
91 // Comment until end of line.
92 do LastChar = getchar();
93 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
99 // Check for end of file. Don't eat the EOF.
103 // Otherwise, just return the character as its ascii value.
104 int ThisChar = LastChar;
105 LastChar = getchar();
109 //===----------------------------------------------------------------------===//
110 // Abstract Syntax Tree (aka Parse Tree)
111 //===----------------------------------------------------------------------===//
115 /// ExprAST - Base class for all expression nodes.
117 virtual ~ExprAST() {}
118 virtual Value* IRGen(IRGenContext &C) = 0;
121 /// NumberExprAST - Expression class for numeric literals like "1.0".
122 struct NumberExprAST : public ExprAST {
123 NumberExprAST(double Val) : Val(Val) {}
124 Value* IRGen(IRGenContext &C) override;
129 /// VariableExprAST - Expression class for referencing a variable, like "a".
130 struct VariableExprAST : public ExprAST {
131 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
132 Value* IRGen(IRGenContext &C) override;
137 /// UnaryExprAST - Expression class for a unary operator.
138 struct UnaryExprAST : public ExprAST {
139 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
140 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
142 Value* IRGen(IRGenContext &C) override;
145 std::unique_ptr<ExprAST> Operand;
148 /// BinaryExprAST - Expression class for a binary operator.
149 struct BinaryExprAST : public ExprAST {
150 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
151 std::unique_ptr<ExprAST> RHS)
152 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
154 Value* IRGen(IRGenContext &C) override;
157 std::unique_ptr<ExprAST> LHS, RHS;
160 /// CallExprAST - Expression class for function calls.
161 struct CallExprAST : public ExprAST {
162 CallExprAST(std::string CalleeName,
163 std::vector<std::unique_ptr<ExprAST>> Args)
164 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
166 Value* IRGen(IRGenContext &C) override;
168 std::string CalleeName;
169 std::vector<std::unique_ptr<ExprAST>> Args;
172 /// IfExprAST - Expression class for if/then/else.
173 struct IfExprAST : public ExprAST {
174 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
175 std::unique_ptr<ExprAST> Else)
176 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
177 Value* IRGen(IRGenContext &C) override;
179 std::unique_ptr<ExprAST> Cond, Then, Else;
182 /// ForExprAST - Expression class for for/in.
183 struct ForExprAST : public ExprAST {
184 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
185 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
186 std::unique_ptr<ExprAST> Body)
187 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
188 Step(std::move(Step)), Body(std::move(Body)) {}
190 Value* IRGen(IRGenContext &C) override;
193 std::unique_ptr<ExprAST> Start, End, Step, Body;
196 /// VarExprAST - Expression class for var/in
197 struct VarExprAST : public ExprAST {
198 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
199 typedef std::vector<Binding> BindingList;
201 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
202 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
204 Value* IRGen(IRGenContext &C) override;
206 BindingList VarBindings;
207 std::unique_ptr<ExprAST> Body;
210 /// PrototypeAST - This class represents the "prototype" for a function,
211 /// which captures its argument names as well as if it is an operator.
212 struct PrototypeAST {
213 PrototypeAST(std::string Name, std::vector<std::string> Args,
214 bool IsOperator = false, unsigned Precedence = 0)
215 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
216 Precedence(Precedence) {}
218 Function* IRGen(IRGenContext &C);
219 void CreateArgumentAllocas(Function *F, IRGenContext &C);
221 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
222 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
224 char getOperatorName() const {
225 assert(isUnaryOp() || isBinaryOp());
226 return Name[Name.size()-1];
230 std::vector<std::string> Args;
232 unsigned Precedence; // Precedence if a binary op.
235 /// FunctionAST - This class represents a function definition itself.
237 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
238 std::unique_ptr<ExprAST> Body)
239 : Proto(std::move(Proto)), Body(std::move(Body)) {}
241 Function* IRGen(IRGenContext &C);
243 std::unique_ptr<PrototypeAST> Proto;
244 std::unique_ptr<ExprAST> Body;
247 //===----------------------------------------------------------------------===//
249 //===----------------------------------------------------------------------===//
251 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
252 /// token the parser is looking at. getNextToken reads another token from the
253 /// lexer and updates CurTok with its results.
255 static int getNextToken() {
256 return CurTok = gettok();
259 /// BinopPrecedence - This holds the precedence for each binary operator that is
261 static std::map<char, int> BinopPrecedence;
263 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
264 static int GetTokPrecedence() {
265 if (!isascii(CurTok))
268 // Make sure it's a declared binop.
269 int TokPrec = BinopPrecedence[CurTok];
270 if (TokPrec <= 0) return -1;
274 template <typename T>
275 std::unique_ptr<T> ErrorU(const std::string &Str) {
276 std::cerr << "Error: " << Str << "\n";
280 template <typename T>
281 T* ErrorP(const std::string &Str) {
282 std::cerr << "Error: " << Str << "\n";
286 static std::unique_ptr<ExprAST> ParseExpression();
290 /// ::= identifier '(' expression* ')'
291 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
292 std::string IdName = IdentifierStr;
294 getNextToken(); // eat identifier.
296 if (CurTok != '(') // Simple variable ref.
297 return llvm::make_unique<VariableExprAST>(IdName);
300 getNextToken(); // eat (
301 std::vector<std::unique_ptr<ExprAST>> Args;
304 auto Arg = ParseExpression();
305 if (!Arg) return nullptr;
306 Args.push_back(std::move(Arg));
308 if (CurTok == ')') break;
311 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
319 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
322 /// numberexpr ::= number
323 static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
324 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
325 getNextToken(); // consume the number
329 /// parenexpr ::= '(' expression ')'
330 static std::unique_ptr<ExprAST> ParseParenExpr() {
331 getNextToken(); // eat (.
332 auto V = ParseExpression();
337 return ErrorU<ExprAST>("expected ')'");
338 getNextToken(); // eat ).
342 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
343 static std::unique_ptr<ExprAST> ParseIfExpr() {
344 getNextToken(); // eat the if.
347 auto Cond = ParseExpression();
351 if (CurTok != tok_then)
352 return ErrorU<ExprAST>("expected then");
353 getNextToken(); // eat the then
355 auto Then = ParseExpression();
359 if (CurTok != tok_else)
360 return ErrorU<ExprAST>("expected else");
364 auto Else = ParseExpression();
368 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
372 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
373 static std::unique_ptr<ForExprAST> ParseForExpr() {
374 getNextToken(); // eat the for.
376 if (CurTok != tok_identifier)
377 return ErrorU<ForExprAST>("expected identifier after for");
379 std::string IdName = IdentifierStr;
380 getNextToken(); // eat identifier.
383 return ErrorU<ForExprAST>("expected '=' after for");
384 getNextToken(); // eat '='.
387 auto Start = ParseExpression();
391 return ErrorU<ForExprAST>("expected ',' after for start value");
394 auto End = ParseExpression();
398 // The step value is optional.
399 std::unique_ptr<ExprAST> Step;
402 Step = ParseExpression();
407 if (CurTok != tok_in)
408 return ErrorU<ForExprAST>("expected 'in' after for");
409 getNextToken(); // eat 'in'.
411 auto Body = ParseExpression();
415 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
416 std::move(Step), std::move(Body));
419 /// varexpr ::= 'var' identifier ('=' expression)?
420 // (',' identifier ('=' expression)?)* 'in' expression
421 static std::unique_ptr<VarExprAST> ParseVarExpr() {
422 getNextToken(); // eat the var.
424 VarExprAST::BindingList VarBindings;
426 // At least one variable name is required.
427 if (CurTok != tok_identifier)
428 return ErrorU<VarExprAST>("expected identifier after var");
431 std::string Name = IdentifierStr;
432 getNextToken(); // eat identifier.
434 // Read the optional initializer.
435 std::unique_ptr<ExprAST> Init;
437 getNextToken(); // eat the '='.
439 Init = ParseExpression();
444 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
446 // End of var list, exit loop.
447 if (CurTok != ',') break;
448 getNextToken(); // eat the ','.
450 if (CurTok != tok_identifier)
451 return ErrorU<VarExprAST>("expected identifier list after var");
454 // At this point, we have to have 'in'.
455 if (CurTok != tok_in)
456 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
457 getNextToken(); // eat 'in'.
459 auto Body = ParseExpression();
463 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
467 /// ::= identifierexpr
473 static std::unique_ptr<ExprAST> ParsePrimary() {
475 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
476 case tok_identifier: return ParseIdentifierExpr();
477 case tok_number: return ParseNumberExpr();
478 case '(': return ParseParenExpr();
479 case tok_if: return ParseIfExpr();
480 case tok_for: return ParseForExpr();
481 case tok_var: return ParseVarExpr();
488 static std::unique_ptr<ExprAST> ParseUnary() {
489 // If the current token is not an operator, it must be a primary expr.
490 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
491 return ParsePrimary();
493 // If this is a unary operator, read it.
496 if (auto Operand = ParseUnary())
497 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
503 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
504 std::unique_ptr<ExprAST> LHS) {
505 // If this is a binop, find its precedence.
507 int TokPrec = GetTokPrecedence();
509 // If this is a binop that binds at least as tightly as the current binop,
510 // consume it, otherwise we are done.
511 if (TokPrec < ExprPrec)
514 // Okay, we know this is a binop.
516 getNextToken(); // eat binop
518 // Parse the unary expression after the binary operator.
519 auto RHS = ParseUnary();
523 // If BinOp binds less tightly with RHS than the operator after RHS, let
524 // the pending operator take RHS as its LHS.
525 int NextPrec = GetTokPrecedence();
526 if (TokPrec < NextPrec) {
527 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
533 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
538 /// ::= unary binoprhs
540 static std::unique_ptr<ExprAST> ParseExpression() {
541 auto LHS = ParseUnary();
545 return ParseBinOpRHS(0, std::move(LHS));
549 /// ::= id '(' id* ')'
550 /// ::= binary LETTER number? (id, id)
551 /// ::= unary LETTER (id)
552 static std::unique_ptr<PrototypeAST> ParsePrototype() {
555 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
556 unsigned BinaryPrecedence = 30;
560 return ErrorU<PrototypeAST>("Expected function name in prototype");
562 FnName = IdentifierStr;
568 if (!isascii(CurTok))
569 return ErrorU<PrototypeAST>("Expected unary operator");
571 FnName += (char)CurTok;
577 if (!isascii(CurTok))
578 return ErrorU<PrototypeAST>("Expected binary operator");
580 FnName += (char)CurTok;
584 // Read the precedence if present.
585 if (CurTok == tok_number) {
586 if (NumVal < 1 || NumVal > 100)
587 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
588 BinaryPrecedence = (unsigned)NumVal;
595 return ErrorU<PrototypeAST>("Expected '(' in prototype");
597 std::vector<std::string> ArgNames;
598 while (getNextToken() == tok_identifier)
599 ArgNames.push_back(IdentifierStr);
601 return ErrorU<PrototypeAST>("Expected ')' in prototype");
604 getNextToken(); // eat ')'.
606 // Verify right number of names for operator.
607 if (Kind && ArgNames.size() != Kind)
608 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
610 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
614 /// definition ::= 'def' prototype expression
615 static std::unique_ptr<FunctionAST> ParseDefinition() {
616 getNextToken(); // eat def.
617 auto Proto = ParsePrototype();
621 if (auto Body = ParseExpression())
622 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
626 /// toplevelexpr ::= expression
627 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
628 if (auto E = ParseExpression()) {
629 // Make an anonymous proto.
631 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
632 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
637 /// external ::= 'extern' prototype
638 static std::unique_ptr<PrototypeAST> ParseExtern() {
639 getNextToken(); // eat extern.
640 return ParsePrototype();
643 //===----------------------------------------------------------------------===//
645 //===----------------------------------------------------------------------===//
647 // FIXME: Obviously we can do better than this
648 std::string GenerateUniqueName(const std::string &Root) {
650 std::ostringstream NameStream;
651 NameStream << Root << ++i;
652 return NameStream.str();
655 std::string MakeLegalFunctionName(std::string Name)
658 assert(!Name.empty() && "Base name must not be empty");
660 // Start with what we have
663 // Look for a numberic first character
664 if (NewName.find_first_of("0123456789") == 0) {
665 NewName.insert(0, 1, 'n');
668 // Replace illegal characters with their ASCII equivalent
669 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
671 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
672 std::ostringstream NumStream;
673 NumStream << (int)NewName.at(pos);
674 NewName = NewName.replace(pos, 1, NumStream.str());
680 class SessionContext {
682 SessionContext(LLVMContext &C) : Context(C) {}
683 LLVMContext& getLLVMContext() const { return Context; }
684 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
685 PrototypeAST* getPrototypeAST(const std::string &Name);
687 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
688 LLVMContext &Context;
689 PrototypeMap Prototypes;
692 void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
693 Prototypes[P->Name] = std::move(P);
696 PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
697 PrototypeMap::iterator I = Prototypes.find(Name);
698 if (I != Prototypes.end())
699 return I->second.get();
706 IRGenContext(SessionContext &S)
708 M(new Module(GenerateUniqueName("jit_module_"),
709 Session.getLLVMContext())),
710 Builder(Session.getLLVMContext()) {}
712 SessionContext& getSession() { return Session; }
713 Module& getM() const { return *M; }
714 std::unique_ptr<Module> takeM() { return std::move(M); }
715 IRBuilder<>& getBuilder() { return Builder; }
716 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
717 Function* getPrototype(const std::string &Name);
719 std::map<std::string, AllocaInst*> NamedValues;
721 SessionContext &Session;
722 std::unique_ptr<Module> M;
726 Function* IRGenContext::getPrototype(const std::string &Name) {
727 if (Function *ExistingProto = M->getFunction(Name))
728 return ExistingProto;
729 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
730 return ProtoAST->IRGen(*this);
734 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
735 /// the function. This is used for mutable variables etc.
736 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
737 const std::string &VarName) {
738 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
739 TheFunction->getEntryBlock().begin());
740 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
744 Value *NumberExprAST::IRGen(IRGenContext &C) {
745 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
748 Value *VariableExprAST::IRGen(IRGenContext &C) {
749 // Look this variable up in the function.
750 Value *V = C.NamedValues[Name];
753 return ErrorP<Value>("Unknown variable name '" + Name + "'");
756 return C.getBuilder().CreateLoad(V, Name.c_str());
759 Value *UnaryExprAST::IRGen(IRGenContext &C) {
760 if (Value *OperandV = Operand->IRGen(C)) {
761 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
762 if (Function *F = C.getPrototype(FnName))
763 return C.getBuilder().CreateCall(F, OperandV, "unop");
764 return ErrorP<Value>("Unknown unary operator");
767 // Could not codegen operand - return null.
771 Value *BinaryExprAST::IRGen(IRGenContext &C) {
772 // Special case '=' because we don't want to emit the LHS as an expression.
774 // Assignment requires the LHS to be an identifier.
775 auto LHSVar = static_cast<VariableExprAST&>(*LHS);
777 Value *Val = RHS->IRGen(C);
778 if (!Val) return nullptr;
781 if (auto Variable = C.NamedValues[LHSVar.Name]) {
782 C.getBuilder().CreateStore(Val, Variable);
785 return ErrorP<Value>("Unknown variable name");
788 Value *L = LHS->IRGen(C);
789 Value *R = RHS->IRGen(C);
790 if (!L || !R) return nullptr;
793 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
794 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
795 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
796 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
798 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
799 // Convert bool 0/1 to double 0.0 or 1.0
800 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
805 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
807 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
808 if (Function *F = C.getPrototype(FnName)) {
809 Value *Ops[] = { L, R };
810 return C.getBuilder().CreateCall(F, Ops, "binop");
813 return ErrorP<Value>("Unknown binary operator");
816 Value *CallExprAST::IRGen(IRGenContext &C) {
817 // Look up the name in the global module table.
818 if (auto CalleeF = C.getPrototype(CalleeName)) {
819 // If argument mismatch error.
820 if (CalleeF->arg_size() != Args.size())
821 return ErrorP<Value>("Incorrect # arguments passed");
823 std::vector<Value*> ArgsV;
824 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
825 ArgsV.push_back(Args[i]->IRGen(C));
826 if (!ArgsV.back()) return nullptr;
829 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
832 return ErrorP<Value>("Unknown function referenced");
835 Value *IfExprAST::IRGen(IRGenContext &C) {
836 Value *CondV = Cond->IRGen(C);
837 if (!CondV) return nullptr;
839 // Convert condition to a bool by comparing equal to 0.0.
841 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
842 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
844 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
846 // Create blocks for the then and else cases. Insert the 'then' block at the
847 // end of the function.
848 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
849 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
850 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
852 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
855 C.getBuilder().SetInsertPoint(ThenBB);
857 Value *ThenV = Then->IRGen(C);
858 if (!ThenV) return nullptr;
860 C.getBuilder().CreateBr(MergeBB);
861 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
862 ThenBB = C.getBuilder().GetInsertBlock();
865 TheFunction->getBasicBlockList().push_back(ElseBB);
866 C.getBuilder().SetInsertPoint(ElseBB);
868 Value *ElseV = Else->IRGen(C);
869 if (!ElseV) return nullptr;
871 C.getBuilder().CreateBr(MergeBB);
872 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
873 ElseBB = C.getBuilder().GetInsertBlock();
876 TheFunction->getBasicBlockList().push_back(MergeBB);
877 C.getBuilder().SetInsertPoint(MergeBB);
878 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
881 PN->addIncoming(ThenV, ThenBB);
882 PN->addIncoming(ElseV, ElseBB);
886 Value *ForExprAST::IRGen(IRGenContext &C) {
888 // var = alloca double
891 // store start -> var
902 // nextvar = curvar + step
903 // store nextvar -> var
904 // br endcond, loop, endloop
907 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
909 // Create an alloca for the variable in the entry block.
910 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
912 // Emit the start code first, without 'variable' in scope.
913 Value *StartVal = Start->IRGen(C);
914 if (!StartVal) return nullptr;
916 // Store the value into the alloca.
917 C.getBuilder().CreateStore(StartVal, Alloca);
919 // Make the new basic block for the loop header, inserting after current
921 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
923 // Insert an explicit fall through from the current block to the LoopBB.
924 C.getBuilder().CreateBr(LoopBB);
926 // Start insertion in LoopBB.
927 C.getBuilder().SetInsertPoint(LoopBB);
929 // Within the loop, the variable is defined equal to the PHI node. If it
930 // shadows an existing variable, we have to restore it, so save it now.
931 AllocaInst *OldVal = C.NamedValues[VarName];
932 C.NamedValues[VarName] = Alloca;
934 // Emit the body of the loop. This, like any other expr, can change the
935 // current BB. Note that we ignore the value computed by the body, but don't
940 // Emit the step value.
943 StepVal = Step->IRGen(C);
944 if (!StepVal) return nullptr;
946 // If not specified, use 1.0.
947 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
950 // Compute the end condition.
951 Value *EndCond = End->IRGen(C);
952 if (EndCond == 0) return EndCond;
954 // Reload, increment, and restore the alloca. This handles the case where
955 // the body of the loop mutates the variable.
956 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
957 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
958 C.getBuilder().CreateStore(NextVar, Alloca);
960 // Convert condition to a bool by comparing equal to 0.0.
961 EndCond = C.getBuilder().CreateFCmpONE(EndCond,
962 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
965 // Create the "after loop" block and insert it.
966 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
968 // Insert the conditional branch into the end of LoopEndBB.
969 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
971 // Any new code will be inserted in AfterBB.
972 C.getBuilder().SetInsertPoint(AfterBB);
974 // Restore the unshadowed variable.
976 C.NamedValues[VarName] = OldVal;
978 C.NamedValues.erase(VarName);
981 // for expr always returns 0.0.
982 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
985 Value *VarExprAST::IRGen(IRGenContext &C) {
986 std::vector<AllocaInst *> OldBindings;
988 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
990 // Register all variables and emit their initializer.
991 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
992 auto &VarName = VarBindings[i].first;
993 auto &Init = VarBindings[i].second;
995 // Emit the initializer before adding the variable to scope, this prevents
996 // the initializer from referencing the variable itself, and permits stuff
999 // var a = a in ... # refers to outer 'a'.
1002 InitVal = Init->IRGen(C);
1003 if (!InitVal) return nullptr;
1004 } else // If not specified, use 0.0.
1005 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1007 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1008 C.getBuilder().CreateStore(InitVal, Alloca);
1010 // Remember the old variable binding so that we can restore the binding when
1012 OldBindings.push_back(C.NamedValues[VarName]);
1014 // Remember this binding.
1015 C.NamedValues[VarName] = Alloca;
1018 // Codegen the body, now that all vars are in scope.
1019 Value *BodyVal = Body->IRGen(C);
1020 if (!BodyVal) return nullptr;
1022 // Pop all our variables from scope.
1023 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1024 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1026 // Return the body computation.
1030 Function *PrototypeAST::IRGen(IRGenContext &C) {
1031 std::string FnName = MakeLegalFunctionName(Name);
1033 // Make the function type: double(double,double) etc.
1034 std::vector<Type*> Doubles(Args.size(),
1035 Type::getDoubleTy(getGlobalContext()));
1036 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
1038 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1041 // If F conflicted, there was already something named 'FnName'. If it has a
1042 // body, don't allow redefinition or reextern.
1043 if (F->getName() != FnName) {
1044 // Delete the one we just made and get the existing one.
1045 F->eraseFromParent();
1046 F = C.getM().getFunction(Name);
1048 // If F already has a body, reject this.
1050 ErrorP<Function>("redefinition of function");
1054 // If F took a different number of args, reject.
1055 if (F->arg_size() != Args.size()) {
1056 ErrorP<Function>("redefinition of function with different # args");
1061 // Set names for all arguments.
1063 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1065 AI->setName(Args[Idx]);
1070 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1071 /// argument in the symbol table so that references to it will succeed.
1072 void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1073 Function::arg_iterator AI = F->arg_begin();
1074 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1075 // Create an alloca for this variable.
1076 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1078 // Store the initial value into the alloca.
1079 C.getBuilder().CreateStore(AI, Alloca);
1081 // Add arguments to variable symbol table.
1082 C.NamedValues[Args[Idx]] = Alloca;
1086 Function *FunctionAST::IRGen(IRGenContext &C) {
1087 C.NamedValues.clear();
1089 Function *TheFunction = Proto->IRGen(C);
1093 // If this is an operator, install it.
1094 if (Proto->isBinaryOp())
1095 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
1097 // Create a new basic block to start insertion into.
1098 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1099 C.getBuilder().SetInsertPoint(BB);
1101 // Add all arguments to the symbol table and create their allocas.
1102 Proto->CreateArgumentAllocas(TheFunction, C);
1104 if (Value *RetVal = Body->IRGen(C)) {
1105 // Finish off the function.
1106 C.getBuilder().CreateRet(RetVal);
1108 // Validate the generated code, checking for consistency.
1109 verifyFunction(*TheFunction);
1114 // Error reading body, remove function.
1115 TheFunction->eraseFromParent();
1117 if (Proto->isBinaryOp())
1118 BinopPrecedence.erase(Proto->getOperatorName());
1122 //===----------------------------------------------------------------------===//
1123 // Top-Level parsing and JIT Driver
1124 //===----------------------------------------------------------------------===//
1126 class KaleidoscopeJIT {
1128 typedef ObjectLinkingLayer<> ObjLayerT;
1129 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1130 typedef LazyEmittingLayer<CompileLayerT> LazyEmitLayerT;
1132 typedef LazyEmitLayerT::ModuleSetHandleT ModuleHandleT;
1135 : TM(EngineBuilder().selectTarget()),
1136 Mang(TM->getDataLayout()),
1137 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
1138 LazyEmitLayer(CompileLayer) {}
1140 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1141 if (!M->getDataLayout())
1142 M->setDataLayout(TM->getDataLayout());
1144 // The LazyEmitLayer takes lists of modules, rather than single modules, so
1145 // we'll just build a single-element list.
1146 std::vector<std::unique_ptr<Module>> S;
1147 S.push_back(std::move(M));
1149 // We need a memory manager to allocate memory and resolve symbols for this
1150 // new module. Create one that resolves symbols by looking back into the JIT.
1151 auto MM = createLookasideRTDyldMM<SectionMemoryManager>(
1152 [&](const std::string &S) {
1153 return getMangledSymbolAddress(S);
1155 [](const std::string &S) { return 0; } );
1157 return LazyEmitLayer.addModuleSet(std::move(S), std::move(MM));
1160 void removeModule(ModuleHandleT H) { LazyEmitLayer.removeModuleSet(H); }
1162 uint64_t getMangledSymbolAddress(const std::string &Name) {
1163 return LazyEmitLayer.getSymbolAddress(Name, false);
1166 uint64_t getSymbolAddress(const std::string Name) {
1167 std::string MangledName;
1169 raw_string_ostream MangledNameStream(MangledName);
1170 Mang.getNameWithPrefix(MangledNameStream, Name);
1172 return getMangledSymbolAddress(MangledName);
1177 std::unique_ptr<TargetMachine> TM;
1180 ObjLayerT ObjectLayer;
1181 CompileLayerT CompileLayer;
1182 LazyEmitLayerT LazyEmitLayer;
1185 static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1186 if (auto F = ParseDefinition()) {
1188 if (auto LF = F->IRGen(C)) {
1189 #ifndef MINIMAL_STDERR_OUTPUT
1190 std::cerr << "Read function definition:\n";
1193 J.addModule(C.takeM());
1194 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
1197 // Skip token for error recovery.
1202 static void HandleExtern(SessionContext &S) {
1203 if (auto P = ParseExtern())
1204 S.addPrototypeAST(std::move(P));
1206 // Skip token for error recovery.
1211 static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1212 // Evaluate a top-level expression into an anonymous function.
1213 if (auto F = ParseTopLevelExpr()) {
1215 if (auto ExprFunc = F->IRGen(C)) {
1216 #ifndef MINIMAL_STDERR_OUTPUT
1217 std::cerr << "Expression function:\n";
1220 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1221 // this module as soon as we've executed Function ExprFunc.
1222 auto H = J.addModule(C.takeM());
1224 // Get the address of the JIT'd function in memory.
1225 uint64_t ExprFuncAddr = J.getSymbolAddress("__anon_expr");
1227 // Cast it to the right type (takes no arguments, returns a double) so we
1228 // can call it as a native function.
1229 double (*FP)() = (double (*)())(intptr_t)ExprFuncAddr;
1230 #ifdef MINIMAL_STDERR_OUTPUT
1233 std::cerr << "Evaluated to " << FP() << "\n";
1236 // Remove the function.
1240 // Skip token for error recovery.
1245 /// top ::= definition | external | expression | ';'
1246 static void MainLoop() {
1248 SessionContext S(getGlobalContext());
1251 #ifndef MINIMAL_STDERR_OUTPUT
1252 std::cerr << "ready> ";
1255 case tok_eof: return;
1256 case ';': getNextToken(); break; // ignore top-level semicolons.
1257 case tok_def: HandleDefinition(S, J); break;
1258 case tok_extern: HandleExtern(S); break;
1259 default: HandleTopLevelExpression(S, J); break;
1264 //===----------------------------------------------------------------------===//
1265 // "Library" functions that can be "extern'd" from user code.
1266 //===----------------------------------------------------------------------===//
1268 /// putchard - putchar that takes a double and returns 0.
1270 double putchard(double X) {
1275 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1277 double printd(double X) {
1288 //===----------------------------------------------------------------------===//
1289 // Main driver code.
1290 //===----------------------------------------------------------------------===//
1293 InitializeNativeTarget();
1294 InitializeNativeTargetAsmPrinter();
1295 InitializeNativeTargetAsmParser();
1297 // Install standard binary operators.
1298 // 1 is lowest precedence.
1299 BinopPrecedence['='] = 2;
1300 BinopPrecedence['<'] = 10;
1301 BinopPrecedence['+'] = 20;
1302 BinopPrecedence['-'] = 20;
1303 BinopPrecedence['/'] = 40;
1304 BinopPrecedence['*'] = 40; // highest.
1306 // Prime the first token.
1307 #ifndef MINIMAL_STDERR_OUTPUT
1308 std::cerr << "ready> ";
1312 std::cerr << std::fixed;
1314 // Run the main "interpreter loop" now.