blob: 41c27d06d477050bbd97a77345f09d63fbc5d4bb [file] [log] [blame]
David Blaikiea373d182018-03-28 17:44:36 +00001#include "../include/KaleidoscopeJIT.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +00002#include "llvm/ADT/APFloat.h"
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00003#include "llvm/ADT/STLExtras.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +00004#include "llvm/IR/BasicBlock.h"
5#include "llvm/IR/Constants.h"
6#include "llvm/IR/DerivedTypes.h"
7#include "llvm/IR/Function.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00008#include "llvm/IR/IRBuilder.h"
David Blaikiea373d182018-03-28 17:44:36 +00009#include "llvm/IR/Instructions.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +000010#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000011#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +000012#include "llvm/IR/Module.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000013#include "llvm/IR/Type.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +000014#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000015#include "llvm/Support/TargetSelect.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000016#include "llvm/Target/TargetMachine.h"
David Blaikiea27771b2018-04-24 00:48:59 +000017#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000018#include "llvm/Transforms/Scalar.h"
Chandler Carruthec5872b2016-03-11 12:10:15 +000019#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiea373d182018-03-28 17:44:36 +000020#include "llvm/Transforms/Utils.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +000021#include <algorithm>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000022#include <cassert>
23#include <cctype>
24#include <cstdint>
25#include <cstdio>
26#include <cstdlib>
27#include <map>
28#include <memory>
29#include <string>
30#include <utility>
31#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000032
Nick Lewycky109af622009-04-12 20:47:23 +000033using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000034using namespace llvm::orc;
Nick Lewycky109af622009-04-12 20:47:23 +000035
36//===----------------------------------------------------------------------===//
37// Lexer
38//===----------------------------------------------------------------------===//
39
40// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
41// of these for known things.
42enum Token {
43 tok_eof = -1,
44
45 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000046 tok_def = -2,
47 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000048
49 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000050 tok_identifier = -4,
51 tok_number = -5,
52
Nick Lewycky109af622009-04-12 20:47:23 +000053 // control
Eric Christopherc0239362014-12-08 18:12:28 +000054 tok_if = -6,
55 tok_then = -7,
56 tok_else = -8,
57 tok_for = -9,
58 tok_in = -10,
59
Nick Lewycky109af622009-04-12 20:47:23 +000060 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000061 tok_binary = -11,
62 tok_unary = -12,
63
Nick Lewycky109af622009-04-12 20:47:23 +000064 // var definition
65 tok_var = -13
66};
67
Eric Christopherc0239362014-12-08 18:12:28 +000068static std::string IdentifierStr; // Filled in if tok_identifier
69static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000070
71/// gettok - Return the next token from standard input.
72static int gettok() {
73 static int LastChar = ' ';
74
75 // Skip any whitespace.
76 while (isspace(LastChar))
77 LastChar = getchar();
78
79 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
80 IdentifierStr = LastChar;
81 while (isalnum((LastChar = getchar())))
82 IdentifierStr += LastChar;
83
Eric Christopherc0239362014-12-08 18:12:28 +000084 if (IdentifierStr == "def")
85 return tok_def;
86 if (IdentifierStr == "extern")
87 return tok_extern;
88 if (IdentifierStr == "if")
89 return tok_if;
90 if (IdentifierStr == "then")
91 return tok_then;
92 if (IdentifierStr == "else")
93 return tok_else;
94 if (IdentifierStr == "for")
95 return tok_for;
96 if (IdentifierStr == "in")
97 return tok_in;
98 if (IdentifierStr == "binary")
99 return tok_binary;
100 if (IdentifierStr == "unary")
101 return tok_unary;
102 if (IdentifierStr == "var")
103 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +0000104 return tok_identifier;
105 }
106
Eric Christopherc0239362014-12-08 18:12:28 +0000107 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +0000108 std::string NumStr;
109 do {
110 NumStr += LastChar;
111 LastChar = getchar();
112 } while (isdigit(LastChar) || LastChar == '.');
113
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000114 NumVal = strtod(NumStr.c_str(), nullptr);
Nick Lewycky109af622009-04-12 20:47:23 +0000115 return tok_number;
116 }
117
118 if (LastChar == '#') {
119 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000120 do
121 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000122 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000123
Nick Lewycky109af622009-04-12 20:47:23 +0000124 if (LastChar != EOF)
125 return gettok();
126 }
Eric Christopherc0239362014-12-08 18:12:28 +0000127
Nick Lewycky109af622009-04-12 20:47:23 +0000128 // Check for end of file. Don't eat the EOF.
129 if (LastChar == EOF)
130 return tok_eof;
131
132 // Otherwise, just return the character as its ascii value.
133 int ThisChar = LastChar;
134 LastChar = getchar();
135 return ThisChar;
136}
137
138//===----------------------------------------------------------------------===//
139// Abstract Syntax Tree (aka Parse Tree)
140//===----------------------------------------------------------------------===//
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000141
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000142namespace {
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000143
Nick Lewycky109af622009-04-12 20:47:23 +0000144/// ExprAST - Base class for all expression nodes.
145class ExprAST {
146public:
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000147 virtual ~ExprAST() = default;
148
Lang Hames2d789c32015-08-26 03:07:41 +0000149 virtual Value *codegen() = 0;
Nick Lewycky109af622009-04-12 20:47:23 +0000150};
151
152/// NumberExprAST - Expression class for numeric literals like "1.0".
153class NumberExprAST : public ExprAST {
154 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000155
Nick Lewycky109af622009-04-12 20:47:23 +0000156public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000157 NumberExprAST(double Val) : Val(Val) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000158
Lang Hames2d789c32015-08-26 03:07:41 +0000159 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000160};
161
162/// VariableExprAST - Expression class for referencing a variable, like "a".
163class VariableExprAST : public ExprAST {
164 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000165
Nick Lewycky109af622009-04-12 20:47:23 +0000166public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000167 VariableExprAST(const std::string &Name) : Name(Name) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000168
Lang Hames2d789c32015-08-26 03:07:41 +0000169 Value *codegen() override;
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000170 const std::string &getName() const { return Name; }
Nick Lewycky109af622009-04-12 20:47:23 +0000171};
172
173/// UnaryExprAST - Expression class for a unary operator.
174class UnaryExprAST : public ExprAST {
175 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000176 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000177
Nick Lewycky109af622009-04-12 20:47:23 +0000178public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000179 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
180 : Opcode(Opcode), Operand(std::move(Operand)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000181
Lang Hames2d789c32015-08-26 03:07:41 +0000182 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000183};
184
185/// BinaryExprAST - Expression class for a binary operator.
186class BinaryExprAST : public ExprAST {
187 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000188 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000189
Nick Lewycky109af622009-04-12 20:47:23 +0000190public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000191 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
192 std::unique_ptr<ExprAST> RHS)
193 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000194
Lang Hames2d789c32015-08-26 03:07:41 +0000195 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000196};
197
198/// CallExprAST - Expression class for function calls.
199class CallExprAST : public ExprAST {
200 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000201 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000202
Nick Lewycky109af622009-04-12 20:47:23 +0000203public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000204 CallExprAST(const std::string &Callee,
205 std::vector<std::unique_ptr<ExprAST>> Args)
206 : Callee(Callee), Args(std::move(Args)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000207
Lang Hames2d789c32015-08-26 03:07:41 +0000208 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000209};
210
211/// IfExprAST - Expression class for if/then/else.
212class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000213 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000214
Nick Lewycky109af622009-04-12 20:47:23 +0000215public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000216 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
217 std::unique_ptr<ExprAST> Else)
218 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000219
Lang Hames2d789c32015-08-26 03:07:41 +0000220 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000221};
222
223/// ForExprAST - Expression class for for/in.
224class ForExprAST : public ExprAST {
225 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000226 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000227
Nick Lewycky109af622009-04-12 20:47:23 +0000228public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000229 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
230 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
231 std::unique_ptr<ExprAST> Body)
232 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
233 Step(std::move(Step)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000234
Lang Hames2d789c32015-08-26 03:07:41 +0000235 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000236};
237
238/// VarExprAST - Expression class for var/in
239class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000240 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
241 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000242
Nick Lewycky109af622009-04-12 20:47:23 +0000243public:
Lang Hames59b0da82015-08-19 18:15:58 +0000244 VarExprAST(
245 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
246 std::unique_ptr<ExprAST> Body)
247 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000248
Lang Hames2d789c32015-08-26 03:07:41 +0000249 Value *codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000250};
251
252/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000253/// which captures its name, and its argument names (thus implicitly the number
254/// of arguments the function takes), as well as if it is an operator.
Nick Lewycky109af622009-04-12 20:47:23 +0000255class PrototypeAST {
256 std::string Name;
257 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000258 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000259 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000260
Nick Lewycky109af622009-04-12 20:47:23 +0000261public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000262 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
263 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000264 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
265 Precedence(Prec) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000266
Lang Hames2d789c32015-08-26 03:07:41 +0000267 Function *codegen();
268 const std::string &getName() const { return Name; }
Eric Christopherc0239362014-12-08 18:12:28 +0000269
Lang Hames09bf4c12015-08-18 18:11:06 +0000270 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
271 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000272
Nick Lewycky109af622009-04-12 20:47:23 +0000273 char getOperatorName() const {
274 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000275 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000276 }
Eric Christopherc0239362014-12-08 18:12:28 +0000277
Nick Lewycky109af622009-04-12 20:47:23 +0000278 unsigned getBinaryPrecedence() const { return Precedence; }
Nick Lewycky109af622009-04-12 20:47:23 +0000279};
280
281/// FunctionAST - This class represents a function definition itself.
282class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000283 std::unique_ptr<PrototypeAST> Proto;
284 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000285
Nick Lewycky109af622009-04-12 20:47:23 +0000286public:
Lang Hames59b0da82015-08-19 18:15:58 +0000287 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
288 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000289 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000290
Lang Hames2d789c32015-08-26 03:07:41 +0000291 Function *codegen();
Nick Lewycky109af622009-04-12 20:47:23 +0000292};
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000293
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000294} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000295
296//===----------------------------------------------------------------------===//
297// Parser
298//===----------------------------------------------------------------------===//
299
300/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000301/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000302/// lexer and updates CurTok with its results.
303static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000304static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000305
306/// BinopPrecedence - This holds the precedence for each binary operator that is
307/// defined.
308static std::map<char, int> BinopPrecedence;
309
310/// GetTokPrecedence - Get the precedence of the pending binary operator token.
311static int GetTokPrecedence() {
312 if (!isascii(CurTok))
313 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000314
Nick Lewycky109af622009-04-12 20:47:23 +0000315 // Make sure it's a declared binop.
316 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000317 if (TokPrec <= 0)
318 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000319 return TokPrec;
320}
321
Lang Hamesf9878c52016-03-25 17:33:32 +0000322/// LogError* - These are little helper functions for error handling.
323std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000324 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000325 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000326}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000327
Lang Hamesf9878c52016-03-25 17:33:32 +0000328std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
329 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000330 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000331}
Nick Lewycky109af622009-04-12 20:47:23 +0000332
Lang Hames09bf4c12015-08-18 18:11:06 +0000333static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000334
Lang Hames59b0da82015-08-19 18:15:58 +0000335/// numberexpr ::= number
336static std::unique_ptr<ExprAST> ParseNumberExpr() {
337 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
338 getNextToken(); // consume the number
339 return std::move(Result);
340}
341
342/// parenexpr ::= '(' expression ')'
343static std::unique_ptr<ExprAST> ParseParenExpr() {
344 getNextToken(); // eat (.
345 auto V = ParseExpression();
346 if (!V)
347 return nullptr;
348
349 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000350 return LogError("expected ')'");
Lang Hames59b0da82015-08-19 18:15:58 +0000351 getNextToken(); // eat ).
352 return V;
353}
354
Nick Lewycky109af622009-04-12 20:47:23 +0000355/// identifierexpr
356/// ::= identifier
357/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000358static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000359 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000360
361 getNextToken(); // eat identifier.
362
Nick Lewycky109af622009-04-12 20:47:23 +0000363 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000364 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000365
Nick Lewycky109af622009-04-12 20:47:23 +0000366 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000367 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000368 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000369 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000370 while (true) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000371 if (auto Arg = ParseExpression())
372 Args.push_back(std::move(Arg));
373 else
374 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000375
Eric Christopherc0239362014-12-08 18:12:28 +0000376 if (CurTok == ')')
377 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000378
Nick Lewycky109af622009-04-12 20:47:23 +0000379 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000380 return LogError("Expected ')' or ',' in argument list");
Nick Lewycky109af622009-04-12 20:47:23 +0000381 getNextToken();
382 }
383 }
384
385 // Eat the ')'.
386 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000387
Lang Hames09bf4c12015-08-18 18:11:06 +0000388 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000389}
390
Nick Lewycky109af622009-04-12 20:47:23 +0000391/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000392static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000393 getNextToken(); // eat the if.
394
Nick Lewycky109af622009-04-12 20:47:23 +0000395 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000396 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000397 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000398 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000399
Nick Lewycky109af622009-04-12 20:47:23 +0000400 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000401 return LogError("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000402 getNextToken(); // eat the then
403
Lang Hames09bf4c12015-08-18 18:11:06 +0000404 auto Then = ParseExpression();
405 if (!Then)
406 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000407
Nick Lewycky109af622009-04-12 20:47:23 +0000408 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000409 return LogError("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000410
Nick Lewycky109af622009-04-12 20:47:23 +0000411 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000412
Lang Hames09bf4c12015-08-18 18:11:06 +0000413 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000414 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000415 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000416
Lang Hames09bf4c12015-08-18 18:11:06 +0000417 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
418 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000419}
420
421/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000422static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000423 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000424
425 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000426 return LogError("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000427
Nick Lewycky109af622009-04-12 20:47:23 +0000428 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000429 getNextToken(); // eat identifier.
430
Nick Lewycky109af622009-04-12 20:47:23 +0000431 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000432 return LogError("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000433 getNextToken(); // eat '='.
434
Lang Hames09bf4c12015-08-18 18:11:06 +0000435 auto Start = ParseExpression();
436 if (!Start)
437 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000438 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000439 return LogError("expected ',' after for start value");
Nick Lewycky109af622009-04-12 20:47:23 +0000440 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000441
Lang Hames09bf4c12015-08-18 18:11:06 +0000442 auto End = ParseExpression();
443 if (!End)
444 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000445
Nick Lewycky109af622009-04-12 20:47:23 +0000446 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000447 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000448 if (CurTok == ',') {
449 getNextToken();
450 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000451 if (!Step)
452 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000453 }
Eric Christopherc0239362014-12-08 18:12:28 +0000454
Nick Lewycky109af622009-04-12 20:47:23 +0000455 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000456 return LogError("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000457 getNextToken(); // eat 'in'.
458
Lang Hames09bf4c12015-08-18 18:11:06 +0000459 auto Body = ParseExpression();
460 if (!Body)
461 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000462
Lang Hames09bf4c12015-08-18 18:11:06 +0000463 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
464 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000465}
466
Eric Christopherc0239362014-12-08 18:12:28 +0000467/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000468// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000469static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000470 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000471
Lang Hames09bf4c12015-08-18 18:11:06 +0000472 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000473
474 // At least one variable name is required.
475 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000476 return LogError("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000477
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000478 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000479 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000480 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000481
482 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000483 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000484 if (CurTok == '=') {
485 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000486
Nick Lewycky109af622009-04-12 20:47:23 +0000487 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000488 if (!Init)
489 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000490 }
Eric Christopherc0239362014-12-08 18:12:28 +0000491
Lang Hames09bf4c12015-08-18 18:11:06 +0000492 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000493
Nick Lewycky109af622009-04-12 20:47:23 +0000494 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000495 if (CurTok != ',')
496 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000497 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000498
Nick Lewycky109af622009-04-12 20:47:23 +0000499 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000500 return LogError("expected identifier list after var");
Nick Lewycky109af622009-04-12 20:47:23 +0000501 }
Eric Christopherc0239362014-12-08 18:12:28 +0000502
Nick Lewycky109af622009-04-12 20:47:23 +0000503 // At this point, we have to have 'in'.
504 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000505 return LogError("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000506 getNextToken(); // eat 'in'.
507
Lang Hames09bf4c12015-08-18 18:11:06 +0000508 auto Body = ParseExpression();
509 if (!Body)
510 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000511
Lang Hames09bf4c12015-08-18 18:11:06 +0000512 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000513}
514
Nick Lewycky109af622009-04-12 20:47:23 +0000515/// primary
516/// ::= identifierexpr
517/// ::= numberexpr
518/// ::= parenexpr
519/// ::= ifexpr
520/// ::= forexpr
521/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000522static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000523 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000524 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000525 return LogError("unknown token when expecting an expression");
Eric Christopherc0239362014-12-08 18:12:28 +0000526 case tok_identifier:
527 return ParseIdentifierExpr();
528 case tok_number:
529 return ParseNumberExpr();
530 case '(':
531 return ParseParenExpr();
532 case tok_if:
533 return ParseIfExpr();
534 case tok_for:
535 return ParseForExpr();
536 case tok_var:
537 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000538 }
539}
540
541/// unary
542/// ::= primary
543/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000544static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000545 // If the current token is not an operator, it must be a primary expr.
546 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
547 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000548
Nick Lewycky109af622009-04-12 20:47:23 +0000549 // If this is a unary operator, read it.
550 int Opc = CurTok;
551 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000552 if (auto Operand = ParseUnary())
553 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
554 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000555}
556
557/// binoprhs
558/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000559static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
560 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000561 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000562 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +0000563 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000564
Nick Lewycky109af622009-04-12 20:47:23 +0000565 // If this is a binop that binds at least as tightly as the current binop,
566 // consume it, otherwise we are done.
567 if (TokPrec < ExprPrec)
568 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000569
Nick Lewycky109af622009-04-12 20:47:23 +0000570 // Okay, we know this is a binop.
571 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000572 getNextToken(); // eat binop
573
Nick Lewycky109af622009-04-12 20:47:23 +0000574 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000575 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000576 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000577 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000578
Nick Lewycky109af622009-04-12 20:47:23 +0000579 // If BinOp binds less tightly with RHS than the operator after RHS, let
580 // the pending operator take RHS as its LHS.
581 int NextPrec = GetTokPrecedence();
582 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000583 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
584 if (!RHS)
585 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000586 }
Eric Christopherc0239362014-12-08 18:12:28 +0000587
Nick Lewycky109af622009-04-12 20:47:23 +0000588 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000589 LHS =
590 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000591 }
592}
593
594/// expression
595/// ::= unary binoprhs
596///
Lang Hames09bf4c12015-08-18 18:11:06 +0000597static std::unique_ptr<ExprAST> ParseExpression() {
598 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000599 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000600 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000601
Lang Hames09bf4c12015-08-18 18:11:06 +0000602 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000603}
604
605/// prototype
606/// ::= id '(' id* ')'
607/// ::= binary LETTER number? (id, id)
608/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000609static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000610 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000611
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000612 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000613 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000614
Nick Lewycky109af622009-04-12 20:47:23 +0000615 switch (CurTok) {
616 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000617 return LogErrorP("Expected function name in prototype");
Nick Lewycky109af622009-04-12 20:47:23 +0000618 case tok_identifier:
619 FnName = IdentifierStr;
620 Kind = 0;
621 getNextToken();
622 break;
623 case tok_unary:
624 getNextToken();
625 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000626 return LogErrorP("Expected unary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000627 FnName = "unary";
628 FnName += (char)CurTok;
629 Kind = 1;
630 getNextToken();
631 break;
632 case tok_binary:
633 getNextToken();
634 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000635 return LogErrorP("Expected binary operator");
Nick Lewycky109af622009-04-12 20:47:23 +0000636 FnName = "binary";
637 FnName += (char)CurTok;
638 Kind = 2;
639 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000640
Nick Lewycky109af622009-04-12 20:47:23 +0000641 // Read the precedence if present.
642 if (CurTok == tok_number) {
643 if (NumVal < 1 || NumVal > 100)
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000644 return LogErrorP("Invalid precedence: must be 1..100");
Nick Lewycky109af622009-04-12 20:47:23 +0000645 BinaryPrecedence = (unsigned)NumVal;
646 getNextToken();
647 }
648 break;
649 }
Eric Christopherc0239362014-12-08 18:12:28 +0000650
Nick Lewycky109af622009-04-12 20:47:23 +0000651 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000652 return LogErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000653
Nick Lewycky109af622009-04-12 20:47:23 +0000654 std::vector<std::string> ArgNames;
655 while (getNextToken() == tok_identifier)
656 ArgNames.push_back(IdentifierStr);
657 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000658 return LogErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000659
Nick Lewycky109af622009-04-12 20:47:23 +0000660 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000661 getNextToken(); // eat ')'.
662
Nick Lewycky109af622009-04-12 20:47:23 +0000663 // Verify right number of names for operator.
664 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000665 return LogErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000666
Lang Hames09bf4c12015-08-18 18:11:06 +0000667 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
668 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000669}
670
671/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000672static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000673 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000674 auto Proto = ParsePrototype();
675 if (!Proto)
676 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000677
Lang Hames09bf4c12015-08-18 18:11:06 +0000678 if (auto E = ParseExpression())
679 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
680 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000681}
682
683/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000684static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
685 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000686 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000687 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
688 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000689 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000690 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000691 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000692}
693
694/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000695static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000696 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000697 return ParsePrototype();
698}
699
700//===----------------------------------------------------------------------===//
701// Code Generation
702//===----------------------------------------------------------------------===//
703
Mehdi Amini03b42e42016-04-14 21:59:01 +0000704static LLVMContext TheContext;
705static IRBuilder<> Builder(TheContext);
Lang Hames24796802016-05-22 22:48:36 +0000706static std::unique_ptr<Module> TheModule;
Eric Christopherc0239362014-12-08 18:12:28 +0000707static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000708static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
709static std::unique_ptr<KaleidoscopeJIT> TheJIT;
710static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Nick Lewycky109af622009-04-12 20:47:23 +0000711
Lang Hamesf9878c52016-03-25 17:33:32 +0000712Value *LogErrorV(const char *Str) {
713 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000714 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000715}
Nick Lewycky109af622009-04-12 20:47:23 +0000716
Lang Hames2d789c32015-08-26 03:07:41 +0000717Function *getFunction(std::string Name) {
718 // First, see if the function has already been added to the current module.
719 if (auto *F = TheModule->getFunction(Name))
720 return F;
721
722 // If not, check whether we can codegen the declaration from some existing
723 // prototype.
724 auto FI = FunctionProtos.find(Name);
725 if (FI != FunctionProtos.end())
726 return FI->second->codegen();
727
728 // If no existing prototype exists, return null.
729 return nullptr;
730}
731
Nick Lewycky109af622009-04-12 20:47:23 +0000732/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
733/// the function. This is used for mutable variables etc.
734static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
735 const std::string &VarName) {
736 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000737 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000738 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Nick Lewycky109af622009-04-12 20:47:23 +0000739}
740
Lang Hames2d789c32015-08-26 03:07:41 +0000741Value *NumberExprAST::codegen() {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000742 return ConstantFP::get(TheContext, APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000743}
744
Lang Hames2d789c32015-08-26 03:07:41 +0000745Value *VariableExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000746 // Look this variable up in the function.
747 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000748 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000749 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000750
751 // Load the value.
752 return Builder.CreateLoad(V, Name.c_str());
753}
754
Lang Hames2d789c32015-08-26 03:07:41 +0000755Value *UnaryExprAST::codegen() {
756 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000757 if (!OperandV)
758 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000759
Lang Hames2d789c32015-08-26 03:07:41 +0000760 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000761 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000762 return LogErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000763
Nick Lewycky109af622009-04-12 20:47:23 +0000764 return Builder.CreateCall(F, OperandV, "unop");
765}
766
Lang Hames2d789c32015-08-26 03:07:41 +0000767Value *BinaryExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000768 // Special case '=' because we don't want to emit the LHS as an expression.
769 if (Op == '=') {
770 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000771 // This assume we're building without RTTI because LLVM builds that way by
772 // default. If you build LLVM with RTTI this can be changed to a
773 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000774 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000775 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000776 return LogErrorV("destination of '=' must be a variable");
Nick Lewycky109af622009-04-12 20:47:23 +0000777 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000778 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000779 if (!Val)
780 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000781
782 // Look up the name.
783 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000784 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000785 return LogErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000786
787 Builder.CreateStore(Val, Variable);
788 return Val;
789 }
Eric Christopherc0239362014-12-08 18:12:28 +0000790
Lang Hames2d789c32015-08-26 03:07:41 +0000791 Value *L = LHS->codegen();
792 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000793 if (!L || !R)
794 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000795
Nick Lewycky109af622009-04-12 20:47:23 +0000796 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000797 case '+':
798 return Builder.CreateFAdd(L, R, "addtmp");
799 case '-':
800 return Builder.CreateFSub(L, R, "subtmp");
801 case '*':
802 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000803 case '<':
804 L = Builder.CreateFCmpULT(L, R, "cmptmp");
805 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000806 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000807 default:
808 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000809 }
Eric Christopherc0239362014-12-08 18:12:28 +0000810
Nick Lewycky109af622009-04-12 20:47:23 +0000811 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
812 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000813 Function *F = getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000814 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000815
Lang Hames59b0da82015-08-19 18:15:58 +0000816 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000817 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000818}
819
Lang Hames2d789c32015-08-26 03:07:41 +0000820Value *CallExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000821 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000822 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000823 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +0000824 return LogErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000825
Nick Lewycky109af622009-04-12 20:47:23 +0000826 // If argument mismatch error.
827 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +0000828 return LogErrorV("Incorrect # arguments passed");
Nick Lewycky109af622009-04-12 20:47:23 +0000829
Eric Christopherc0239362014-12-08 18:12:28 +0000830 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000831 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000832 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000833 if (!ArgsV.back())
834 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000835 }
Eric Christopherc0239362014-12-08 18:12:28 +0000836
Francois Pichetc5d10502011-07-15 10:59:52 +0000837 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000838}
839
Lang Hames2d789c32015-08-26 03:07:41 +0000840Value *IfExprAST::codegen() {
841 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000842 if (!CondV)
843 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000844
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000845 // Convert condition to a bool by comparing non-equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000846 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000847 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000848
Nick Lewycky109af622009-04-12 20:47:23 +0000849 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000850
Nick Lewycky109af622009-04-12 20:47:23 +0000851 // Create blocks for the then and else cases. Insert the 'then' block at the
852 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000853 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
854 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
855 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000856
Nick Lewycky109af622009-04-12 20:47:23 +0000857 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000858
Nick Lewycky109af622009-04-12 20:47:23 +0000859 // Emit then value.
860 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000861
Lang Hames2d789c32015-08-26 03:07:41 +0000862 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000863 if (!ThenV)
864 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000865
Nick Lewycky109af622009-04-12 20:47:23 +0000866 Builder.CreateBr(MergeBB);
867 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
868 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000869
Nick Lewycky109af622009-04-12 20:47:23 +0000870 // Emit else block.
871 TheFunction->getBasicBlockList().push_back(ElseBB);
872 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000873
Lang Hames2d789c32015-08-26 03:07:41 +0000874 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000875 if (!ElseV)
876 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000877
Nick Lewycky109af622009-04-12 20:47:23 +0000878 Builder.CreateBr(MergeBB);
879 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
880 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000881
Nick Lewycky109af622009-04-12 20:47:23 +0000882 // Emit merge block.
883 TheFunction->getBasicBlockList().push_back(MergeBB);
884 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000885 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000886
Nick Lewycky109af622009-04-12 20:47:23 +0000887 PN->addIncoming(ThenV, ThenBB);
888 PN->addIncoming(ElseV, ElseBB);
889 return PN;
890}
891
Lang Hames59b0da82015-08-19 18:15:58 +0000892// Output for-loop as:
893// var = alloca double
894// ...
895// start = startexpr
896// store start -> var
897// goto loop
898// loop:
899// ...
900// bodyexpr
901// ...
902// loopend:
903// step = stepexpr
904// endcond = endexpr
905//
906// curvar = load var
907// nextvar = curvar + step
908// store nextvar -> var
909// br endcond, loop, endloop
910// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000911Value *ForExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000912 Function *TheFunction = Builder.GetInsertBlock()->getParent();
913
914 // Create an alloca for the variable in the entry block.
915 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000916
Nick Lewycky109af622009-04-12 20:47:23 +0000917 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000918 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000919 if (!StartVal)
920 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000921
Nick Lewycky109af622009-04-12 20:47:23 +0000922 // Store the value into the alloca.
923 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000924
Nick Lewycky109af622009-04-12 20:47:23 +0000925 // Make the new basic block for the loop header, inserting after current
926 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000927 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000928
Nick Lewycky109af622009-04-12 20:47:23 +0000929 // Insert an explicit fall through from the current block to the LoopBB.
930 Builder.CreateBr(LoopBB);
931
932 // Start insertion in LoopBB.
933 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000934
Nick Lewycky109af622009-04-12 20:47:23 +0000935 // Within the loop, the variable is defined equal to the PHI node. If it
936 // shadows an existing variable, we have to restore it, so save it now.
937 AllocaInst *OldVal = NamedValues[VarName];
938 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000939
Nick Lewycky109af622009-04-12 20:47:23 +0000940 // Emit the body of the loop. This, like any other expr, can change the
941 // current BB. Note that we ignore the value computed by the body, but don't
942 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000943 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000944 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000945
Nick Lewycky109af622009-04-12 20:47:23 +0000946 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000947 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000948 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000949 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000950 if (!StepVal)
951 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000952 } else {
953 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000954 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000955 }
Eric Christopherc0239362014-12-08 18:12:28 +0000956
Nick Lewycky109af622009-04-12 20:47:23 +0000957 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000958 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000959 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000960 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000961
Nick Lewycky109af622009-04-12 20:47:23 +0000962 // Reload, increment, and restore the alloca. This handles the case where
963 // the body of the loop mutates the variable.
964 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000965 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000966 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000967
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000968 // Convert condition to a bool by comparing non-equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000969 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000970 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopherc0239362014-12-08 18:12:28 +0000971
Nick Lewycky109af622009-04-12 20:47:23 +0000972 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000973 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +0000974 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +0000975
Nick Lewycky109af622009-04-12 20:47:23 +0000976 // Insert the conditional branch into the end of LoopEndBB.
977 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000978
Nick Lewycky109af622009-04-12 20:47:23 +0000979 // Any new code will be inserted in AfterBB.
980 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000981
Nick Lewycky109af622009-04-12 20:47:23 +0000982 // Restore the unshadowed variable.
983 if (OldVal)
984 NamedValues[VarName] = OldVal;
985 else
986 NamedValues.erase(VarName);
987
Nick Lewycky109af622009-04-12 20:47:23 +0000988 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000989 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Nick Lewycky109af622009-04-12 20:47:23 +0000990}
991
Lang Hames2d789c32015-08-26 03:07:41 +0000992Value *VarExprAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000993 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000994
Nick Lewycky109af622009-04-12 20:47:23 +0000995 Function *TheFunction = Builder.GetInsertBlock()->getParent();
996
997 // Register all variables and emit their initializer.
998 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
999 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +00001000 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +00001001
Nick Lewycky109af622009-04-12 20:47:23 +00001002 // Emit the initializer before adding the variable to scope, this prevents
1003 // the initializer from referencing the variable itself, and permits stuff
1004 // like this:
1005 // var a = 1 in
1006 // var a = a in ... # refers to outer 'a'.
1007 Value *InitVal;
1008 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +00001009 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001010 if (!InitVal)
1011 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001012 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001013 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +00001014 }
Eric Christopherc0239362014-12-08 18:12:28 +00001015
Nick Lewycky109af622009-04-12 20:47:23 +00001016 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1017 Builder.CreateStore(InitVal, Alloca);
1018
1019 // Remember the old variable binding so that we can restore the binding when
1020 // we unrecurse.
1021 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +00001022
Nick Lewycky109af622009-04-12 20:47:23 +00001023 // Remember this binding.
1024 NamedValues[VarName] = Alloca;
1025 }
Eric Christopherc0239362014-12-08 18:12:28 +00001026
Nick Lewycky109af622009-04-12 20:47:23 +00001027 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001028 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001029 if (!BodyVal)
1030 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001031
Nick Lewycky109af622009-04-12 20:47:23 +00001032 // Pop all our variables from scope.
1033 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1034 NamedValues[VarNames[i].first] = OldBindings[i];
1035
1036 // Return the body computation.
1037 return BodyVal;
1038}
1039
Lang Hames2d789c32015-08-26 03:07:41 +00001040Function *PrototypeAST::codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +00001041 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001042 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopherc0239362014-12-08 18:12:28 +00001043 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001044 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopherc0239362014-12-08 18:12:28 +00001045
1046 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001047 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +00001048
Nick Lewycky109af622009-04-12 20:47:23 +00001049 // Set names for all arguments.
1050 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001051 for (auto &Arg : F->args())
1052 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +00001053
Nick Lewycky109af622009-04-12 20:47:23 +00001054 return F;
1055}
1056
Lang Hames2d789c32015-08-26 03:07:41 +00001057Function *FunctionAST::codegen() {
1058 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1059 // reference to it for use below.
1060 auto &P = *Proto;
1061 FunctionProtos[Proto->getName()] = std::move(Proto);
1062 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001063 if (!TheFunction)
1064 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001065
Nick Lewycky109af622009-04-12 20:47:23 +00001066 // If this is an operator, install it.
Lang Hames2d789c32015-08-26 03:07:41 +00001067 if (P.isBinaryOp())
1068 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001069
Nick Lewycky109af622009-04-12 20:47:23 +00001070 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001071 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001072 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001073
Lang Hames2d789c32015-08-26 03:07:41 +00001074 // Record the function arguments in the NamedValues map.
1075 NamedValues.clear();
1076 for (auto &Arg : TheFunction->args()) {
1077 // Create an alloca for this variable.
1078 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001079
Lang Hames2d789c32015-08-26 03:07:41 +00001080 // Store the initial value into the alloca.
1081 Builder.CreateStore(&Arg, Alloca);
1082
1083 // Add arguments to variable symbol table.
1084 NamedValues[Arg.getName()] = Alloca;
1085 }
1086
1087 if (Value *RetVal = Body->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001088 // Finish off the function.
1089 Builder.CreateRet(RetVal);
1090
1091 // Validate the generated code, checking for consistency.
1092 verifyFunction(*TheFunction);
1093
Lang Hames2d789c32015-08-26 03:07:41 +00001094 // Run the optimizer on the function.
Nick Lewycky109af622009-04-12 20:47:23 +00001095 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001096
Nick Lewycky109af622009-04-12 20:47:23 +00001097 return TheFunction;
1098 }
Eric Christopherc0239362014-12-08 18:12:28 +00001099
Nick Lewycky109af622009-04-12 20:47:23 +00001100 // Error reading body, remove function.
1101 TheFunction->eraseFromParent();
1102
Lang Hames2d789c32015-08-26 03:07:41 +00001103 if (P.isBinaryOp())
Peter Szecsi5305d392017-05-07 11:00:01 +00001104 BinopPrecedence.erase(P.getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001105 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001106}
1107
1108//===----------------------------------------------------------------------===//
1109// Top-Level parsing and JIT Driver
1110//===----------------------------------------------------------------------===//
1111
Lang Hames2d789c32015-08-26 03:07:41 +00001112static void InitializeModuleAndPassManager() {
1113 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001114 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001115 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1116
1117 // Create a new pass manager attached to it.
1118 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1119
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001120 // Promote allocas to registers.
1121 TheFPM->add(createPromoteMemoryToRegisterPass());
Lang Hames2d789c32015-08-26 03:07:41 +00001122 // Do simple "peephole" optimizations and bit-twiddling optzns.
1123 TheFPM->add(createInstructionCombiningPass());
1124 // Reassociate expressions.
1125 TheFPM->add(createReassociatePass());
1126 // Eliminate Common SubExpressions.
1127 TheFPM->add(createGVNPass());
1128 // Simplify the control flow graph (deleting unreachable blocks, etc).
1129 TheFPM->add(createCFGSimplificationPass());
1130
1131 TheFPM->doInitialization();
1132}
Nick Lewycky109af622009-04-12 20:47:23 +00001133
1134static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001135 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001136 if (auto *FnIR = FnAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001137 fprintf(stderr, "Read function definition:");
Matthias Braun25bcaba2017-01-28 02:47:46 +00001138 FnIR->print(errs());
1139 fprintf(stderr, "\n");
Lang Hames2d789c32015-08-26 03:07:41 +00001140 TheJIT->addModule(std::move(TheModule));
1141 InitializeModuleAndPassManager();
Nick Lewycky109af622009-04-12 20:47:23 +00001142 }
1143 } else {
1144 // Skip token for error recovery.
1145 getNextToken();
1146 }
1147}
1148
1149static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001150 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001151 if (auto *FnIR = ProtoAST->codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001152 fprintf(stderr, "Read extern: ");
Matthias Braun25bcaba2017-01-28 02:47:46 +00001153 FnIR->print(errs());
1154 fprintf(stderr, "\n");
Lang Hames2d789c32015-08-26 03:07:41 +00001155 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Nick Lewycky109af622009-04-12 20:47:23 +00001156 }
1157 } else {
1158 // Skip token for error recovery.
1159 getNextToken();
1160 }
1161}
1162
1163static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001164 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001165 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001166 if (FnAST->codegen()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001167 // JIT the module containing the anonymous expression, keeping a handle so
1168 // we can free it later.
1169 auto H = TheJIT->addModule(std::move(TheModule));
1170 InitializeModuleAndPassManager();
1171
1172 // Search the JIT for the __anon_expr symbol.
1173 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1174 assert(ExprSymbol && "Function not found");
1175
1176 // Get the symbol's address and cast it to the right type (takes no
1177 // arguments, returns a double) so we can call it as a native function.
Lang Hames4ce98662017-07-07 02:59:13 +00001178 double (*FP)() = (double (*)())(intptr_t)cantFail(ExprSymbol.getAddress());
Nick Lewycky109af622009-04-12 20:47:23 +00001179 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +00001180
1181 // Delete the anonymous expression module from the JIT.
1182 TheJIT->removeModule(H);
Nick Lewycky109af622009-04-12 20:47:23 +00001183 }
1184 } else {
1185 // Skip token for error recovery.
1186 getNextToken();
1187 }
1188}
1189
1190/// top ::= definition | external | expression | ';'
1191static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001192 while (true) {
Nick Lewycky109af622009-04-12 20:47:23 +00001193 fprintf(stderr, "ready> ");
1194 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001195 case tok_eof:
1196 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001197 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001198 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001199 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001200 case tok_def:
1201 HandleDefinition();
1202 break;
1203 case tok_extern:
1204 HandleExtern();
1205 break;
1206 default:
1207 HandleTopLevelExpression();
1208 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001209 }
1210 }
1211}
1212
Nick Lewycky109af622009-04-12 20:47:23 +00001213//===----------------------------------------------------------------------===//
1214// "Library" functions that can be "extern'd" from user code.
1215//===----------------------------------------------------------------------===//
1216
Nico Weber712e8d22018-04-29 00:45:03 +00001217#ifdef _WIN32
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001218#define DLLEXPORT __declspec(dllexport)
1219#else
1220#define DLLEXPORT
1221#endif
1222
Nick Lewycky109af622009-04-12 20:47:23 +00001223/// putchard - putchar that takes a double and returns 0.
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001224extern "C" DLLEXPORT double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001225 fputc((char)X, stderr);
Nick Lewycky109af622009-04-12 20:47:23 +00001226 return 0;
1227}
1228
1229/// printd - printf that takes a double prints it as "%f\n", returning 0.
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001230extern "C" DLLEXPORT double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001231 fprintf(stderr, "%f\n", X);
Nick Lewycky109af622009-04-12 20:47:23 +00001232 return 0;
1233}
1234
1235//===----------------------------------------------------------------------===//
1236// Main driver code.
1237//===----------------------------------------------------------------------===//
1238
1239int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001240 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001241 InitializeNativeTargetAsmPrinter();
1242 InitializeNativeTargetAsmParser();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001243
Nick Lewycky109af622009-04-12 20:47:23 +00001244 // Install standard binary operators.
1245 // 1 is lowest precedence.
1246 BinopPrecedence['='] = 2;
1247 BinopPrecedence['<'] = 10;
1248 BinopPrecedence['+'] = 20;
1249 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001250 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001251
1252 // Prime the first token.
1253 fprintf(stderr, "ready> ");
1254 getNextToken();
1255
Lang Hames2d789c32015-08-26 03:07:41 +00001256 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
Nick Lewycky109af622009-04-12 20:47:23 +00001257
Lang Hames2d789c32015-08-26 03:07:41 +00001258 InitializeModuleAndPassManager();
Reid Klecknerab770042009-08-26 20:58:25 +00001259
1260 // Run the main "interpreter loop" now.
1261 MainLoop();
1262
Nick Lewycky109af622009-04-12 20:47:23 +00001263 return 0;
1264}