1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/Triple.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DIBuilder.h"
8 #include "llvm/IR/DataLayout.h"
9 #include "llvm/IR/DerivedTypes.h"
10 #include "llvm/IR/IRBuilder.h"
11 #include "llvm/IR/LLVMContext.h"
12 #include "llvm/IR/LegacyPassManager.h"
13 #include "llvm/IR/Module.h"
14 #include "llvm/IR/Verifier.h"
15 #include "llvm/Support/Host.h"
16 #include "llvm/Support/TargetSelect.h"
17 #include "llvm/Transforms/Scalar.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31 // of these for known things.
58 std::string getTokName(int Tok) {
87 return std::string(1, (char)Tok);
94 static IRBuilder<> Builder(getGlobalContext());
98 std::vector<DIScope *> LexicalBlocks;
99 std::map<const PrototypeAST *, DIScope *> FnScopeMap;
101 void emitLocation(ExprAST *AST);
102 DIType *getDoubleTy();
105 static std::string IdentifierStr; // Filled in if tok_identifier
106 static double NumVal; // Filled in if tok_number
107 struct SourceLocation {
111 static SourceLocation CurLoc;
112 static SourceLocation LexLoc = { 1, 0 };
114 static int advance() {
115 int LastChar = getchar();
117 if (LastChar == '\n' || LastChar == '\r') {
125 /// gettok - Return the next token from standard input.
126 static int gettok() {
127 static int LastChar = ' ';
129 // Skip any whitespace.
130 while (isspace(LastChar))
131 LastChar = advance();
135 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136 IdentifierStr = LastChar;
137 while (isalnum((LastChar = advance())))
138 IdentifierStr += LastChar;
140 if (IdentifierStr == "def")
142 if (IdentifierStr == "extern")
144 if (IdentifierStr == "if")
146 if (IdentifierStr == "then")
148 if (IdentifierStr == "else")
150 if (IdentifierStr == "for")
152 if (IdentifierStr == "in")
154 if (IdentifierStr == "binary")
156 if (IdentifierStr == "unary")
158 if (IdentifierStr == "var")
160 return tok_identifier;
163 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
167 LastChar = advance();
168 } while (isdigit(LastChar) || LastChar == '.');
170 NumVal = strtod(NumStr.c_str(), 0);
174 if (LastChar == '#') {
175 // Comment until end of line.
177 LastChar = advance();
178 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
184 // Check for end of file. Don't eat the EOF.
188 // Otherwise, just return the character as its ascii value.
189 int ThisChar = LastChar;
190 LastChar = advance();
194 //===----------------------------------------------------------------------===//
195 // Abstract Syntax Tree (aka Parse Tree)
196 //===----------------------------------------------------------------------===//
199 std::ostream &indent(std::ostream &O, int size) {
200 return O << std::string(size, ' ');
203 /// ExprAST - Base class for all expression nodes.
207 int getLine() const { return Loc.Line; }
208 int getCol() const { return Loc.Col; }
209 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
210 virtual std::ostream &dump(std::ostream &out, int ind) {
211 return out << ':' << getLine() << ':' << getCol() << '\n';
213 virtual ~ExprAST() {}
214 virtual Value *Codegen() = 0;
217 /// NumberExprAST - Expression class for numeric literals like "1.0".
218 class NumberExprAST : public ExprAST {
221 NumberExprAST(double Val) : Val(Val) {}
222 std::ostream &dump(std::ostream &out, int ind) override {
223 return ExprAST::dump(out << Val, ind);
225 Value *Codegen() override;
228 /// VariableExprAST - Expression class for referencing a variable, like "a".
229 class VariableExprAST : public ExprAST {
232 VariableExprAST(SourceLocation Loc, const std::string &Name)
233 : ExprAST(Loc), Name(Name) {}
234 const std::string &getName() const { return Name; }
235 std::ostream &dump(std::ostream &out, int ind) override {
236 return ExprAST::dump(out << Name, ind);
238 Value *Codegen() override;
241 /// UnaryExprAST - Expression class for a unary operator.
242 class UnaryExprAST : public ExprAST {
244 std::unique_ptr<ExprAST> Operand;
246 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
247 : Opcode(Opcode), Operand(std::move(Operand)) {}
248 std::ostream &dump(std::ostream &out, int ind) override {
249 ExprAST::dump(out << "unary" << Opcode, ind);
250 Operand->dump(out, ind + 1);
253 Value *Codegen() override;
256 /// BinaryExprAST - Expression class for a binary operator.
257 class BinaryExprAST : public ExprAST {
259 std::unique_ptr<ExprAST> LHS, RHS;
261 BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr<ExprAST> LHS,
262 std::unique_ptr<ExprAST> RHS)
263 : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
264 std::ostream &dump(std::ostream &out, int ind) override {
265 ExprAST::dump(out << "binary" << Op, ind);
266 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
267 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
270 Value *Codegen() override;
273 /// CallExprAST - Expression class for function calls.
274 class CallExprAST : public ExprAST {
276 std::vector<std::unique_ptr<ExprAST>> Args;
278 CallExprAST(SourceLocation Loc, const std::string &Callee,
279 std::vector<std::unique_ptr<ExprAST>> Args)
280 : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
281 std::ostream &dump(std::ostream &out, int ind) override {
282 ExprAST::dump(out << "call " << Callee, ind);
283 for (const auto &Arg : Args)
284 Arg->dump(indent(out, ind + 1), ind + 1);
287 Value *Codegen() override;
290 /// IfExprAST - Expression class for if/then/else.
291 class IfExprAST : public ExprAST {
292 std::unique_ptr<ExprAST> Cond, Then, Else;
294 IfExprAST(SourceLocation Loc, std::unique_ptr<ExprAST> Cond,
295 std::unique_ptr<ExprAST> Then, std::unique_ptr<ExprAST> Else)
296 : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
297 std::ostream &dump(std::ostream &out, int ind) override {
298 ExprAST::dump(out << "if", ind);
299 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
300 Then->dump(indent(out, ind) << "Then:", ind + 1);
301 Else->dump(indent(out, ind) << "Else:", ind + 1);
304 Value *Codegen() override;
307 /// ForExprAST - Expression class for for/in.
308 class ForExprAST : public ExprAST {
310 std::unique_ptr<ExprAST> Start, End, Step, Body;
312 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
313 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
314 std::unique_ptr<ExprAST> Body)
315 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
316 Step(std::move(Step)), Body(std::move(Body)) {}
317 std::ostream &dump(std::ostream &out, int ind) override {
318 ExprAST::dump(out << "for", ind);
319 Start->dump(indent(out, ind) << "Cond:", ind + 1);
320 End->dump(indent(out, ind) << "End:", ind + 1);
321 Step->dump(indent(out, ind) << "Step:", ind + 1);
322 Body->dump(indent(out, ind) << "Body:", ind + 1);
325 Value *Codegen() override;
328 /// VarExprAST - Expression class for var/in
329 class VarExprAST : public ExprAST {
330 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
331 std::unique_ptr<ExprAST> Body;
333 VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
334 std::unique_ptr<ExprAST> Body)
335 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
336 std::ostream &dump(std::ostream &out, int ind) override {
337 ExprAST::dump(out << "var", ind);
338 for (const auto &NamedVar : VarNames)
339 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
340 Body->dump(indent(out, ind) << "Body:", ind + 1);
343 Value *Codegen() override;
346 /// PrototypeAST - This class represents the "prototype" for a function,
347 /// which captures its argument names as well as if it is an operator.
350 std::vector<std::string> Args;
352 unsigned Precedence; // Precedence if a binary op.
355 PrototypeAST(SourceLocation Loc, const std::string &Name,
356 std::vector<std::string> Args, bool IsOperator = false,
358 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
359 Precedence(Prec), Line(Loc.Line) {}
361 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
362 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
364 char getOperatorName() const {
365 assert(isUnaryOp() || isBinaryOp());
366 return Name[Name.size() - 1];
369 unsigned getBinaryPrecedence() const { return Precedence; }
373 void CreateArgumentAllocas(Function *F);
374 const std::vector<std::string> &getArgs() const { return Args; }
377 /// FunctionAST - This class represents a function definition itself.
379 std::unique_ptr<PrototypeAST> Proto;
380 std::unique_ptr<ExprAST> Body;
382 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
383 std::unique_ptr<ExprAST> Body)
384 : Proto(std::move(Proto)), Body(std::move(Body)) {}
386 std::ostream &dump(std::ostream &out, int ind) {
387 indent(out, ind) << "FunctionAST\n";
389 indent(out, ind) << "Body:";
390 return Body ? Body->dump(out, ind) : out << "null\n";
395 } // end anonymous namespace
397 //===----------------------------------------------------------------------===//
399 //===----------------------------------------------------------------------===//
401 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
402 /// token the parser is looking at. getNextToken reads another token from the
403 /// lexer and updates CurTok with its results.
405 static int getNextToken() { return CurTok = gettok(); }
407 /// BinopPrecedence - This holds the precedence for each binary operator that is
409 static std::map<char, int> BinopPrecedence;
411 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
412 static int GetTokPrecedence() {
413 if (!isascii(CurTok))
416 // Make sure it's a declared binop.
417 int TokPrec = BinopPrecedence[CurTok];
423 /// Error* - These are little helper functions for error handling.
424 std::unique_ptr<ExprAST> Error(const char *Str) {
425 fprintf(stderr, "Error: %s\n", Str);
428 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
432 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
437 static std::unique_ptr<ExprAST> ParseExpression();
441 /// ::= identifier '(' expression* ')'
442 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
443 std::string IdName = IdentifierStr;
445 SourceLocation LitLoc = CurLoc;
447 getNextToken(); // eat identifier.
449 if (CurTok != '(') // Simple variable ref.
450 return llvm::make_unique<VariableExprAST>(LitLoc, IdName);
453 getNextToken(); // eat (
454 std::vector<std::unique_ptr<ExprAST>> Args;
457 auto Arg = ParseExpression();
460 Args.push_back(std::move(Arg));
466 return Error("Expected ')' or ',' in argument list");
474 return llvm::make_unique<CallExprAST>(LitLoc, IdName, std::move(Args));
477 /// numberexpr ::= number
478 static std::unique_ptr<ExprAST> ParseNumberExpr() {
479 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
480 getNextToken(); // consume the number
481 return std::move(Result);
484 /// parenexpr ::= '(' expression ')'
485 static std::unique_ptr<ExprAST> ParseParenExpr() {
486 getNextToken(); // eat (.
487 auto V = ParseExpression();
492 return Error("expected ')'");
493 getNextToken(); // eat ).
497 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
498 static std::unique_ptr<ExprAST> ParseIfExpr() {
499 SourceLocation IfLoc = CurLoc;
501 getNextToken(); // eat the if.
504 auto Cond = ParseExpression();
508 if (CurTok != tok_then)
509 return Error("expected then");
510 getNextToken(); // eat the then
512 auto Then = ParseExpression();
516 if (CurTok != tok_else)
517 return Error("expected else");
521 auto Else = ParseExpression();
525 return llvm::make_unique<IfExprAST>(IfLoc, std::move(Cond), std::move(Then),
529 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
530 static std::unique_ptr<ExprAST> ParseForExpr() {
531 getNextToken(); // eat the for.
533 if (CurTok != tok_identifier)
534 return Error("expected identifier after for");
536 std::string IdName = IdentifierStr;
537 getNextToken(); // eat identifier.
540 return Error("expected '=' after for");
541 getNextToken(); // eat '='.
543 auto Start = ParseExpression();
547 return Error("expected ',' after for start value");
550 auto End = ParseExpression();
554 // The step value is optional.
555 std::unique_ptr<ExprAST> Step;
558 Step = ParseExpression();
563 if (CurTok != tok_in)
564 return Error("expected 'in' after for");
565 getNextToken(); // eat 'in'.
567 auto Body = ParseExpression();
571 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
572 std::move(Step), std::move(Body));
575 /// varexpr ::= 'var' identifier ('=' expression)?
576 // (',' identifier ('=' expression)?)* 'in' expression
577 static std::unique_ptr<ExprAST> ParseVarExpr() {
578 getNextToken(); // eat the var.
580 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
582 // At least one variable name is required.
583 if (CurTok != tok_identifier)
584 return Error("expected identifier after var");
587 std::string Name = IdentifierStr;
588 getNextToken(); // eat identifier.
590 // Read the optional initializer.
591 std::unique_ptr<ExprAST> Init = nullptr;
593 getNextToken(); // eat the '='.
595 Init = ParseExpression();
600 VarNames.push_back(std::make_pair(Name, std::move(Init)));
602 // End of var list, exit loop.
605 getNextToken(); // eat the ','.
607 if (CurTok != tok_identifier)
608 return Error("expected identifier list after var");
611 // At this point, we have to have 'in'.
612 if (CurTok != tok_in)
613 return Error("expected 'in' keyword after 'var'");
614 getNextToken(); // eat 'in'.
616 auto Body = ParseExpression();
620 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
624 /// ::= identifierexpr
630 static std::unique_ptr<ExprAST> ParsePrimary() {
633 return Error("unknown token when expecting an expression");
635 return ParseIdentifierExpr();
637 return ParseNumberExpr();
639 return ParseParenExpr();
641 return ParseIfExpr();
643 return ParseForExpr();
645 return ParseVarExpr();
652 static std::unique_ptr<ExprAST> ParseUnary() {
653 // If the current token is not an operator, it must be a primary expr.
654 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
655 return ParsePrimary();
657 // If this is a unary operator, read it.
660 if (auto Operand = ParseUnary())
661 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
667 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
668 // If this is a binop, find its precedence.
670 int TokPrec = GetTokPrecedence();
672 // If this is a binop that binds at least as tightly as the current binop,
673 // consume it, otherwise we are done.
674 if (TokPrec < ExprPrec)
677 // Okay, we know this is a binop.
679 SourceLocation BinLoc = CurLoc;
680 getNextToken(); // eat binop
682 // Parse the unary expression after the binary operator.
683 auto RHS = ParseUnary();
687 // If BinOp binds less tightly with RHS than the operator after RHS, let
688 // the pending operator take RHS as its LHS.
689 int NextPrec = GetTokPrecedence();
690 if (TokPrec < NextPrec) {
691 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
697 LHS = llvm::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
703 /// ::= unary binoprhs
705 static std::unique_ptr<ExprAST> ParseExpression() {
706 auto LHS = ParseUnary();
710 return ParseBinOpRHS(0, std::move(LHS));
714 /// ::= id '(' id* ')'
715 /// ::= binary LETTER number? (id, id)
716 /// ::= unary LETTER (id)
717 static std::unique_ptr<PrototypeAST> ParsePrototype() {
720 SourceLocation FnLoc = CurLoc;
722 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
723 unsigned BinaryPrecedence = 30;
727 return ErrorP("Expected function name in prototype");
729 FnName = IdentifierStr;
735 if (!isascii(CurTok))
736 return ErrorP("Expected unary operator");
738 FnName += (char)CurTok;
744 if (!isascii(CurTok))
745 return ErrorP("Expected binary operator");
747 FnName += (char)CurTok;
751 // Read the precedence if present.
752 if (CurTok == tok_number) {
753 if (NumVal < 1 || NumVal > 100)
754 return ErrorP("Invalid precedecnce: must be 1..100");
755 BinaryPrecedence = (unsigned)NumVal;
762 return ErrorP("Expected '(' in prototype");
764 std::vector<std::string> ArgNames;
765 while (getNextToken() == tok_identifier)
766 ArgNames.push_back(IdentifierStr);
768 return ErrorP("Expected ')' in prototype");
771 getNextToken(); // eat ')'.
773 // Verify right number of names for operator.
774 if (Kind && ArgNames.size() != Kind)
775 return ErrorP("Invalid number of operands for operator");
777 return llvm::make_unique<PrototypeAST>(FnLoc, FnName, ArgNames, Kind != 0,
781 /// definition ::= 'def' prototype expression
782 static std::unique_ptr<FunctionAST> ParseDefinition() {
783 getNextToken(); // eat def.
784 auto Proto = ParsePrototype();
788 if (auto E = ParseExpression())
789 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
793 /// toplevelexpr ::= expression
794 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
795 SourceLocation FnLoc = CurLoc;
796 if (auto E = ParseExpression()) {
797 // Make an anonymous proto.
799 llvm::make_unique<PrototypeAST>(FnLoc, "main", std::vector<std::string>());
800 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
805 /// external ::= 'extern' prototype
806 static std::unique_ptr<PrototypeAST> ParseExtern() {
807 getNextToken(); // eat extern.
808 return ParsePrototype();
811 //===----------------------------------------------------------------------===//
812 // Debug Info Support
813 //===----------------------------------------------------------------------===//
815 static DIBuilder *DBuilder;
817 DIType *DebugInfo::getDoubleTy() {
821 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
825 void DebugInfo::emitLocation(ExprAST *AST) {
827 return Builder.SetCurrentDebugLocation(DebugLoc());
829 if (LexicalBlocks.empty())
832 Scope = LexicalBlocks.back();
833 Builder.SetCurrentDebugLocation(
834 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
837 static DISubroutineType *CreateFunctionType(unsigned NumArgs, DIFile *Unit) {
838 SmallVector<Metadata *, 8> EltTys;
839 DIType *DblTy = KSDbgInfo.getDoubleTy();
841 // Add the result type.
842 EltTys.push_back(DblTy);
844 for (unsigned i = 0, e = NumArgs; i != e; ++i)
845 EltTys.push_back(DblTy);
847 return DBuilder->createSubroutineType(Unit,
848 DBuilder->getOrCreateTypeArray(EltTys));
851 //===----------------------------------------------------------------------===//
853 //===----------------------------------------------------------------------===//
855 static Module *TheModule;
856 static std::map<std::string, AllocaInst *> NamedValues;
857 static legacy::FunctionPassManager *TheFPM;
859 Value *ErrorV(const char *Str) {
864 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
865 /// the function. This is used for mutable variables etc.
866 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
867 const std::string &VarName) {
868 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
869 TheFunction->getEntryBlock().begin());
870 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
874 Value *NumberExprAST::Codegen() {
875 KSDbgInfo.emitLocation(this);
876 return ConstantFP::get(getGlobalContext(), APFloat(Val));
879 Value *VariableExprAST::Codegen() {
880 // Look this variable up in the function.
881 Value *V = NamedValues[Name];
883 return ErrorV("Unknown variable name");
885 KSDbgInfo.emitLocation(this);
887 return Builder.CreateLoad(V, Name.c_str());
890 Value *UnaryExprAST::Codegen() {
891 Value *OperandV = Operand->Codegen();
895 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
897 return ErrorV("Unknown unary operator");
899 KSDbgInfo.emitLocation(this);
900 return Builder.CreateCall(F, OperandV, "unop");
903 Value *BinaryExprAST::Codegen() {
904 KSDbgInfo.emitLocation(this);
906 // Special case '=' because we don't want to emit the LHS as an expression.
908 // Assignment requires the LHS to be an identifier.
909 // This assume we're building without RTTI because LLVM builds that way by
910 // default. If you build LLVM with RTTI this can be changed to a
911 // dynamic_cast for automatic error checking.
912 VariableExprAST *LHSE = static_cast<VariableExprAST*>(LHS.get());
914 return ErrorV("destination of '=' must be a variable");
916 Value *Val = RHS->Codegen();
921 Value *Variable = NamedValues[LHSE->getName()];
923 return ErrorV("Unknown variable name");
925 Builder.CreateStore(Val, Variable);
929 Value *L = LHS->Codegen();
930 Value *R = RHS->Codegen();
936 return Builder.CreateFAdd(L, R, "addtmp");
938 return Builder.CreateFSub(L, R, "subtmp");
940 return Builder.CreateFMul(L, R, "multmp");
942 L = Builder.CreateFCmpULT(L, R, "cmptmp");
943 // Convert bool 0/1 to double 0.0 or 1.0
944 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
950 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
952 Function *F = TheModule->getFunction(std::string("binary") + Op);
953 assert(F && "binary operator not found!");
955 Value *Ops[] = { L, R };
956 return Builder.CreateCall(F, Ops, "binop");
959 Value *CallExprAST::Codegen() {
960 KSDbgInfo.emitLocation(this);
962 // Look up the name in the global module table.
963 Function *CalleeF = TheModule->getFunction(Callee);
965 return ErrorV("Unknown function referenced");
967 // If argument mismatch error.
968 if (CalleeF->arg_size() != Args.size())
969 return ErrorV("Incorrect # arguments passed");
971 std::vector<Value *> ArgsV;
972 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
973 ArgsV.push_back(Args[i]->Codegen());
978 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
981 Value *IfExprAST::Codegen() {
982 KSDbgInfo.emitLocation(this);
984 Value *CondV = Cond->Codegen();
988 // Convert condition to a bool by comparing equal to 0.0.
989 CondV = Builder.CreateFCmpONE(
990 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
992 Function *TheFunction = Builder.GetInsertBlock()->getParent();
994 // Create blocks for the then and else cases. Insert the 'then' block at the
995 // end of the function.
997 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
998 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
999 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1001 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1004 Builder.SetInsertPoint(ThenBB);
1006 Value *ThenV = Then->Codegen();
1010 Builder.CreateBr(MergeBB);
1011 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1012 ThenBB = Builder.GetInsertBlock();
1015 TheFunction->getBasicBlockList().push_back(ElseBB);
1016 Builder.SetInsertPoint(ElseBB);
1018 Value *ElseV = Else->Codegen();
1022 Builder.CreateBr(MergeBB);
1023 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1024 ElseBB = Builder.GetInsertBlock();
1026 // Emit merge block.
1027 TheFunction->getBasicBlockList().push_back(MergeBB);
1028 Builder.SetInsertPoint(MergeBB);
1030 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1032 PN->addIncoming(ThenV, ThenBB);
1033 PN->addIncoming(ElseV, ElseBB);
1037 Value *ForExprAST::Codegen() {
1039 // var = alloca double
1041 // start = startexpr
1042 // store start -> var
1050 // endcond = endexpr
1052 // curvar = load var
1053 // nextvar = curvar + step
1054 // store nextvar -> var
1055 // br endcond, loop, endloop
1058 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1060 // Create an alloca for the variable in the entry block.
1061 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1063 KSDbgInfo.emitLocation(this);
1065 // Emit the start code first, without 'variable' in scope.
1066 Value *StartVal = Start->Codegen();
1070 // Store the value into the alloca.
1071 Builder.CreateStore(StartVal, Alloca);
1073 // Make the new basic block for the loop header, inserting after current
1075 BasicBlock *LoopBB =
1076 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1078 // Insert an explicit fall through from the current block to the LoopBB.
1079 Builder.CreateBr(LoopBB);
1081 // Start insertion in LoopBB.
1082 Builder.SetInsertPoint(LoopBB);
1084 // Within the loop, the variable is defined equal to the PHI node. If it
1085 // shadows an existing variable, we have to restore it, so save it now.
1086 AllocaInst *OldVal = NamedValues[VarName];
1087 NamedValues[VarName] = Alloca;
1089 // Emit the body of the loop. This, like any other expr, can change the
1090 // current BB. Note that we ignore the value computed by the body, but don't
1092 if (!Body->Codegen())
1095 // Emit the step value.
1098 StepVal = Step->Codegen();
1102 // If not specified, use 1.0.
1103 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1106 // Compute the end condition.
1107 Value *EndCond = End->Codegen();
1111 // Reload, increment, and restore the alloca. This handles the case where
1112 // the body of the loop mutates the variable.
1113 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1114 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1115 Builder.CreateStore(NextVar, Alloca);
1117 // Convert condition to a bool by comparing equal to 0.0.
1118 EndCond = Builder.CreateFCmpONE(
1119 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1121 // Create the "after loop" block and insert it.
1122 BasicBlock *AfterBB =
1123 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1125 // Insert the conditional branch into the end of LoopEndBB.
1126 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1128 // Any new code will be inserted in AfterBB.
1129 Builder.SetInsertPoint(AfterBB);
1131 // Restore the unshadowed variable.
1133 NamedValues[VarName] = OldVal;
1135 NamedValues.erase(VarName);
1137 // for expr always returns 0.0.
1138 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1141 Value *VarExprAST::Codegen() {
1142 std::vector<AllocaInst *> OldBindings;
1144 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1146 // Register all variables and emit their initializer.
1147 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1148 const std::string &VarName = VarNames[i].first;
1149 ExprAST *Init = VarNames[i].second.get();
1151 // Emit the initializer before adding the variable to scope, this prevents
1152 // the initializer from referencing the variable itself, and permits stuff
1155 // var a = a in ... # refers to outer 'a'.
1158 InitVal = Init->Codegen();
1161 } else { // If not specified, use 0.0.
1162 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1165 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1166 Builder.CreateStore(InitVal, Alloca);
1168 // Remember the old variable binding so that we can restore the binding when
1170 OldBindings.push_back(NamedValues[VarName]);
1172 // Remember this binding.
1173 NamedValues[VarName] = Alloca;
1176 KSDbgInfo.emitLocation(this);
1178 // Codegen the body, now that all vars are in scope.
1179 Value *BodyVal = Body->Codegen();
1183 // Pop all our variables from scope.
1184 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1185 NamedValues[VarNames[i].first] = OldBindings[i];
1187 // Return the body computation.
1191 Function *PrototypeAST::Codegen() {
1192 // Make the function type: double(double,double) etc.
1193 std::vector<Type *> Doubles(Args.size(),
1194 Type::getDoubleTy(getGlobalContext()));
1196 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1199 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1201 // If F conflicted, there was already something named 'Name'. If it has a
1202 // body, don't allow redefinition or reextern.
1203 if (F->getName() != Name) {
1204 // Delete the one we just made and get the existing one.
1205 F->eraseFromParent();
1206 F = TheModule->getFunction(Name);
1208 // If F already has a body, reject this.
1210 ErrorF("redefinition of function");
1214 // If F took a different number of args, reject.
1215 if (F->arg_size() != Args.size()) {
1216 ErrorF("redefinition of function with different # args");
1221 // Set names for all arguments.
1223 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1225 AI->setName(Args[Idx]);
1227 // Create a subprogram DIE for this function.
1228 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1229 KSDbgInfo.TheCU->getDirectory());
1230 DIScope *FContext = Unit;
1231 unsigned LineNo = Line;
1232 unsigned ScopeLine = Line;
1233 DISubprogram *SP = DBuilder->createFunction(
1234 FContext, Name, StringRef(), Unit, LineNo,
1235 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
1236 true /* definition */, ScopeLine, DINode::FlagPrototyped, false, F);
1238 KSDbgInfo.FnScopeMap[this] = SP;
1242 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1243 /// argument in the symbol table so that references to it will succeed.
1244 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1245 Function::arg_iterator AI = F->arg_begin();
1246 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1247 // Create an alloca for this variable.
1248 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1250 // Create a debug descriptor for the variable.
1251 DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
1252 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1253 KSDbgInfo.TheCU->getDirectory());
1254 DILocalVariable *D = DBuilder->createParameterVariable(
1255 Scope, Args[Idx], Idx + 1, Unit, Line, KSDbgInfo.getDoubleTy(), true);
1257 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
1258 DebugLoc::get(Line, 0, Scope),
1259 Builder.GetInsertBlock());
1261 // Store the initial value into the alloca.
1262 Builder.CreateStore(AI, Alloca);
1264 // Add arguments to variable symbol table.
1265 NamedValues[Args[Idx]] = Alloca;
1269 Function *FunctionAST::Codegen() {
1270 NamedValues.clear();
1272 Function *TheFunction = Proto->Codegen();
1276 // Push the current scope.
1277 KSDbgInfo.LexicalBlocks.push_back(KSDbgInfo.FnScopeMap[Proto.get()]);
1279 // Unset the location for the prologue emission (leading instructions with no
1280 // location in a function are considered part of the prologue and the debugger
1281 // will run past them when breaking on a function)
1282 KSDbgInfo.emitLocation(nullptr);
1284 // If this is an operator, install it.
1285 if (Proto->isBinaryOp())
1286 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1288 // Create a new basic block to start insertion into.
1289 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1290 Builder.SetInsertPoint(BB);
1292 // Add all arguments to the symbol table and create their allocas.
1293 Proto->CreateArgumentAllocas(TheFunction);
1295 KSDbgInfo.emitLocation(Body.get());
1297 if (Value *RetVal = Body->Codegen()) {
1298 // Finish off the function.
1299 Builder.CreateRet(RetVal);
1301 // Pop off the lexical block for the function.
1302 KSDbgInfo.LexicalBlocks.pop_back();
1304 // Validate the generated code, checking for consistency.
1305 verifyFunction(*TheFunction);
1307 // Optimize the function.
1308 TheFPM->run(*TheFunction);
1313 // Error reading body, remove function.
1314 TheFunction->eraseFromParent();
1316 if (Proto->isBinaryOp())
1317 BinopPrecedence.erase(Proto->getOperatorName());
1319 // Pop off the lexical block for the function since we added it
1321 KSDbgInfo.LexicalBlocks.pop_back();
1326 //===----------------------------------------------------------------------===//
1327 // Top-Level parsing and JIT Driver
1328 //===----------------------------------------------------------------------===//
1330 static ExecutionEngine *TheExecutionEngine;
1332 static void HandleDefinition() {
1333 if (auto FnAST = ParseDefinition()) {
1334 if (!FnAST->Codegen()) {
1335 fprintf(stderr, "Error reading function definition:");
1338 // Skip token for error recovery.
1343 static void HandleExtern() {
1344 if (auto ProtoAST = ParseExtern()) {
1345 if (!ProtoAST->Codegen()) {
1346 fprintf(stderr, "Error reading extern");
1349 // Skip token for error recovery.
1354 static void HandleTopLevelExpression() {
1355 // Evaluate a top-level expression into an anonymous function.
1356 if (auto FnAST = ParseTopLevelExpr()) {
1357 if (!FnAST->Codegen()) {
1358 fprintf(stderr, "Error generating code for top level expr");
1361 // Skip token for error recovery.
1366 /// top ::= definition | external | expression | ';'
1367 static void MainLoop() {
1374 break; // ignore top-level semicolons.
1382 HandleTopLevelExpression();
1388 //===----------------------------------------------------------------------===//
1389 // "Library" functions that can be "extern'd" from user code.
1390 //===----------------------------------------------------------------------===//
1392 /// putchard - putchar that takes a double and returns 0.
1393 extern "C" double putchard(double X) {
1398 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1399 extern "C" double printd(double X) {
1404 //===----------------------------------------------------------------------===//
1405 // Main driver code.
1406 //===----------------------------------------------------------------------===//
1409 InitializeNativeTarget();
1410 InitializeNativeTargetAsmPrinter();
1411 InitializeNativeTargetAsmParser();
1412 LLVMContext &Context = getGlobalContext();
1414 // Install standard binary operators.
1415 // 1 is lowest precedence.
1416 BinopPrecedence['='] = 2;
1417 BinopPrecedence['<'] = 10;
1418 BinopPrecedence['+'] = 20;
1419 BinopPrecedence['-'] = 20;
1420 BinopPrecedence['*'] = 40; // highest.
1422 // Prime the first token.
1425 // Make the module, which holds all the code.
1426 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1427 TheModule = Owner.get();
1429 // Add the current debug info version into the module.
1430 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1431 DEBUG_METADATA_VERSION);
1433 // Darwin only supports dwarf2.
1434 if (Triple(sys::getProcessTriple()).isOSDarwin())
1435 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1437 // Construct the DIBuilder, we do this here because we need the module.
1438 DBuilder = new DIBuilder(*TheModule);
1440 // Create the compile unit for the module.
1441 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1442 // but we'd like actual source locations.
1443 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1444 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1446 // Create the JIT. This takes ownership of the module.
1448 TheExecutionEngine =
1449 EngineBuilder(std::move(Owner))
1450 .setErrorStr(&ErrStr)
1451 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1453 if (!TheExecutionEngine) {
1454 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1458 legacy::FunctionPassManager OurFPM(TheModule);
1460 // Set up the optimizer pipeline. Start with registering info about how the
1461 // target lays out data structures.
1462 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1464 // Provide basic AliasAnalysis support for GVN.
1465 OurFPM.add(createBasicAliasAnalysisPass());
1466 // Promote allocas to registers.
1467 OurFPM.add(createPromoteMemoryToRegisterPass());
1468 // Do simple "peephole" optimizations and bit-twiddling optzns.
1469 OurFPM.add(createInstructionCombiningPass());
1470 // Reassociate expressions.
1471 OurFPM.add(createReassociatePass());
1472 // Eliminate Common SubExpressions.
1473 OurFPM.add(createGVNPass());
1474 // Simplify the control flow graph (deleting unreachable blocks, etc).
1475 OurFPM.add(createCFGSimplificationPass());
1477 OurFPM.doInitialization();
1479 // Set the global so the code gen can use this.
1482 // Run the main "interpreter loop" now.
1487 // Finalize the debug info.
1488 DBuilder->finalize();
1490 // Print out all of the generated code.