blob: fffbfba286c203cc30ff0311ddbd9cc7e8b26fad [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 Zelenkof981ec42016-05-19 01:08:04 +000019#include <cassert>
20#include <cctype>
21#include <cstdint>
22#include <cstdio>
23#include <cstdlib>
24#include <map>
25#include <memory>
26#include <string>
27#include <utility>
28#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000029
Nick Lewycky109af622009-04-12 20:47:23 +000030using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000031using namespace llvm::orc;
Nick Lewycky109af622009-04-12 20:47:23 +000032
33//===----------------------------------------------------------------------===//
34// Lexer
35//===----------------------------------------------------------------------===//
36
37// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
38// of these for known things.
39enum Token {
40 tok_eof = -1,
41
42 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000043 tok_def = -2,
44 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000045
46 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000047 tok_identifier = -4,
48 tok_number = -5,
49
Nick Lewycky109af622009-04-12 20:47:23 +000050 // control
Eric Christopherc0239362014-12-08 18:12:28 +000051 tok_if = -6,
52 tok_then = -7,
53 tok_else = -8,
54 tok_for = -9,
55 tok_in = -10,
56
Nick Lewycky109af622009-04-12 20:47:23 +000057 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000058 tok_binary = -11,
59 tok_unary = -12,
60
Nick Lewycky109af622009-04-12 20:47:23 +000061 // var definition
62 tok_var = -13
63};
64
Eric Christopherc0239362014-12-08 18:12:28 +000065static std::string IdentifierStr; // Filled in if tok_identifier
66static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000067
68/// gettok - Return the next token from standard input.
69static int gettok() {
70 static int LastChar = ' ';
71
72 // Skip any whitespace.
73 while (isspace(LastChar))
74 LastChar = getchar();
75
76 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
77 IdentifierStr = LastChar;
78 while (isalnum((LastChar = getchar())))
79 IdentifierStr += LastChar;
80
Eric Christopherc0239362014-12-08 18:12:28 +000081 if (IdentifierStr == "def")
82 return tok_def;
83 if (IdentifierStr == "extern")
84 return tok_extern;
85 if (IdentifierStr == "if")
86 return tok_if;
87 if (IdentifierStr == "then")
88 return tok_then;
89 if (IdentifierStr == "else")
90 return tok_else;
91 if (IdentifierStr == "for")
92 return tok_for;
93 if (IdentifierStr == "in")
94 return tok_in;
95 if (IdentifierStr == "binary")
96 return tok_binary;
97 if (IdentifierStr == "unary")
98 return tok_unary;
99 if (IdentifierStr == "var")
100 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +0000101 return tok_identifier;
102 }
103
Eric Christopherc0239362014-12-08 18:12:28 +0000104 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +0000105 std::string NumStr;
106 do {
107 NumStr += LastChar;
108 LastChar = getchar();
109 } while (isdigit(LastChar) || LastChar == '.');
110
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000111 NumVal = strtod(NumStr.c_str(), nullptr);
Nick Lewycky109af622009-04-12 20:47:23 +0000112 return tok_number;
113 }
114
115 if (LastChar == '#') {
116 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000117 do
118 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000119 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000120
Nick Lewycky109af622009-04-12 20:47:23 +0000121 if (LastChar != EOF)
122 return gettok();
123 }
Eric Christopherc0239362014-12-08 18:12:28 +0000124
Nick Lewycky109af622009-04-12 20:47:23 +0000125 // Check for end of file. Don't eat the EOF.
126 if (LastChar == EOF)
127 return tok_eof;
128
129 // Otherwise, just return the character as its ascii value.
130 int ThisChar = LastChar;
131 LastChar = getchar();
132 return ThisChar;
133}
134
135//===----------------------------------------------------------------------===//
136// Abstract Syntax Tree (aka Parse Tree)
137//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000138namespace {
Nick Lewycky109af622009-04-12 20:47:23 +0000139/// ExprAST - Base class for all expression nodes.
140class ExprAST {
141public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000142 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000143 virtual Value *codegen() = 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000144};
145
146/// NumberExprAST - Expression class for numeric literals like "1.0".
147class NumberExprAST : public ExprAST {
148 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000149
Nick Lewycky109af622009-04-12 20:47:23 +0000150public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000151 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000152 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000153};
154
155/// VariableExprAST - Expression class for referencing a variable, like "a".
156class VariableExprAST : public ExprAST {
157 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000158
Nick Lewycky109af622009-04-12 20:47:23 +0000159public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000160 VariableExprAST(const std::string &Name) : Name(Name) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000161 const std::string &getName() const { return Name; }
Lang Hames2d789c32015-08-26 03:07:41 +0000162 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000163};
164
165/// UnaryExprAST - Expression class for a unary operator.
166class UnaryExprAST : public ExprAST {
167 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000168 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000169
Nick Lewycky109af622009-04-12 20:47:23 +0000170public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000171 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
172 : Opcode(Opcode), Operand(std::move(Operand)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000173 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000174};
175
176/// BinaryExprAST - Expression class for a binary operator.
177class BinaryExprAST : public ExprAST {
178 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000179 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000180
Nick Lewycky109af622009-04-12 20:47:23 +0000181public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000182 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
183 std::unique_ptr<ExprAST> RHS)
184 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000185 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000186};
187
188/// CallExprAST - Expression class for function calls.
189class CallExprAST : public ExprAST {
190 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000191 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000192
Nick Lewycky109af622009-04-12 20:47:23 +0000193public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000194 CallExprAST(const std::string &Callee,
195 std::vector<std::unique_ptr<ExprAST>> Args)
196 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000197 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000198};
199
200/// IfExprAST - Expression class for if/then/else.
201class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000202 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000203
Nick Lewycky109af622009-04-12 20:47:23 +0000204public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000205 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
206 std::unique_ptr<ExprAST> Else)
207 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000208 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000209};
210
211/// ForExprAST - Expression class for for/in.
212class ForExprAST : public ExprAST {
213 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000214 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000215
Nick Lewycky109af622009-04-12 20:47:23 +0000216public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000217 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
218 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
219 std::unique_ptr<ExprAST> Body)
220 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
221 Step(std::move(Step)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000222 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000223};
224
225/// VarExprAST - Expression class for var/in
226class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000227 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
228 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000229
Nick Lewycky109af622009-04-12 20:47:23 +0000230public:
Lang Hames59b0da82015-08-19 18:15:58 +0000231 VarExprAST(
232 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
233 std::unique_ptr<ExprAST> Body)
234 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000235 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000236};
237
238/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000239/// which captures its name, and its argument names (thus implicitly the number
240/// of arguments the function takes), as well as if it is an operator.
Nick Lewycky109af622009-04-12 20:47:23 +0000241class PrototypeAST {
242 std::string Name;
243 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000244 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000245 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000246
Nick Lewycky109af622009-04-12 20:47:23 +0000247public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000248 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
249 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000250 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
251 Precedence(Prec) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000252 Function *codegen();
253 const std::string &getName() const { return Name; }
Eric Christopherc0239362014-12-08 18:12:28 +0000254
Lang Hames09bf4c12015-08-18 18:11:06 +0000255 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
256 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000257
Nick Lewycky109af622009-04-12 20:47:23 +0000258 char getOperatorName() const {
259 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000260 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000261 }
Eric Christopherc0239362014-12-08 18:12:28 +0000262
Nick Lewycky109af622009-04-12 20:47:23 +0000263 unsigned getBinaryPrecedence() const { return Precedence; }
Nick Lewycky109af622009-04-12 20:47:23 +0000264};
265
266/// FunctionAST - This class represents a function definition itself.
267class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000268 std::unique_ptr<PrototypeAST> Proto;
269 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000270
Nick Lewycky109af622009-04-12 20:47:23 +0000271public:
Lang Hames59b0da82015-08-19 18:15:58 +0000272 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
273 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000274 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000275 Function *codegen();
Nick Lewycky109af622009-04-12 20:47:23 +0000276};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000277} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000278
279//===----------------------------------------------------------------------===//
280// Parser
281//===----------------------------------------------------------------------===//
282
283/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000284/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000285/// lexer and updates CurTok with its results.
286static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000287static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000288
289/// BinopPrecedence - This holds the precedence for each binary operator that is
290/// defined.
291static std::map<char, int> BinopPrecedence;
292
293/// GetTokPrecedence - Get the precedence of the pending binary operator token.
294static int GetTokPrecedence() {
295 if (!isascii(CurTok))
296 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000297
Nick Lewycky109af622009-04-12 20:47:23 +0000298 // Make sure it's a declared binop.
299 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000300 if (TokPrec <= 0)
301 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000302 return TokPrec;
303}
304
Lang Hamesf9878c52016-03-25 17:33:32 +0000305/// LogError* - These are little helper functions for error handling.
306std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000307 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000308 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000309}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000310
Lang Hamesf9878c52016-03-25 17:33:32 +0000311std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
312 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000313 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000314}
Nick Lewycky109af622009-04-12 20:47:23 +0000315
Lang Hames09bf4c12015-08-18 18:11:06 +0000316static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000317
Lang Hames59b0da82015-08-19 18:15:58 +0000318/// numberexpr ::= number
319static std::unique_ptr<ExprAST> ParseNumberExpr() {
320 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
321 getNextToken(); // consume the number
322 return std::move(Result);
323}
324
325/// parenexpr ::= '(' expression ')'
326static std::unique_ptr<ExprAST> ParseParenExpr() {
327 getNextToken(); // eat (.
328 auto V = ParseExpression();
329 if (!V)
330 return nullptr;
331
332 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000333 return LogError("expected ')'");
Lang Hames59b0da82015-08-19 18:15:58 +0000334 getNextToken(); // eat ).
335 return V;
336}
337
Nick Lewycky109af622009-04-12 20:47:23 +0000338/// identifierexpr
339/// ::= identifier
340/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000341static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000342 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000343
344 getNextToken(); // eat identifier.
345
Nick Lewycky109af622009-04-12 20:47:23 +0000346 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000347 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000348
Nick Lewycky109af622009-04-12 20:47:23 +0000349 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000350 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000351 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000352 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000353 while (true) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000354 if (auto Arg = ParseExpression())
355 Args.push_back(std::move(Arg));
356 else
357 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000358
Eric Christopherc0239362014-12-08 18:12:28 +0000359 if (CurTok == ')')
360 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000361
Nick Lewycky109af622009-04-12 20:47:23 +0000362 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000363 return LogError("Expected ')' or ',' in argument list");
Nick Lewycky109af622009-04-12 20:47:23 +0000364 getNextToken();
365 }
366 }
367
368 // Eat the ')'.
369 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000370
Lang Hames09bf4c12015-08-18 18:11:06 +0000371 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000372}
373
Nick Lewycky109af622009-04-12 20:47:23 +0000374/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000375static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000376 getNextToken(); // eat the if.
377
Nick Lewycky109af622009-04-12 20:47:23 +0000378 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000379 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000380 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000381 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000382
Nick Lewycky109af622009-04-12 20:47:23 +0000383 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000384 return LogError("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000385 getNextToken(); // eat the then
386
Lang Hames09bf4c12015-08-18 18:11:06 +0000387 auto Then = ParseExpression();
388 if (!Then)
389 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000390
Nick Lewycky109af622009-04-12 20:47:23 +0000391 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000392 return LogError("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000393
Nick Lewycky109af622009-04-12 20:47:23 +0000394 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000395
Lang Hames09bf4c12015-08-18 18:11:06 +0000396 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000397 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000398 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000399
Lang Hames09bf4c12015-08-18 18:11:06 +0000400 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
401 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000402}
403
404/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000405static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000406 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000407
408 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000409 return LogError("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000410
Nick Lewycky109af622009-04-12 20:47:23 +0000411 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000412 getNextToken(); // eat identifier.
413
Nick Lewycky109af622009-04-12 20:47:23 +0000414 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000415 return LogError("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000416 getNextToken(); // eat '='.
417
Lang Hames09bf4c12015-08-18 18:11:06 +0000418 auto Start = ParseExpression();
419 if (!Start)
420 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000421 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000422 return LogError("expected ',' after for start value");
Nick Lewycky109af622009-04-12 20:47:23 +0000423 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000424
Lang Hames09bf4c12015-08-18 18:11:06 +0000425 auto End = ParseExpression();
426 if (!End)
427 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000428
Nick Lewycky109af622009-04-12 20:47:23 +0000429 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000430 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000431 if (CurTok == ',') {
432 getNextToken();
433 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000434 if (!Step)
435 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000436 }
Eric Christopherc0239362014-12-08 18:12:28 +0000437
Nick Lewycky109af622009-04-12 20:47:23 +0000438 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000439 return LogError("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000440 getNextToken(); // eat 'in'.
441
Lang Hames09bf4c12015-08-18 18:11:06 +0000442 auto Body = ParseExpression();
443 if (!Body)
444 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000445
Lang Hames09bf4c12015-08-18 18:11:06 +0000446 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
447 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000448}
449
Eric Christopherc0239362014-12-08 18:12:28 +0000450/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000451// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000452static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000453 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000454
Lang Hames09bf4c12015-08-18 18:11:06 +0000455 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000456
457 // At least one variable name is required.
458 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000459 return LogError("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000460
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000461 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000462 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000463 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000464
465 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000466 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000467 if (CurTok == '=') {
468 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000469
Nick Lewycky109af622009-04-12 20:47:23 +0000470 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000471 if (!Init)
472 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000473 }
Eric Christopherc0239362014-12-08 18:12:28 +0000474
Lang Hames09bf4c12015-08-18 18:11:06 +0000475 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000476
Nick Lewycky109af622009-04-12 20:47:23 +0000477 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000478 if (CurTok != ',')
479 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000480 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000481
Nick Lewycky109af622009-04-12 20:47:23 +0000482 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000483 return LogError("expected identifier list after var");
Nick Lewycky109af622009-04-12 20:47:23 +0000484 }
Eric Christopherc0239362014-12-08 18:12:28 +0000485
Nick Lewycky109af622009-04-12 20:47:23 +0000486 // At this point, we have to have 'in'.
487 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000488 return LogError("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000489 getNextToken(); // eat 'in'.
490
Lang Hames09bf4c12015-08-18 18:11:06 +0000491 auto Body = ParseExpression();
492 if (!Body)
493 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000494
Lang Hames09bf4c12015-08-18 18:11:06 +0000495 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000496}
497
Nick Lewycky109af622009-04-12 20:47:23 +0000498/// primary
499/// ::= identifierexpr
500/// ::= numberexpr
501/// ::= parenexpr
502/// ::= ifexpr
503/// ::= forexpr
504/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000505static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000506 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000507 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000508 return LogError("unknown token when expecting an expression");
Eric Christopherc0239362014-12-08 18:12:28 +0000509 case tok_identifier:
510 return ParseIdentifierExpr();
511 case tok_number:
512 return ParseNumberExpr();
513 case '(':
514 return ParseParenExpr();
515 case tok_if:
516 return ParseIfExpr();
517 case tok_for:
518 return ParseForExpr();
519 case tok_var:
520 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000521 }
522}
523
524/// unary
525/// ::= primary
526/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000527static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000528 // If the current token is not an operator, it must be a primary expr.
529 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
530 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000531
Nick Lewycky109af622009-04-12 20:47:23 +0000532 // If this is a unary operator, read it.
533 int Opc = CurTok;
534 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000535 if (auto Operand = ParseUnary())
536 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
537 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000538}
539
540/// binoprhs
541/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000542static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
543 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000544 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000545 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000546 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000547
Nick Lewycky109af622009-04-12 20:47:23 +0000548 // If this is a binop that binds at least as tightly as the current binop,
549 // consume it, otherwise we are done.
550 if (TokPrec < ExprPrec)
551 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000552
Nick Lewycky109af622009-04-12 20:47:23 +0000553 // Okay, we know this is a binop.
554 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000555 getNextToken(); // eat binop
556
Nick Lewycky109af622009-04-12 20:47:23 +0000557 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000558 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000559 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000560 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000561
Nick Lewycky109af622009-04-12 20:47:23 +0000562 // If BinOp binds less tightly with RHS than the operator after RHS, let
563 // the pending operator take RHS as its LHS.
564 int NextPrec = GetTokPrecedence();
565 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000566 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
567 if (!RHS)
568 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000569 }
Eric Christopherc0239362014-12-08 18:12:28 +0000570
Nick Lewycky109af622009-04-12 20:47:23 +0000571 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000572 LHS =
573 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000574 }
575}
576
577/// expression
578/// ::= unary binoprhs
579///
Lang Hames09bf4c12015-08-18 18:11:06 +0000580static std::unique_ptr<ExprAST> ParseExpression() {
581 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000582 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000583 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000584
Lang Hames09bf4c12015-08-18 18:11:06 +0000585 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000586}
587
588/// prototype
589/// ::= id '(' id* ')'
590/// ::= binary LETTER number? (id, id)
591/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000592static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000593 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000594
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000595 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000596 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000597
Nick Lewycky109af622009-04-12 20:47:23 +0000598 switch (CurTok) {
599 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000600 return LogErrorP("Expected function name in prototype");
Nick Lewycky109af622009-04-12 20:47:23 +0000601 case tok_identifier:
602 FnName = IdentifierStr;
603 Kind = 0;
604 getNextToken();
605 break;
606 case tok_unary:
607 getNextToken();
608 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000609 return LogErrorP("Expected unary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000610 FnName = "unary";
611 FnName += (char)CurTok;
612 Kind = 1;
613 getNextToken();
614 break;
615 case tok_binary:
616 getNextToken();
617 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000618 return LogErrorP("Expected binary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000619 FnName = "binary";
620 FnName += (char)CurTok;
621 Kind = 2;
622 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000623
Nick Lewycky109af622009-04-12 20:47:23 +0000624 // Read the precedence if present.
625 if (CurTok == tok_number) {
626 if (NumVal < 1 || NumVal > 100)
Lang Hamesf9878c52016-03-25 17:33:32 +0000627 return LogErrorP("Invalid precedecnce: must be 1..100");
Nick Lewycky109af622009-04-12 20:47:23 +0000628 BinaryPrecedence = (unsigned)NumVal;
629 getNextToken();
630 }
631 break;
632 }
Eric Christopherc0239362014-12-08 18:12:28 +0000633
Nick Lewycky109af622009-04-12 20:47:23 +0000634 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000635 return LogErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000636
Nick Lewycky109af622009-04-12 20:47:23 +0000637 std::vector<std::string> ArgNames;
638 while (getNextToken() == tok_identifier)
639 ArgNames.push_back(IdentifierStr);
640 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000641 return LogErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000642
Nick Lewycky109af622009-04-12 20:47:23 +0000643 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000644 getNextToken(); // eat ')'.
645
Nick Lewycky109af622009-04-12 20:47:23 +0000646 // Verify right number of names for operator.
647 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000648 return LogErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000649
Lang Hames09bf4c12015-08-18 18:11:06 +0000650 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
651 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000652}
653
654/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000655static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000656 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000657 auto Proto = ParsePrototype();
658 if (!Proto)
659 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000660
Lang Hames09bf4c12015-08-18 18:11:06 +0000661 if (auto E = ParseExpression())
662 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
663 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000664}
665
666/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000667static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
668 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000669 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000670 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
671 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000672 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000673 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000674 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000675}
676
677/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000678static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000679 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000680 return ParsePrototype();
681}
682
683//===----------------------------------------------------------------------===//
684// Code Generation
685//===----------------------------------------------------------------------===//
686
Lang Hames2d789c32015-08-26 03:07:41 +0000687static std::unique_ptr<Module> TheModule;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000688static LLVMContext TheContext;
689static IRBuilder<> Builder(TheContext);
Eric Christopherc0239362014-12-08 18:12:28 +0000690static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000691static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
692static std::unique_ptr<KaleidoscopeJIT> TheJIT;
693static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000694
Lang Hamesf9878c52016-03-25 17:33:32 +0000695Value *LogErrorV(const char *Str) {
696 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000697 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000698}
Nick Lewycky109af622009-04-12 20:47:23 +0000699
Lang Hames2d789c32015-08-26 03:07:41 +0000700Function *getFunction(std::string Name) {
701 // First, see if the function has already been added to the current module.
702 if (auto *F = TheModule->getFunction(Name))
703 return F;
704
705 // If not, check whether we can codegen the declaration from some existing
706 // prototype.
707 auto FI = FunctionProtos.find(Name);
708 if (FI != FunctionProtos.end())
709 return FI->second->codegen();
710
711 // If no existing prototype exists, return null.
712 return nullptr;
713}
714
Nick Lewycky109af622009-04-12 20:47:23 +0000715/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
716/// the function. This is used for mutable variables etc.
717static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
718 const std::string &VarName) {
719 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000720 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000721 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Nick Lewycky109af622009-04-12 20:47:23 +0000722}
723
Lang Hames2d789c32015-08-26 03:07:41 +0000724Value *NumberExprAST::codegen() {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000725 return ConstantFP::get(TheContext, APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000726}
727
Lang Hames2d789c32015-08-26 03:07:41 +0000728Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000729 // Look this variable up in the function.
730 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000731 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000732 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000733
734 // Load the value.
735 return Builder.CreateLoad(V, Name.c_str());
736}
737
Lang Hames2d789c32015-08-26 03:07:41 +0000738Value *UnaryExprAST::codegen() {
739 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000740 if (!OperandV)
741 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000742
Lang Hames2d789c32015-08-26 03:07:41 +0000743 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000744 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000745 return LogErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000746
Nick Lewycky109af622009-04-12 20:47:23 +0000747 return Builder.CreateCall(F, OperandV, "unop");
748}
749
Lang Hames2d789c32015-08-26 03:07:41 +0000750Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000751 // Special case '=' because we don't want to emit the LHS as an expression.
752 if (Op == '=') {
753 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000754 // This assume we're building without RTTI because LLVM builds that way by
755 // default. If you build LLVM with RTTI this can be changed to a
756 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000757 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000758 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000759 return LogErrorV("destination of '=' must be a variable");
Nick Lewycky109af622009-04-12 20:47:23 +0000760 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000761 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000762 if (!Val)
763 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000764
765 // Look up the name.
766 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000767 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000768 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000769
770 Builder.CreateStore(Val, Variable);
771 return Val;
772 }
Eric Christopherc0239362014-12-08 18:12:28 +0000773
Lang Hames2d789c32015-08-26 03:07:41 +0000774 Value *L = LHS->codegen();
775 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000776 if (!L || !R)
777 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000778
Nick Lewycky109af622009-04-12 20:47:23 +0000779 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000780 case '+':
781 return Builder.CreateFAdd(L, R, "addtmp");
782 case '-':
783 return Builder.CreateFSub(L, R, "subtmp");
784 case '*':
785 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000786 case '<':
787 L = Builder.CreateFCmpULT(L, R, "cmptmp");
788 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000789 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000790 default:
791 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000792 }
Eric Christopherc0239362014-12-08 18:12:28 +0000793
Nick Lewycky109af622009-04-12 20:47:23 +0000794 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
795 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000796 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000797 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000798
Lang Hames59b0da82015-08-19 18:15:58 +0000799 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000800 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000801}
802
Lang Hames2d789c32015-08-26 03:07:41 +0000803Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000804 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000805 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000806 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +0000807 return LogErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000808
Nick Lewycky109af622009-04-12 20:47:23 +0000809 // If argument mismatch error.
810 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +0000811 return LogErrorV("Incorrect # arguments passed");
Nick Lewycky109af622009-04-12 20:47:23 +0000812
Eric Christopherc0239362014-12-08 18:12:28 +0000813 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000814 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000815 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000816 if (!ArgsV.back())
817 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000818 }
Eric Christopherc0239362014-12-08 18:12:28 +0000819
Francois Pichetc5d10502011-07-15 10:59:52 +0000820 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000821}
822
Lang Hames2d789c32015-08-26 03:07:41 +0000823Value *IfExprAST::codegen() {
824 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000825 if (!CondV)
826 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000827
Nick Lewycky109af622009-04-12 20:47:23 +0000828 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000829 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000830 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000831
Nick Lewycky109af622009-04-12 20:47:23 +0000832 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000833
Nick Lewycky109af622009-04-12 20:47:23 +0000834 // Create blocks for the then and else cases. Insert the 'then' block at the
835 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000836 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
837 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
838 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000839
Nick Lewycky109af622009-04-12 20:47:23 +0000840 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000841
Nick Lewycky109af622009-04-12 20:47:23 +0000842 // Emit then value.
843 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000844
Lang Hames2d789c32015-08-26 03:07:41 +0000845 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000846 if (!ThenV)
847 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000848
Nick Lewycky109af622009-04-12 20:47:23 +0000849 Builder.CreateBr(MergeBB);
850 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
851 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000852
Nick Lewycky109af622009-04-12 20:47:23 +0000853 // Emit else block.
854 TheFunction->getBasicBlockList().push_back(ElseBB);
855 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000856
Lang Hames2d789c32015-08-26 03:07:41 +0000857 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000858 if (!ElseV)
859 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000860
Nick Lewycky109af622009-04-12 20:47:23 +0000861 Builder.CreateBr(MergeBB);
862 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
863 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000864
Nick Lewycky109af622009-04-12 20:47:23 +0000865 // Emit merge block.
866 TheFunction->getBasicBlockList().push_back(MergeBB);
867 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000868 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000869
Nick Lewycky109af622009-04-12 20:47:23 +0000870 PN->addIncoming(ThenV, ThenBB);
871 PN->addIncoming(ElseV, ElseBB);
872 return PN;
873}
874
Lang Hames59b0da82015-08-19 18:15:58 +0000875// Output for-loop as:
876// var = alloca double
877// ...
878// start = startexpr
879// store start -> var
880// goto loop
881// loop:
882// ...
883// bodyexpr
884// ...
885// loopend:
886// step = stepexpr
887// endcond = endexpr
888//
889// curvar = load var
890// nextvar = curvar + step
891// store nextvar -> var
892// br endcond, loop, endloop
893// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000894Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000895 Function *TheFunction = Builder.GetInsertBlock()->getParent();
896
897 // Create an alloca for the variable in the entry block.
898 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000899
Nick Lewycky109af622009-04-12 20:47:23 +0000900 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000901 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000902 if (!StartVal)
903 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000904
Nick Lewycky109af622009-04-12 20:47:23 +0000905 // Store the value into the alloca.
906 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000907
Nick Lewycky109af622009-04-12 20:47:23 +0000908 // Make the new basic block for the loop header, inserting after current
909 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000910 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000911
Nick Lewycky109af622009-04-12 20:47:23 +0000912 // Insert an explicit fall through from the current block to the LoopBB.
913 Builder.CreateBr(LoopBB);
914
915 // Start insertion in LoopBB.
916 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000917
Nick Lewycky109af622009-04-12 20:47:23 +0000918 // Within the loop, the variable is defined equal to the PHI node. If it
919 // shadows an existing variable, we have to restore it, so save it now.
920 AllocaInst *OldVal = NamedValues[VarName];
921 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000922
Nick Lewycky109af622009-04-12 20:47:23 +0000923 // Emit the body of the loop. This, like any other expr, can change the
924 // current BB. Note that we ignore the value computed by the body, but don't
925 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000926 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000927 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000928
Nick Lewycky109af622009-04-12 20:47:23 +0000929 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000930 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000931 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000932 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000933 if (!StepVal)
934 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000935 } else {
936 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000937 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000938 }
Eric Christopherc0239362014-12-08 18:12:28 +0000939
Nick Lewycky109af622009-04-12 20:47:23 +0000940 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000941 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000942 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000943 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000944
Nick Lewycky109af622009-04-12 20:47:23 +0000945 // Reload, increment, and restore the alloca. This handles the case where
946 // the body of the loop mutates the variable.
947 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000948 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000949 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000950
Nick Lewycky109af622009-04-12 20:47:23 +0000951 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000952 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000953 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000954
Nick Lewycky109af622009-04-12 20:47:23 +0000955 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000956 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +0000957 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000958
Nick Lewycky109af622009-04-12 20:47:23 +0000959 // Insert the conditional branch into the end of LoopEndBB.
960 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000961
Nick Lewycky109af622009-04-12 20:47:23 +0000962 // Any new code will be inserted in AfterBB.
963 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000964
Nick Lewycky109af622009-04-12 20:47:23 +0000965 // Restore the unshadowed variable.
966 if (OldVal)
967 NamedValues[VarName] = OldVal;
968 else
969 NamedValues.erase(VarName);
970
Nick Lewycky109af622009-04-12 20:47:23 +0000971 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000972 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Nick Lewycky109af622009-04-12 20:47:23 +0000973}
974
Lang Hames2d789c32015-08-26 03:07:41 +0000975Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000976 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000977
Nick Lewycky109af622009-04-12 20:47:23 +0000978 Function *TheFunction = Builder.GetInsertBlock()->getParent();
979
980 // Register all variables and emit their initializer.
981 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
982 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000983 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000984
Nick Lewycky109af622009-04-12 20:47:23 +0000985 // Emit the initializer before adding the variable to scope, this prevents
986 // the initializer from referencing the variable itself, and permits stuff
987 // like this:
988 // var a = 1 in
989 // var a = a in ... # refers to outer 'a'.
990 Value *InitVal;
991 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +0000992 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000993 if (!InitVal)
994 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000995 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000996 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000997 }
Eric Christopherc0239362014-12-08 18:12:28 +0000998
Nick Lewycky109af622009-04-12 20:47:23 +0000999 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1000 Builder.CreateStore(InitVal, Alloca);
1001
1002 // Remember the old variable binding so that we can restore the binding when
1003 // we unrecurse.
1004 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +00001005
Nick Lewycky109af622009-04-12 20:47:23 +00001006 // Remember this binding.
1007 NamedValues[VarName] = Alloca;
1008 }
Eric Christopherc0239362014-12-08 18:12:28 +00001009
Nick Lewycky109af622009-04-12 20:47:23 +00001010 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001011 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001012 if (!BodyVal)
1013 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001014
Nick Lewycky109af622009-04-12 20:47:23 +00001015 // Pop all our variables from scope.
1016 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1017 NamedValues[VarNames[i].first] = OldBindings[i];
1018
1019 // Return the body computation.
1020 return BodyVal;
1021}
1022
Lang Hames2d789c32015-08-26 03:07:41 +00001023Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001024 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001025 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopherc0239362014-12-08 18:12:28 +00001026 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001027 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopherc0239362014-12-08 18:12:28 +00001028
1029 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001030 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001031
Nick Lewycky109af622009-04-12 20:47:23 +00001032 // Set names for all arguments.
1033 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001034 for (auto &Arg : F->args())
1035 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001036
Nick Lewycky109af622009-04-12 20:47:23 +00001037 return F;
1038}
1039
Lang Hames2d789c32015-08-26 03:07:41 +00001040Function *FunctionAST::codegen() {
1041 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1042 // reference to it for use below.
1043 auto &P = *Proto;
1044 FunctionProtos[Proto->getName()] = std::move(Proto);
1045 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001046 if (!TheFunction)
1047 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001048
Nick Lewycky109af622009-04-12 20:47:23 +00001049 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001050 if (P.isBinaryOp())
1051 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001052
Nick Lewycky109af622009-04-12 20:47:23 +00001053 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001054 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001055 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001056
Lang Hames2d789c32015-08-26 03:07:41 +00001057 // Record the function arguments in the NamedValues map.
1058 NamedValues.clear();
1059 for (auto &Arg : TheFunction->args()) {
1060 // Create an alloca for this variable.
1061 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001062
Lang Hames2d789c32015-08-26 03:07:41 +00001063 // Store the initial value into the alloca.
1064 Builder.CreateStore(&Arg, Alloca);
1065
1066 // Add arguments to variable symbol table.
1067 NamedValues[Arg.getName()] = Alloca;
1068 }
1069
1070 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001071 // Finish off the function.
1072 Builder.CreateRet(RetVal);
1073
1074 // Validate the generated code, checking for consistency.
1075 verifyFunction(*TheFunction);
1076
Lang Hames2d789c32015-08-26 03:07:41 +00001077 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001078 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001079
Nick Lewycky109af622009-04-12 20:47:23 +00001080 return TheFunction;
1081 }
Eric Christopherc0239362014-12-08 18:12:28 +00001082
Nick Lewycky109af622009-04-12 20:47:23 +00001083 // Error reading body, remove function.
1084 TheFunction->eraseFromParent();
1085
Lang Hames2d789c32015-08-26 03:07:41 +00001086 if (P.isBinaryOp())
Nick Lewycky109af622009-04-12 20:47:23 +00001087 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001088 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001089}
1090
1091//===----------------------------------------------------------------------===//
1092// Top-Level parsing and JIT Driver
1093//===----------------------------------------------------------------------===//
1094
Lang Hames2d789c32015-08-26 03:07:41 +00001095static void InitializeModuleAndPassManager() {
1096 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001097 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001098 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1099
1100 // Create a new pass manager attached to it.
1101 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1102
Lang Hames2d789c32015-08-26 03:07:41 +00001103 // Do simple "peephole" optimizations and bit-twiddling optzns.
1104 TheFPM->add(createInstructionCombiningPass());
1105 // Reassociate expressions.
1106 TheFPM->add(createReassociatePass());
1107 // Eliminate Common SubExpressions.
1108 TheFPM->add(createGVNPass());
1109 // Simplify the control flow graph (deleting unreachable blocks, etc).
1110 TheFPM->add(createCFGSimplificationPass());
1111
1112 TheFPM->doInitialization();
1113}
Nick Lewycky109af622009-04-12 20:47:23 +00001114
1115static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001116 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001117 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001118 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001119 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001120 TheJIT->addModule(std::move(TheModule));
1121 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001122 }
1123 } else {
1124 // Skip token for error recovery.
1125 getNextToken();
1126 }
1127}
1128
1129static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001130 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001131 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001132 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001133 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +00001134 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001135 }
1136 } else {
1137 // Skip token for error recovery.
1138 getNextToken();
1139 }
1140}
1141
1142static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001143 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001144 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001145 if (FnAST->codegen()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001146 // JIT the module containing the anonymous expression, keeping a handle so
1147 // we can free it later.
1148 auto H = TheJIT->addModule(std::move(TheModule));
1149 InitializeModuleAndPassManager();
1150
1151 // Search the JIT for the __anon_expr symbol.
1152 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1153 assert(ExprSymbol && "Function not found");
1154
1155 // Get the symbol's address and cast it to the right type (takes no
1156 // arguments, returns a double) so we can call it as a native function.
1157 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Nick Lewycky109af622009-04-12 20:47:23 +00001158 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001159
1160 // Delete the anonymous expression module from the JIT.
1161 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001162 }
1163 } else {
1164 // Skip token for error recovery.
1165 getNextToken();
1166 }
1167}
1168
1169/// top ::= definition | external | expression | ';'
1170static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001171 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +00001172 fprintf(stderr, "ready> ");
1173 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001174 case tok_eof:
1175 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001176 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001177 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001178 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001179 case tok_def:
1180 HandleDefinition();
1181 break;
1182 case tok_extern:
1183 HandleExtern();
1184 break;
1185 default:
1186 HandleTopLevelExpression();
1187 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001188 }
1189 }
1190}
1191
Nick Lewycky109af622009-04-12 20:47:23 +00001192//===----------------------------------------------------------------------===//
1193// "Library" functions that can be "extern'd" from user code.
1194//===----------------------------------------------------------------------===//
1195
1196/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001197extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001198 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001199 return 0;
1200}
1201
1202/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001203extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001204 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001205 return 0;
1206}
1207
1208//===----------------------------------------------------------------------===//
1209// Main driver code.
1210//===----------------------------------------------------------------------===//
1211
1212int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001213 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001214 InitializeNativeTargetAsmPrinter();
1215 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001216
Nick Lewycky109af622009-04-12 20:47:23 +00001217 // Install standard binary operators.
1218 // 1 is lowest precedence.
1219 BinopPrecedence['='] = 2;
1220 BinopPrecedence['<'] = 10;
1221 BinopPrecedence['+'] = 20;
1222 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001223 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001224
1225 // Prime the first token.
1226 fprintf(stderr, "ready> ");
1227 getNextToken();
1228
Lang Hames2d789c32015-08-26 03:07:41 +00001229 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001230
Lang Hames2d789c32015-08-26 03:07:41 +00001231 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001232
1233 // Run the main "interpreter loop" now.
1234 MainLoop();
1235
Nick Lewycky109af622009-04-12 20:47:23 +00001236 return 0;
1237}