blob: 58b7ce1ceda2115333eede7decbab314e6242c47 [file] [log] [blame]
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001#include "llvm/ADT/APFloat.h"
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00002#include "llvm/ADT/STLExtras.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +00003#include "llvm/IR/BasicBlock.h"
4#include "llvm/IR/Constants.h"
5#include "llvm/IR/DerivedTypes.h"
6#include "llvm/IR/Function.h"
7#include "llvm/IR/Instructions.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00008#include "llvm/IR/IRBuilder.h"
9#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000010#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +000011#include "llvm/IR/Module.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000012#include "llvm/IR/Type.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +000013#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000014#include "llvm/Support/TargetSelect.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000015#include "llvm/Target/TargetMachine.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000016#include "llvm/Transforms/Scalar.h"
Chandler Carruthec5872b2016-03-11 12:10:15 +000017#include "llvm/Transforms/Scalar/GVN.h"
Lang Hames2d789c32015-08-26 03:07:41 +000018#include "../include/KaleidoscopeJIT.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +000019#include <algorithm>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000020#include <cassert>
21#include <cctype>
22#include <cstdint>
23#include <cstdio>
24#include <cstdlib>
25#include <map>
26#include <memory>
27#include <string>
28#include <utility>
29#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000030
Nick Lewycky109af622009-04-12 20:47:23 +000031using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000032using namespace llvm::orc;
Nick Lewycky109af622009-04-12 20:47:23 +000033
34//===----------------------------------------------------------------------===//
35// Lexer
36//===----------------------------------------------------------------------===//
37
38// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
39// of these for known things.
40enum Token {
41 tok_eof = -1,
42
43 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000044 tok_def = -2,
45 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000046
47 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000048 tok_identifier = -4,
49 tok_number = -5,
50
Nick Lewycky109af622009-04-12 20:47:23 +000051 // control
Eric Christopherc0239362014-12-08 18:12:28 +000052 tok_if = -6,
53 tok_then = -7,
54 tok_else = -8,
55 tok_for = -9,
56 tok_in = -10,
57
Nick Lewycky109af622009-04-12 20:47:23 +000058 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000059 tok_binary = -11,
60 tok_unary = -12,
61
Nick Lewycky109af622009-04-12 20:47:23 +000062 // var definition
63 tok_var = -13
64};
65
Eric Christopherc0239362014-12-08 18:12:28 +000066static std::string IdentifierStr; // Filled in if tok_identifier
67static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000068
69/// gettok - Return the next token from standard input.
70static int gettok() {
71 static int LastChar = ' ';
72
73 // Skip any whitespace.
74 while (isspace(LastChar))
75 LastChar = getchar();
76
77 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
78 IdentifierStr = LastChar;
79 while (isalnum((LastChar = getchar())))
80 IdentifierStr += LastChar;
81
Eric Christopherc0239362014-12-08 18:12:28 +000082 if (IdentifierStr == "def")
83 return tok_def;
84 if (IdentifierStr == "extern")
85 return tok_extern;
86 if (IdentifierStr == "if")
87 return tok_if;
88 if (IdentifierStr == "then")
89 return tok_then;
90 if (IdentifierStr == "else")
91 return tok_else;
92 if (IdentifierStr == "for")
93 return tok_for;
94 if (IdentifierStr == "in")
95 return tok_in;
96 if (IdentifierStr == "binary")
97 return tok_binary;
98 if (IdentifierStr == "unary")
99 return tok_unary;
100 if (IdentifierStr == "var")
101 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +0000102 return tok_identifier;
103 }
104
Eric Christopherc0239362014-12-08 18:12:28 +0000105 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +0000106 std::string NumStr;
107 do {
108 NumStr += LastChar;
109 LastChar = getchar();
110 } while (isdigit(LastChar) || LastChar == '.');
111
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000112 NumVal = strtod(NumStr.c_str(), nullptr);
Nick Lewycky109af622009-04-12 20:47:23 +0000113 return tok_number;
114 }
115
116 if (LastChar == '#') {
117 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000118 do
119 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000120 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000121
Nick Lewycky109af622009-04-12 20:47:23 +0000122 if (LastChar != EOF)
123 return gettok();
124 }
Eric Christopherc0239362014-12-08 18:12:28 +0000125
Nick Lewycky109af622009-04-12 20:47:23 +0000126 // Check for end of file. Don't eat the EOF.
127 if (LastChar == EOF)
128 return tok_eof;
129
130 // Otherwise, just return the character as its ascii value.
131 int ThisChar = LastChar;
132 LastChar = getchar();
133 return ThisChar;
134}
135
136//===----------------------------------------------------------------------===//
137// Abstract Syntax Tree (aka Parse Tree)
138//===----------------------------------------------------------------------===//
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000139
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000140namespace {
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000141
Nick Lewycky109af622009-04-12 20:47:23 +0000142/// ExprAST - Base class for all expression nodes.
143class ExprAST {
144public:
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000145 virtual ~ExprAST() = default;
146
Lang Hames2d789c32015-08-26 03:07:41 +0000147 virtual Value *codegen() = 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000148};
149
150/// NumberExprAST - Expression class for numeric literals like "1.0".
151class NumberExprAST : public ExprAST {
152 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000153
Nick Lewycky109af622009-04-12 20:47:23 +0000154public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000155 NumberExprAST(double Val) : Val(Val) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000156
Lang Hames2d789c32015-08-26 03:07:41 +0000157 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000158};
159
160/// VariableExprAST - Expression class for referencing a variable, like "a".
161class VariableExprAST : public ExprAST {
162 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000163
Nick Lewycky109af622009-04-12 20:47:23 +0000164public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000165 VariableExprAST(const std::string &Name) : Name(Name) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000166
Lang Hames2d789c32015-08-26 03:07:41 +0000167 Value *codegen() override;
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000168 const std::string &getName() const { return Name; }
Nick Lewycky109af622009-04-12 20:47:23 +0000169};
170
171/// UnaryExprAST - Expression class for a unary operator.
172class UnaryExprAST : public ExprAST {
173 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000174 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000175
Nick Lewycky109af622009-04-12 20:47:23 +0000176public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000177 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
178 : Opcode(Opcode), Operand(std::move(Operand)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000179
Lang Hames2d789c32015-08-26 03:07:41 +0000180 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000181};
182
183/// BinaryExprAST - Expression class for a binary operator.
184class BinaryExprAST : public ExprAST {
185 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000186 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000187
Nick Lewycky109af622009-04-12 20:47:23 +0000188public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000189 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
190 std::unique_ptr<ExprAST> RHS)
191 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000192
Lang Hames2d789c32015-08-26 03:07:41 +0000193 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000194};
195
196/// CallExprAST - Expression class for function calls.
197class CallExprAST : public ExprAST {
198 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000199 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000200
Nick Lewycky109af622009-04-12 20:47:23 +0000201public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000202 CallExprAST(const std::string &Callee,
203 std::vector<std::unique_ptr<ExprAST>> Args)
204 : Callee(Callee), Args(std::move(Args)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000205
Lang Hames2d789c32015-08-26 03:07:41 +0000206 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000207};
208
209/// IfExprAST - Expression class for if/then/else.
210class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000211 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000212
Nick Lewycky109af622009-04-12 20:47:23 +0000213public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000214 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
215 std::unique_ptr<ExprAST> Else)
216 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000217
Lang Hames2d789c32015-08-26 03:07:41 +0000218 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000219};
220
221/// ForExprAST - Expression class for for/in.
222class ForExprAST : public ExprAST {
223 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000224 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000225
Nick Lewycky109af622009-04-12 20:47:23 +0000226public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000227 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
228 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
229 std::unique_ptr<ExprAST> Body)
230 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
231 Step(std::move(Step)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000232
Lang Hames2d789c32015-08-26 03:07:41 +0000233 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000234};
235
236/// VarExprAST - Expression class for var/in
237class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000238 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
239 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000240
Nick Lewycky109af622009-04-12 20:47:23 +0000241public:
Lang Hames59b0da82015-08-19 18:15:58 +0000242 VarExprAST(
243 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
244 std::unique_ptr<ExprAST> Body)
245 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000246
Lang Hames2d789c32015-08-26 03:07:41 +0000247 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000248};
249
250/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000251/// which captures its name, and its argument names (thus implicitly the number
252/// of arguments the function takes), as well as if it is an operator.
Nick Lewycky109af622009-04-12 20:47:23 +0000253class PrototypeAST {
254 std::string Name;
255 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000256 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000257 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000258
Nick Lewycky109af622009-04-12 20:47:23 +0000259public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000260 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
261 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000262 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
263 Precedence(Prec) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000264
Lang Hames2d789c32015-08-26 03:07:41 +0000265 Function *codegen();
266 const std::string &getName() const { return Name; }
Eric Christopherc0239362014-12-08 18:12:28 +0000267
Lang Hames09bf4c12015-08-18 18:11:06 +0000268 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
269 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000270
Nick Lewycky109af622009-04-12 20:47:23 +0000271 char getOperatorName() const {
272 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000273 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000274 }
Eric Christopherc0239362014-12-08 18:12:28 +0000275
Nick Lewycky109af622009-04-12 20:47:23 +0000276 unsigned getBinaryPrecedence() const { return Precedence; }
Nick Lewycky109af622009-04-12 20:47:23 +0000277};
278
279/// FunctionAST - This class represents a function definition itself.
280class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000281 std::unique_ptr<PrototypeAST> Proto;
282 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000283
Nick Lewycky109af622009-04-12 20:47:23 +0000284public:
Lang Hames59b0da82015-08-19 18:15:58 +0000285 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
286 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000287 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000288
Lang Hames2d789c32015-08-26 03:07:41 +0000289 Function *codegen();
Nick Lewycky109af622009-04-12 20:47:23 +0000290};
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000291
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000292} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000293
294//===----------------------------------------------------------------------===//
295// Parser
296//===----------------------------------------------------------------------===//
297
298/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000299/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000300/// lexer and updates CurTok with its results.
301static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000302static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000303
304/// BinopPrecedence - This holds the precedence for each binary operator that is
305/// defined.
306static std::map<char, int> BinopPrecedence;
307
308/// GetTokPrecedence - Get the precedence of the pending binary operator token.
309static int GetTokPrecedence() {
310 if (!isascii(CurTok))
311 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000312
Nick Lewycky109af622009-04-12 20:47:23 +0000313 // Make sure it's a declared binop.
314 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000315 if (TokPrec <= 0)
316 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000317 return TokPrec;
318}
319
Lang Hamesf9878c52016-03-25 17:33:32 +0000320/// LogError* - These are little helper functions for error handling.
321std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000322 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000323 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000324}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000325
Lang Hamesf9878c52016-03-25 17:33:32 +0000326std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
327 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000328 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000329}
Nick Lewycky109af622009-04-12 20:47:23 +0000330
Lang Hames09bf4c12015-08-18 18:11:06 +0000331static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000332
Lang Hames59b0da82015-08-19 18:15:58 +0000333/// numberexpr ::= number
334static std::unique_ptr<ExprAST> ParseNumberExpr() {
335 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
336 getNextToken(); // consume the number
337 return std::move(Result);
338}
339
340/// parenexpr ::= '(' expression ')'
341static std::unique_ptr<ExprAST> ParseParenExpr() {
342 getNextToken(); // eat (.
343 auto V = ParseExpression();
344 if (!V)
345 return nullptr;
346
347 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000348 return LogError("expected ')'");
Lang Hames59b0da82015-08-19 18:15:58 +0000349 getNextToken(); // eat ).
350 return V;
351}
352
Nick Lewycky109af622009-04-12 20:47:23 +0000353/// identifierexpr
354/// ::= identifier
355/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000356static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000357 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000358
359 getNextToken(); // eat identifier.
360
Nick Lewycky109af622009-04-12 20:47:23 +0000361 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000362 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000363
Nick Lewycky109af622009-04-12 20:47:23 +0000364 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000365 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000366 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000367 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000368 while (true) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000369 if (auto Arg = ParseExpression())
370 Args.push_back(std::move(Arg));
371 else
372 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000373
Eric Christopherc0239362014-12-08 18:12:28 +0000374 if (CurTok == ')')
375 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000376
Nick Lewycky109af622009-04-12 20:47:23 +0000377 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000378 return LogError("Expected ')' or ',' in argument list");
Nick Lewycky109af622009-04-12 20:47:23 +0000379 getNextToken();
380 }
381 }
382
383 // Eat the ')'.
384 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000385
Lang Hames09bf4c12015-08-18 18:11:06 +0000386 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000387}
388
Nick Lewycky109af622009-04-12 20:47:23 +0000389/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000390static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000391 getNextToken(); // eat the if.
392
Nick Lewycky109af622009-04-12 20:47:23 +0000393 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000394 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000395 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000396 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000397
Nick Lewycky109af622009-04-12 20:47:23 +0000398 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000399 return LogError("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000400 getNextToken(); // eat the then
401
Lang Hames09bf4c12015-08-18 18:11:06 +0000402 auto Then = ParseExpression();
403 if (!Then)
404 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000405
Nick Lewycky109af622009-04-12 20:47:23 +0000406 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000407 return LogError("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000408
Nick Lewycky109af622009-04-12 20:47:23 +0000409 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000410
Lang Hames09bf4c12015-08-18 18:11:06 +0000411 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000412 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000413 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000414
Lang Hames09bf4c12015-08-18 18:11:06 +0000415 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
416 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000417}
418
419/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000420static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000421 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000422
423 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000424 return LogError("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000425
Nick Lewycky109af622009-04-12 20:47:23 +0000426 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000427 getNextToken(); // eat identifier.
428
Nick Lewycky109af622009-04-12 20:47:23 +0000429 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000430 return LogError("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000431 getNextToken(); // eat '='.
432
Lang Hames09bf4c12015-08-18 18:11:06 +0000433 auto Start = ParseExpression();
434 if (!Start)
435 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000436 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000437 return LogError("expected ',' after for start value");
Nick Lewycky109af622009-04-12 20:47:23 +0000438 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000439
Lang Hames09bf4c12015-08-18 18:11:06 +0000440 auto End = ParseExpression();
441 if (!End)
442 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000443
Nick Lewycky109af622009-04-12 20:47:23 +0000444 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000445 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000446 if (CurTok == ',') {
447 getNextToken();
448 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000449 if (!Step)
450 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000451 }
Eric Christopherc0239362014-12-08 18:12:28 +0000452
Nick Lewycky109af622009-04-12 20:47:23 +0000453 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000454 return LogError("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000455 getNextToken(); // eat 'in'.
456
Lang Hames09bf4c12015-08-18 18:11:06 +0000457 auto Body = ParseExpression();
458 if (!Body)
459 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000460
Lang Hames09bf4c12015-08-18 18:11:06 +0000461 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
462 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000463}
464
Eric Christopherc0239362014-12-08 18:12:28 +0000465/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000466// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000467static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000468 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000469
Lang Hames09bf4c12015-08-18 18:11:06 +0000470 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000471
472 // At least one variable name is required.
473 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000474 return LogError("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000475
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000476 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000477 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000478 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000479
480 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000481 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000482 if (CurTok == '=') {
483 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000484
Nick Lewycky109af622009-04-12 20:47:23 +0000485 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000486 if (!Init)
487 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000488 }
Eric Christopherc0239362014-12-08 18:12:28 +0000489
Lang Hames09bf4c12015-08-18 18:11:06 +0000490 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000491
Nick Lewycky109af622009-04-12 20:47:23 +0000492 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000493 if (CurTok != ',')
494 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000495 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000496
Nick Lewycky109af622009-04-12 20:47:23 +0000497 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000498 return LogError("expected identifier list after var");
Nick Lewycky109af622009-04-12 20:47:23 +0000499 }
Eric Christopherc0239362014-12-08 18:12:28 +0000500
Nick Lewycky109af622009-04-12 20:47:23 +0000501 // At this point, we have to have 'in'.
502 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000503 return LogError("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000504 getNextToken(); // eat 'in'.
505
Lang Hames09bf4c12015-08-18 18:11:06 +0000506 auto Body = ParseExpression();
507 if (!Body)
508 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000509
Lang Hames09bf4c12015-08-18 18:11:06 +0000510 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000511}
512
Nick Lewycky109af622009-04-12 20:47:23 +0000513/// primary
514/// ::= identifierexpr
515/// ::= numberexpr
516/// ::= parenexpr
517/// ::= ifexpr
518/// ::= forexpr
519/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000520static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000521 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000522 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000523 return LogError("unknown token when expecting an expression");
Eric Christopherc0239362014-12-08 18:12:28 +0000524 case tok_identifier:
525 return ParseIdentifierExpr();
526 case tok_number:
527 return ParseNumberExpr();
528 case '(':
529 return ParseParenExpr();
530 case tok_if:
531 return ParseIfExpr();
532 case tok_for:
533 return ParseForExpr();
534 case tok_var:
535 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000536 }
537}
538
539/// unary
540/// ::= primary
541/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000542static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000543 // If the current token is not an operator, it must be a primary expr.
544 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
545 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000546
Nick Lewycky109af622009-04-12 20:47:23 +0000547 // If this is a unary operator, read it.
548 int Opc = CurTok;
549 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000550 if (auto Operand = ParseUnary())
551 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
552 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000553}
554
555/// binoprhs
556/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000557static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
558 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000559 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000560 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000561 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000562
Nick Lewycky109af622009-04-12 20:47:23 +0000563 // If this is a binop that binds at least as tightly as the current binop,
564 // consume it, otherwise we are done.
565 if (TokPrec < ExprPrec)
566 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000567
Nick Lewycky109af622009-04-12 20:47:23 +0000568 // Okay, we know this is a binop.
569 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000570 getNextToken(); // eat binop
571
Nick Lewycky109af622009-04-12 20:47:23 +0000572 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000573 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000574 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000575 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000576
Nick Lewycky109af622009-04-12 20:47:23 +0000577 // If BinOp binds less tightly with RHS than the operator after RHS, let
578 // the pending operator take RHS as its LHS.
579 int NextPrec = GetTokPrecedence();
580 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000581 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
582 if (!RHS)
583 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000584 }
Eric Christopherc0239362014-12-08 18:12:28 +0000585
Nick Lewycky109af622009-04-12 20:47:23 +0000586 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000587 LHS =
588 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000589 }
590}
591
592/// expression
593/// ::= unary binoprhs
594///
Lang Hames09bf4c12015-08-18 18:11:06 +0000595static std::unique_ptr<ExprAST> ParseExpression() {
596 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000597 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000598 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000599
Lang Hames09bf4c12015-08-18 18:11:06 +0000600 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000601}
602
603/// prototype
604/// ::= id '(' id* ')'
605/// ::= binary LETTER number? (id, id)
606/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000607static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000608 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000609
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000610 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000611 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000612
Nick Lewycky109af622009-04-12 20:47:23 +0000613 switch (CurTok) {
614 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000615 return LogErrorP("Expected function name in prototype");
Nick Lewycky109af622009-04-12 20:47:23 +0000616 case tok_identifier:
617 FnName = IdentifierStr;
618 Kind = 0;
619 getNextToken();
620 break;
621 case tok_unary:
622 getNextToken();
623 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000624 return LogErrorP("Expected unary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000625 FnName = "unary";
626 FnName += (char)CurTok;
627 Kind = 1;
628 getNextToken();
629 break;
630 case tok_binary:
631 getNextToken();
632 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000633 return LogErrorP("Expected binary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000634 FnName = "binary";
635 FnName += (char)CurTok;
636 Kind = 2;
637 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000638
Nick Lewycky109af622009-04-12 20:47:23 +0000639 // Read the precedence if present.
640 if (CurTok == tok_number) {
641 if (NumVal < 1 || NumVal > 100)
Lang Hamesf9878c52016-03-25 17:33:32 +0000642 return LogErrorP("Invalid precedecnce: must be 1..100");
Nick Lewycky109af622009-04-12 20:47:23 +0000643 BinaryPrecedence = (unsigned)NumVal;
644 getNextToken();
645 }
646 break;
647 }
Eric Christopherc0239362014-12-08 18:12:28 +0000648
Nick Lewycky109af622009-04-12 20:47:23 +0000649 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000650 return LogErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000651
Nick Lewycky109af622009-04-12 20:47:23 +0000652 std::vector<std::string> ArgNames;
653 while (getNextToken() == tok_identifier)
654 ArgNames.push_back(IdentifierStr);
655 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000656 return LogErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000657
Nick Lewycky109af622009-04-12 20:47:23 +0000658 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000659 getNextToken(); // eat ')'.
660
Nick Lewycky109af622009-04-12 20:47:23 +0000661 // Verify right number of names for operator.
662 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000663 return LogErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000664
Lang Hames09bf4c12015-08-18 18:11:06 +0000665 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
666 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000667}
668
669/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000670static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000671 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000672 auto Proto = ParsePrototype();
673 if (!Proto)
674 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000675
Lang Hames09bf4c12015-08-18 18:11:06 +0000676 if (auto E = ParseExpression())
677 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
678 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000679}
680
681/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000682static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
683 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000684 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000685 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
686 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000687 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000688 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000689 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000690}
691
692/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000693static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000694 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000695 return ParsePrototype();
696}
697
698//===----------------------------------------------------------------------===//
699// Code Generation
700//===----------------------------------------------------------------------===//
701
Mehdi Amini03b42e42016-04-14 21:59:01 +0000702static LLVMContext TheContext;
703static IRBuilder<> Builder(TheContext);
Lang Hames24796802016-05-22 22:48:36 +0000704static std::unique_ptr<Module> TheModule;
Eric Christopherc0239362014-12-08 18:12:28 +0000705static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000706static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
707static std::unique_ptr<KaleidoscopeJIT> TheJIT;
708static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000709
Lang Hamesf9878c52016-03-25 17:33:32 +0000710Value *LogErrorV(const char *Str) {
711 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000712 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000713}
Nick Lewycky109af622009-04-12 20:47:23 +0000714
Lang Hames2d789c32015-08-26 03:07:41 +0000715Function *getFunction(std::string Name) {
716 // First, see if the function has already been added to the current module.
717 if (auto *F = TheModule->getFunction(Name))
718 return F;
719
720 // If not, check whether we can codegen the declaration from some existing
721 // prototype.
722 auto FI = FunctionProtos.find(Name);
723 if (FI != FunctionProtos.end())
724 return FI->second->codegen();
725
726 // If no existing prototype exists, return null.
727 return nullptr;
728}
729
Nick Lewycky109af622009-04-12 20:47:23 +0000730/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
731/// the function. This is used for mutable variables etc.
732static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
733 const std::string &VarName) {
734 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000735 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000736 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Nick Lewycky109af622009-04-12 20:47:23 +0000737}
738
Lang Hames2d789c32015-08-26 03:07:41 +0000739Value *NumberExprAST::codegen() {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000740 return ConstantFP::get(TheContext, APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000741}
742
Lang Hames2d789c32015-08-26 03:07:41 +0000743Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000744 // Look this variable up in the function.
745 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000746 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000747 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000748
749 // Load the value.
750 return Builder.CreateLoad(V, Name.c_str());
751}
752
Lang Hames2d789c32015-08-26 03:07:41 +0000753Value *UnaryExprAST::codegen() {
754 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000755 if (!OperandV)
756 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000757
Lang Hames2d789c32015-08-26 03:07:41 +0000758 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000759 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000760 return LogErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000761
Nick Lewycky109af622009-04-12 20:47:23 +0000762 return Builder.CreateCall(F, OperandV, "unop");
763}
764
Lang Hames2d789c32015-08-26 03:07:41 +0000765Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000766 // Special case '=' because we don't want to emit the LHS as an expression.
767 if (Op == '=') {
768 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000769 // This assume we're building without RTTI because LLVM builds that way by
770 // default. If you build LLVM with RTTI this can be changed to a
771 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000772 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000773 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000774 return LogErrorV("destination of '=' must be a variable");
Nick Lewycky109af622009-04-12 20:47:23 +0000775 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000776 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000777 if (!Val)
778 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000779
780 // Look up the name.
781 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000782 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000783 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000784
785 Builder.CreateStore(Val, Variable);
786 return Val;
787 }
Eric Christopherc0239362014-12-08 18:12:28 +0000788
Lang Hames2d789c32015-08-26 03:07:41 +0000789 Value *L = LHS->codegen();
790 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000791 if (!L || !R)
792 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000793
Nick Lewycky109af622009-04-12 20:47:23 +0000794 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000795 case '+':
796 return Builder.CreateFAdd(L, R, "addtmp");
797 case '-':
798 return Builder.CreateFSub(L, R, "subtmp");
799 case '*':
800 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000801 case '<':
802 L = Builder.CreateFCmpULT(L, R, "cmptmp");
803 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000804 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000805 default:
806 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000807 }
Eric Christopherc0239362014-12-08 18:12:28 +0000808
Nick Lewycky109af622009-04-12 20:47:23 +0000809 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
810 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000811 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000812 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000813
Lang Hames59b0da82015-08-19 18:15:58 +0000814 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000815 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000816}
817
Lang Hames2d789c32015-08-26 03:07:41 +0000818Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000819 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000820 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000821 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +0000822 return LogErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000823
Nick Lewycky109af622009-04-12 20:47:23 +0000824 // If argument mismatch error.
825 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +0000826 return LogErrorV("Incorrect # arguments passed");
Nick Lewycky109af622009-04-12 20:47:23 +0000827
Eric Christopherc0239362014-12-08 18:12:28 +0000828 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000829 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000830 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000831 if (!ArgsV.back())
832 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000833 }
Eric Christopherc0239362014-12-08 18:12:28 +0000834
Francois Pichetc5d10502011-07-15 10:59:52 +0000835 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000836}
837
Lang Hames2d789c32015-08-26 03:07:41 +0000838Value *IfExprAST::codegen() {
839 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000840 if (!CondV)
841 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000842
Nick Lewycky109af622009-04-12 20:47:23 +0000843 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000844 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000845 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000846
Nick Lewycky109af622009-04-12 20:47:23 +0000847 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000848
Nick Lewycky109af622009-04-12 20:47:23 +0000849 // Create blocks for the then and else cases. Insert the 'then' block at the
850 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000851 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
852 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
853 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000854
Nick Lewycky109af622009-04-12 20:47:23 +0000855 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000856
Nick Lewycky109af622009-04-12 20:47:23 +0000857 // Emit then value.
858 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000859
Lang Hames2d789c32015-08-26 03:07:41 +0000860 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000861 if (!ThenV)
862 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000863
Nick Lewycky109af622009-04-12 20:47:23 +0000864 Builder.CreateBr(MergeBB);
865 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
866 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000867
Nick Lewycky109af622009-04-12 20:47:23 +0000868 // Emit else block.
869 TheFunction->getBasicBlockList().push_back(ElseBB);
870 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000871
Lang Hames2d789c32015-08-26 03:07:41 +0000872 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000873 if (!ElseV)
874 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000875
Nick Lewycky109af622009-04-12 20:47:23 +0000876 Builder.CreateBr(MergeBB);
877 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
878 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000879
Nick Lewycky109af622009-04-12 20:47:23 +0000880 // Emit merge block.
881 TheFunction->getBasicBlockList().push_back(MergeBB);
882 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000883 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000884
Nick Lewycky109af622009-04-12 20:47:23 +0000885 PN->addIncoming(ThenV, ThenBB);
886 PN->addIncoming(ElseV, ElseBB);
887 return PN;
888}
889
Lang Hames59b0da82015-08-19 18:15:58 +0000890// Output for-loop as:
891// var = alloca double
892// ...
893// start = startexpr
894// store start -> var
895// goto loop
896// loop:
897// ...
898// bodyexpr
899// ...
900// loopend:
901// step = stepexpr
902// endcond = endexpr
903//
904// curvar = load var
905// nextvar = curvar + step
906// store nextvar -> var
907// br endcond, loop, endloop
908// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000909Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000910 Function *TheFunction = Builder.GetInsertBlock()->getParent();
911
912 // Create an alloca for the variable in the entry block.
913 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000914
Nick Lewycky109af622009-04-12 20:47:23 +0000915 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000916 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000917 if (!StartVal)
918 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000919
Nick Lewycky109af622009-04-12 20:47:23 +0000920 // Store the value into the alloca.
921 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000922
Nick Lewycky109af622009-04-12 20:47:23 +0000923 // Make the new basic block for the loop header, inserting after current
924 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000925 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000926
Nick Lewycky109af622009-04-12 20:47:23 +0000927 // Insert an explicit fall through from the current block to the LoopBB.
928 Builder.CreateBr(LoopBB);
929
930 // Start insertion in LoopBB.
931 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000932
Nick Lewycky109af622009-04-12 20:47:23 +0000933 // Within the loop, the variable is defined equal to the PHI node. If it
934 // shadows an existing variable, we have to restore it, so save it now.
935 AllocaInst *OldVal = NamedValues[VarName];
936 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000937
Nick Lewycky109af622009-04-12 20:47:23 +0000938 // Emit the body of the loop. This, like any other expr, can change the
939 // current BB. Note that we ignore the value computed by the body, but don't
940 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000941 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000942 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000943
Nick Lewycky109af622009-04-12 20:47:23 +0000944 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000945 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000946 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000947 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000948 if (!StepVal)
949 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000950 } else {
951 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000952 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000953 }
Eric Christopherc0239362014-12-08 18:12:28 +0000954
Nick Lewycky109af622009-04-12 20:47:23 +0000955 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000956 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000957 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000958 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000959
Nick Lewycky109af622009-04-12 20:47:23 +0000960 // Reload, increment, and restore the alloca. This handles the case where
961 // the body of the loop mutates the variable.
962 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000963 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000964 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000965
Nick Lewycky109af622009-04-12 20:47:23 +0000966 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000967 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000968 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000969
Nick Lewycky109af622009-04-12 20:47:23 +0000970 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000971 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +0000972 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000973
Nick Lewycky109af622009-04-12 20:47:23 +0000974 // Insert the conditional branch into the end of LoopEndBB.
975 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000976
Nick Lewycky109af622009-04-12 20:47:23 +0000977 // Any new code will be inserted in AfterBB.
978 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000979
Nick Lewycky109af622009-04-12 20:47:23 +0000980 // Restore the unshadowed variable.
981 if (OldVal)
982 NamedValues[VarName] = OldVal;
983 else
984 NamedValues.erase(VarName);
985
Nick Lewycky109af622009-04-12 20:47:23 +0000986 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000987 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Nick Lewycky109af622009-04-12 20:47:23 +0000988}
989
Lang Hames2d789c32015-08-26 03:07:41 +0000990Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000991 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000992
Nick Lewycky109af622009-04-12 20:47:23 +0000993 Function *TheFunction = Builder.GetInsertBlock()->getParent();
994
995 // Register all variables and emit their initializer.
996 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
997 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000998 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000999
Nick Lewycky109af622009-04-12 20:47:23 +00001000 // Emit the initializer before adding the variable to scope, this prevents
1001 // the initializer from referencing the variable itself, and permits stuff
1002 // like this:
1003 // var a = 1 in
1004 // var a = a in ... # refers to outer 'a'.
1005 Value *InitVal;
1006 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +00001007 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001008 if (!InitVal)
1009 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001010 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001011 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +00001012 }
Eric Christopherc0239362014-12-08 18:12:28 +00001013
Nick Lewycky109af622009-04-12 20:47:23 +00001014 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1015 Builder.CreateStore(InitVal, Alloca);
1016
1017 // Remember the old variable binding so that we can restore the binding when
1018 // we unrecurse.
1019 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +00001020
Nick Lewycky109af622009-04-12 20:47:23 +00001021 // Remember this binding.
1022 NamedValues[VarName] = Alloca;
1023 }
Eric Christopherc0239362014-12-08 18:12:28 +00001024
Nick Lewycky109af622009-04-12 20:47:23 +00001025 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001026 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001027 if (!BodyVal)
1028 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001029
Nick Lewycky109af622009-04-12 20:47:23 +00001030 // Pop all our variables from scope.
1031 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1032 NamedValues[VarNames[i].first] = OldBindings[i];
1033
1034 // Return the body computation.
1035 return BodyVal;
1036}
1037
Lang Hames2d789c32015-08-26 03:07:41 +00001038Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001039 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001040 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopherc0239362014-12-08 18:12:28 +00001041 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001042 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopherc0239362014-12-08 18:12:28 +00001043
1044 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001045 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001046
Nick Lewycky109af622009-04-12 20:47:23 +00001047 // Set names for all arguments.
1048 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001049 for (auto &Arg : F->args())
1050 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001051
Nick Lewycky109af622009-04-12 20:47:23 +00001052 return F;
1053}
1054
Lang Hames2d789c32015-08-26 03:07:41 +00001055Function *FunctionAST::codegen() {
1056 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1057 // reference to it for use below.
1058 auto &P = *Proto;
1059 FunctionProtos[Proto->getName()] = std::move(Proto);
1060 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001061 if (!TheFunction)
1062 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001063
Nick Lewycky109af622009-04-12 20:47:23 +00001064 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001065 if (P.isBinaryOp())
1066 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001067
Nick Lewycky109af622009-04-12 20:47:23 +00001068 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001069 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001070 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001071
Lang Hames2d789c32015-08-26 03:07:41 +00001072 // Record the function arguments in the NamedValues map.
1073 NamedValues.clear();
1074 for (auto &Arg : TheFunction->args()) {
1075 // Create an alloca for this variable.
1076 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001077
Lang Hames2d789c32015-08-26 03:07:41 +00001078 // Store the initial value into the alloca.
1079 Builder.CreateStore(&Arg, Alloca);
1080
1081 // Add arguments to variable symbol table.
1082 NamedValues[Arg.getName()] = Alloca;
1083 }
1084
1085 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001086 // Finish off the function.
1087 Builder.CreateRet(RetVal);
1088
1089 // Validate the generated code, checking for consistency.
1090 verifyFunction(*TheFunction);
1091
Lang Hames2d789c32015-08-26 03:07:41 +00001092 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001093 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001094
Nick Lewycky109af622009-04-12 20:47:23 +00001095 return TheFunction;
1096 }
Eric Christopherc0239362014-12-08 18:12:28 +00001097
Nick Lewycky109af622009-04-12 20:47:23 +00001098 // Error reading body, remove function.
1099 TheFunction->eraseFromParent();
1100
Lang Hames2d789c32015-08-26 03:07:41 +00001101 if (P.isBinaryOp())
Nick Lewycky109af622009-04-12 20:47:23 +00001102 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001103 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001104}
1105
1106//===----------------------------------------------------------------------===//
1107// Top-Level parsing and JIT Driver
1108//===----------------------------------------------------------------------===//
1109
Lang Hames2d789c32015-08-26 03:07:41 +00001110static void InitializeModuleAndPassManager() {
1111 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001112 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001113 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1114
1115 // Create a new pass manager attached to it.
1116 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1117
Lang Hames2d789c32015-08-26 03:07:41 +00001118 // Do simple "peephole" optimizations and bit-twiddling optzns.
1119 TheFPM->add(createInstructionCombiningPass());
1120 // Reassociate expressions.
1121 TheFPM->add(createReassociatePass());
1122 // Eliminate Common SubExpressions.
1123 TheFPM->add(createGVNPass());
1124 // Simplify the control flow graph (deleting unreachable blocks, etc).
1125 TheFPM->add(createCFGSimplificationPass());
1126
1127 TheFPM->doInitialization();
1128}
Nick Lewycky109af622009-04-12 20:47:23 +00001129
1130static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001131 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001132 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001133 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001134 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001135 TheJIT->addModule(std::move(TheModule));
1136 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001137 }
1138 } else {
1139 // Skip token for error recovery.
1140 getNextToken();
1141 }
1142}
1143
1144static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001145 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001146 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001147 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001148 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001149 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001150 }
1151 } else {
1152 // Skip token for error recovery.
1153 getNextToken();
1154 }
1155}
1156
1157static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001158 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001159 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001160 if (FnAST->codegen()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001161 // JIT the module containing the anonymous expression, keeping a handle so
1162 // we can free it later.
1163 auto H = TheJIT->addModule(std::move(TheModule));
1164 InitializeModuleAndPassManager();
1165
1166 // Search the JIT for the __anon_expr symbol.
1167 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1168 assert(ExprSymbol && "Function not found");
1169
1170 // Get the symbol's address and cast it to the right type (takes no
1171 // arguments, returns a double) so we can call it as a native function.
1172 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Nick Lewycky109af622009-04-12 20:47:23 +00001173 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001174
1175 // Delete the anonymous expression module from the JIT.
1176 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001177 }
1178 } else {
1179 // Skip token for error recovery.
1180 getNextToken();
1181 }
1182}
1183
1184/// top ::= definition | external | expression | ';'
1185static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001186 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +00001187 fprintf(stderr, "ready> ");
1188 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001189 case tok_eof:
1190 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001191 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001192 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001193 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001194 case tok_def:
1195 HandleDefinition();
1196 break;
1197 case tok_extern:
1198 HandleExtern();
1199 break;
1200 default:
1201 HandleTopLevelExpression();
1202 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001203 }
1204 }
1205}
1206
Nick Lewycky109af622009-04-12 20:47:23 +00001207//===----------------------------------------------------------------------===//
1208// "Library" functions that can be "extern'd" from user code.
1209//===----------------------------------------------------------------------===//
1210
1211/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001212extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001213 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001214 return 0;
1215}
1216
1217/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001218extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001219 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001220 return 0;
1221}
1222
1223//===----------------------------------------------------------------------===//
1224// Main driver code.
1225//===----------------------------------------------------------------------===//
1226
1227int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001228 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001229 InitializeNativeTargetAsmPrinter();
1230 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001231
Nick Lewycky109af622009-04-12 20:47:23 +00001232 // Install standard binary operators.
1233 // 1 is lowest precedence.
1234 BinopPrecedence['='] = 2;
1235 BinopPrecedence['<'] = 10;
1236 BinopPrecedence['+'] = 20;
1237 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001238 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001239
1240 // Prime the first token.
1241 fprintf(stderr, "ready> ");
1242 getNextToken();
1243
Lang Hames2d789c32015-08-26 03:07:41 +00001244 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001245
Lang Hames2d789c32015-08-26 03:07:41 +00001246 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001247
1248 // Run the main "interpreter loop" now.
1249 MainLoop();
1250
Nick Lewycky109af622009-04-12 20:47:23 +00001251 return 0;
1252}