blob: 3ed98fcfdb5cd31b829315ebefad76bf1fc652ef [file] [log] [blame]
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001#include "llvm/ADT/APFloat.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +00002#include "llvm/ADT/Optional.h"
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00003#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +00004#include "llvm/IR/BasicBlock.h"
5#include "llvm/IR/Constants.h"
6#include "llvm/IR/DerivedTypes.h"
7#include "llvm/IR/Function.h"
8#include "llvm/IR/Instructions.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00009#include "llvm/IR/IRBuilder.h"
10#include "llvm/IR/LLVMContext.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000011#include "llvm/IR/LegacyPassManager.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000012#include "llvm/IR/Module.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000013#include "llvm/IR/Type.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000014#include "llvm/IR/Verifier.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000015#include "llvm/Support/FileSystem.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +000016#include "llvm/Support/Host.h"
17#include "llvm/Support/raw_ostream.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000018#include "llvm/Support/TargetRegistry.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000019#include "llvm/Support/TargetSelect.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000020#include "llvm/Target/TargetMachine.h"
Wilfred Hughes945f43e2016-07-02 17:01:59 +000021#include "llvm/Target/TargetOptions.h"
Eugene Zelenkoae7ac952016-11-18 21:57:58 +000022#include <algorithm>
23#include <cassert>
Eric Christopher05917fa2014-12-08 18:00:47 +000024#include <cctype>
25#include <cstdio>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000026#include <cstdlib>
Eric Christopher05917fa2014-12-08 18:00:47 +000027#include <map>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000028#include <memory>
Eric Christopher05917fa2014-12-08 18:00:47 +000029#include <string>
Eugene Zelenkoae7ac952016-11-18 21:57:58 +000030#include <system_error>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000031#include <utility>
Eric Christopher05917fa2014-12-08 18:00:47 +000032#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000033
Eric Christopher05917fa2014-12-08 18:00:47 +000034using namespace llvm;
Wilfred Hughes945f43e2016-07-02 17:01:59 +000035using namespace llvm::sys;
Eric Christopher05917fa2014-12-08 18:00:47 +000036
37//===----------------------------------------------------------------------===//
38// Lexer
39//===----------------------------------------------------------------------===//
40
41// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
42// of these for known things.
43enum Token {
44 tok_eof = -1,
45
46 // commands
47 tok_def = -2,
48 tok_extern = -3,
49
50 // primary
51 tok_identifier = -4,
52 tok_number = -5,
53
54 // control
55 tok_if = -6,
56 tok_then = -7,
57 tok_else = -8,
58 tok_for = -9,
59 tok_in = -10,
60
61 // operators
62 tok_binary = -11,
63 tok_unary = -12,
64
65 // var definition
66 tok_var = -13
67};
68
Lang Hames2d789c32015-08-26 03:07:41 +000069static std::string IdentifierStr; // Filled in if tok_identifier
70static double NumVal; // Filled in if tok_number
71
Eric Christopher05917fa2014-12-08 18:00:47 +000072/// gettok - Return the next token from standard input.
73static int gettok() {
74 static int LastChar = ' ';
75
76 // Skip any whitespace.
77 while (isspace(LastChar))
Wilfred Hughes945f43e2016-07-02 17:01:59 +000078 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +000079
80 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
81 IdentifierStr = LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +000082 while (isalnum((LastChar = getchar())))
Eric Christopher05917fa2014-12-08 18:00:47 +000083 IdentifierStr += LastChar;
84
85 if (IdentifierStr == "def")
86 return tok_def;
87 if (IdentifierStr == "extern")
88 return tok_extern;
89 if (IdentifierStr == "if")
90 return tok_if;
91 if (IdentifierStr == "then")
92 return tok_then;
93 if (IdentifierStr == "else")
94 return tok_else;
95 if (IdentifierStr == "for")
96 return tok_for;
97 if (IdentifierStr == "in")
98 return tok_in;
99 if (IdentifierStr == "binary")
100 return tok_binary;
101 if (IdentifierStr == "unary")
102 return tok_unary;
103 if (IdentifierStr == "var")
104 return tok_var;
105 return tok_identifier;
106 }
107
108 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
109 std::string NumStr;
110 do {
111 NumStr += LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000112 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000113 } while (isdigit(LastChar) || LastChar == '.');
114
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000115 NumVal = strtod(NumStr.c_str(), nullptr);
Eric Christopher05917fa2014-12-08 18:00:47 +0000116 return tok_number;
117 }
118
119 if (LastChar == '#') {
120 // Comment until end of line.
121 do
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000122 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000123 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
124
125 if (LastChar != EOF)
126 return gettok();
127 }
128
129 // Check for end of file. Don't eat the EOF.
130 if (LastChar == EOF)
131 return tok_eof;
132
133 // Otherwise, just return the character as its ascii value.
134 int ThisChar = LastChar;
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000135 LastChar = getchar();
Eric Christopher05917fa2014-12-08 18:00:47 +0000136 return ThisChar;
137}
138
139//===----------------------------------------------------------------------===//
140// Abstract Syntax Tree (aka Parse Tree)
141//===----------------------------------------------------------------------===//
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000142
Eric Christopher05917fa2014-12-08 18:00:47 +0000143namespace {
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000144
Eric Christopher05917fa2014-12-08 18:00:47 +0000145/// ExprAST - Base class for all expression nodes.
146class ExprAST {
Eric Christopher05917fa2014-12-08 18:00:47 +0000147public:
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000148 virtual ~ExprAST() = default;
149
Lang Hames2d789c32015-08-26 03:07:41 +0000150 virtual Value *codegen() = 0;
Eric Christopher05917fa2014-12-08 18:00:47 +0000151};
152
153/// NumberExprAST - Expression class for numeric literals like "1.0".
154class NumberExprAST : public ExprAST {
155 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000156
Eric Christopher05917fa2014-12-08 18:00:47 +0000157public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000158 NumberExprAST(double Val) : Val(Val) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000159
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000160 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000161};
162
163/// VariableExprAST - Expression class for referencing a variable, like "a".
164class VariableExprAST : public ExprAST {
165 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000166
Eric Christopher05917fa2014-12-08 18:00:47 +0000167public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000168 VariableExprAST(const std::string &Name) : Name(Name) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000169
Lang Hames2d789c32015-08-26 03:07:41 +0000170 Value *codegen() override;
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000171 const std::string &getName() const { return Name; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000172};
173
174/// UnaryExprAST - Expression class for a unary operator.
175class UnaryExprAST : public ExprAST {
176 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000177 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000178
Eric Christopher05917fa2014-12-08 18:00:47 +0000179public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000180 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
181 : Opcode(Opcode), Operand(std::move(Operand)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000182
Lang Hames2d789c32015-08-26 03:07:41 +0000183 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000184};
185
186/// BinaryExprAST - Expression class for a binary operator.
187class BinaryExprAST : public ExprAST {
188 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000189 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000190
Eric Christopher05917fa2014-12-08 18:00:47 +0000191public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000192 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
Lang Hames09bf4c12015-08-18 18:11:06 +0000193 std::unique_ptr<ExprAST> RHS)
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000194 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000195
Lang Hames2d789c32015-08-26 03:07:41 +0000196 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000197};
198
199/// CallExprAST - Expression class for function calls.
200class CallExprAST : public ExprAST {
201 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000202 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000203
Eric Christopher05917fa2014-12-08 18:00:47 +0000204public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000205 CallExprAST(const std::string &Callee,
Lang Hames09bf4c12015-08-18 18:11:06 +0000206 std::vector<std::unique_ptr<ExprAST>> Args)
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000207 : Callee(Callee), Args(std::move(Args)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000208
Lang Hames2d789c32015-08-26 03:07:41 +0000209 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000210};
211
212/// IfExprAST - Expression class for if/then/else.
213class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000214 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000215
Eric Christopher05917fa2014-12-08 18:00:47 +0000216public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000217 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
218 std::unique_ptr<ExprAST> Else)
219 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000220
Lang Hames2d789c32015-08-26 03:07:41 +0000221 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000222};
223
224/// ForExprAST - Expression class for for/in.
225class ForExprAST : public ExprAST {
226 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000227 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000228
Eric Christopher05917fa2014-12-08 18:00:47 +0000229public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000230 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
231 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
232 std::unique_ptr<ExprAST> Body)
233 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
234 Step(std::move(Step)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000235
Lang Hames2d789c32015-08-26 03:07:41 +0000236 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000237};
238
239/// VarExprAST - Expression class for var/in
240class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000241 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
242 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000243
Eric Christopher05917fa2014-12-08 18:00:47 +0000244public:
Lang Hames59b0da82015-08-19 18:15:58 +0000245 VarExprAST(
246 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
247 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000248 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000249
Lang Hames2d789c32015-08-26 03:07:41 +0000250 Value *codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000251};
252
253/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000254/// which captures its name, and its argument names (thus implicitly the number
255/// of arguments the function takes), as well as if it is an operator.
Eric Christopher05917fa2014-12-08 18:00:47 +0000256class PrototypeAST {
257 std::string Name;
258 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000259 bool IsOperator;
Eric Christopher05917fa2014-12-08 18:00:47 +0000260 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000261
Eric Christopher05917fa2014-12-08 18:00:47 +0000262public:
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000263 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
264 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000265 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000266 Precedence(Prec) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000267
Lang Hames2d789c32015-08-26 03:07:41 +0000268 Function *codegen();
269 const std::string &getName() const { return Name; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000270
Lang Hames09bf4c12015-08-18 18:11:06 +0000271 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
272 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000273
274 char getOperatorName() const {
275 assert(isUnaryOp() || isBinaryOp());
276 return Name[Name.size() - 1];
277 }
278
279 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000280};
281
282/// FunctionAST - This class represents a function definition itself.
283class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000284 std::unique_ptr<PrototypeAST> Proto;
285 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000286
Eric Christopher05917fa2014-12-08 18:00:47 +0000287public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000288 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
289 std::unique_ptr<ExprAST> Body)
290 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000291
Lang Hames2d789c32015-08-26 03:07:41 +0000292 Function *codegen();
Eric Christopher05917fa2014-12-08 18:00:47 +0000293};
Eugene Zelenkoae7ac952016-11-18 21:57:58 +0000294
Eric Christopher05917fa2014-12-08 18:00:47 +0000295} // end anonymous namespace
296
297//===----------------------------------------------------------------------===//
298// Parser
299//===----------------------------------------------------------------------===//
300
301/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
302/// token the parser is looking at. getNextToken reads another token from the
303/// lexer and updates CurTok with its results.
304static int CurTok;
305static int getNextToken() { return CurTok = gettok(); }
306
307/// BinopPrecedence - This holds the precedence for each binary operator that is
308/// defined.
309static std::map<char, int> BinopPrecedence;
310
311/// GetTokPrecedence - Get the precedence of the pending binary operator token.
312static int GetTokPrecedence() {
313 if (!isascii(CurTok))
314 return -1;
315
316 // Make sure it's a declared binop.
317 int TokPrec = BinopPrecedence[CurTok];
318 if (TokPrec <= 0)
319 return -1;
320 return TokPrec;
321}
322
Lang Hamesf9878c52016-03-25 17:33:32 +0000323/// LogError* - These are little helper functions for error handling.
324std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000325 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000326 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000327}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000328
Lang Hamesf9878c52016-03-25 17:33:32 +0000329std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
330 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000331 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000332}
Eric Christopher05917fa2014-12-08 18:00:47 +0000333
Lang Hames09bf4c12015-08-18 18:11:06 +0000334static std::unique_ptr<ExprAST> ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000335
Eric Christopher05917fa2014-12-08 18:00:47 +0000336/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000337static std::unique_ptr<ExprAST> ParseNumberExpr() {
338 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Eric Christopher05917fa2014-12-08 18:00:47 +0000339 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000340 return std::move(Result);
Eric Christopher05917fa2014-12-08 18:00:47 +0000341}
342
343/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000344static std::unique_ptr<ExprAST> ParseParenExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000345 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000346 auto V = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000347 if (!V)
Lang Hames09bf4c12015-08-18 18:11:06 +0000348 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000349
350 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000351 return LogError("expected ')'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000352 getNextToken(); // eat ).
353 return V;
354}
355
Lang Hames59b0da82015-08-19 18:15:58 +0000356/// identifierexpr
357/// ::= identifier
358/// ::= identifier '(' expression* ')'
359static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
360 std::string IdName = IdentifierStr;
361
Lang Hames59b0da82015-08-19 18:15:58 +0000362 getNextToken(); // eat identifier.
363
364 if (CurTok != '(') // Simple variable ref.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000365 return llvm::make_unique<VariableExprAST>(IdName);
Lang Hames59b0da82015-08-19 18:15:58 +0000366
367 // Call.
368 getNextToken(); // eat (
369 std::vector<std::unique_ptr<ExprAST>> Args;
370 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000371 while (true) {
Lang Hames59b0da82015-08-19 18:15:58 +0000372 if (auto Arg = ParseExpression())
373 Args.push_back(std::move(Arg));
374 else
375 return nullptr;
376
377 if (CurTok == ')')
378 break;
379
380 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000381 return LogError("Expected ')' or ',' in argument list");
Lang Hames59b0da82015-08-19 18:15:58 +0000382 getNextToken();
383 }
384 }
385
386 // Eat the ')'.
387 getNextToken();
388
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000389 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Lang Hames59b0da82015-08-19 18:15:58 +0000390}
391
Eric Christopher05917fa2014-12-08 18:00:47 +0000392/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000393static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000394 getNextToken(); // eat the if.
395
396 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000397 auto Cond = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000398 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000399 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000400
401 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000402 return LogError("expected then");
Eric Christopher05917fa2014-12-08 18:00:47 +0000403 getNextToken(); // eat the then
404
Lang Hames09bf4c12015-08-18 18:11:06 +0000405 auto Then = ParseExpression();
406 if (!Then)
407 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000408
409 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000410 return LogError("expected else");
Eric Christopher05917fa2014-12-08 18:00:47 +0000411
412 getNextToken();
413
Lang Hames09bf4c12015-08-18 18:11:06 +0000414 auto Else = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000415 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000416 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000417
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000418 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
Lang Hames09bf4c12015-08-18 18:11:06 +0000419 std::move(Else));
Eric Christopher05917fa2014-12-08 18:00:47 +0000420}
421
422/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000423static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000424 getNextToken(); // eat the for.
425
426 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000427 return LogError("expected identifier after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000428
429 std::string IdName = IdentifierStr;
430 getNextToken(); // eat identifier.
431
432 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000433 return LogError("expected '=' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000434 getNextToken(); // eat '='.
435
Lang Hames09bf4c12015-08-18 18:11:06 +0000436 auto Start = ParseExpression();
437 if (!Start)
438 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000439 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000440 return LogError("expected ',' after for start value");
Eric Christopher05917fa2014-12-08 18:00:47 +0000441 getNextToken();
442
Lang Hames09bf4c12015-08-18 18:11:06 +0000443 auto End = ParseExpression();
444 if (!End)
445 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000446
447 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000448 std::unique_ptr<ExprAST> Step;
Eric Christopher05917fa2014-12-08 18:00:47 +0000449 if (CurTok == ',') {
450 getNextToken();
451 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000452 if (!Step)
453 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000454 }
455
456 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000457 return LogError("expected 'in' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000458 getNextToken(); // eat 'in'.
459
Lang Hames09bf4c12015-08-18 18:11:06 +0000460 auto Body = ParseExpression();
461 if (!Body)
462 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000463
Lang Hames09bf4c12015-08-18 18:11:06 +0000464 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
465 std::move(Step), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000466}
467
468/// varexpr ::= 'var' identifier ('=' expression)?
469// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000470static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000471 getNextToken(); // eat the var.
472
Lang Hames09bf4c12015-08-18 18:11:06 +0000473 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Eric Christopher05917fa2014-12-08 18:00:47 +0000474
475 // At least one variable name is required.
476 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000477 return LogError("expected identifier after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000478
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000479 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000480 std::string Name = IdentifierStr;
481 getNextToken(); // eat identifier.
482
483 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000484 std::unique_ptr<ExprAST> Init = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000485 if (CurTok == '=') {
486 getNextToken(); // eat the '='.
487
488 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000489 if (!Init)
490 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000491 }
492
Lang Hames09bf4c12015-08-18 18:11:06 +0000493 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopher05917fa2014-12-08 18:00:47 +0000494
495 // End of var list, exit loop.
496 if (CurTok != ',')
497 break;
498 getNextToken(); // eat the ','.
499
500 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000501 return LogError("expected identifier list after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000502 }
503
504 // At this point, we have to have 'in'.
505 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000506 return LogError("expected 'in' keyword after 'var'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000507 getNextToken(); // eat 'in'.
508
Lang Hames09bf4c12015-08-18 18:11:06 +0000509 auto Body = ParseExpression();
510 if (!Body)
511 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000512
Lang Hames09bf4c12015-08-18 18:11:06 +0000513 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000514}
515
516/// primary
517/// ::= identifierexpr
518/// ::= numberexpr
519/// ::= parenexpr
520/// ::= ifexpr
521/// ::= forexpr
522/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000523static std::unique_ptr<ExprAST> ParsePrimary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000524 switch (CurTok) {
525 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000526 return LogError("unknown token when expecting an expression");
Eric Christopher05917fa2014-12-08 18:00:47 +0000527 case tok_identifier:
528 return ParseIdentifierExpr();
529 case tok_number:
530 return ParseNumberExpr();
531 case '(':
532 return ParseParenExpr();
533 case tok_if:
534 return ParseIfExpr();
535 case tok_for:
536 return ParseForExpr();
537 case tok_var:
538 return ParseVarExpr();
539 }
540}
541
542/// unary
543/// ::= primary
544/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000545static std::unique_ptr<ExprAST> ParseUnary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000546 // If the current token is not an operator, it must be a primary expr.
547 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
548 return ParsePrimary();
549
550 // If this is a unary operator, read it.
551 int Opc = CurTok;
552 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000553 if (auto Operand = ParseUnary())
554 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
555 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000556}
557
558/// binoprhs
559/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000560static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
561 std::unique_ptr<ExprAST> LHS) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000562 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000563 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000564 int TokPrec = GetTokPrecedence();
565
566 // If this is a binop that binds at least as tightly as the current binop,
567 // consume it, otherwise we are done.
568 if (TokPrec < ExprPrec)
569 return LHS;
570
571 // Okay, we know this is a binop.
572 int BinOp = CurTok;
Eric Christopher05917fa2014-12-08 18:00:47 +0000573 getNextToken(); // eat binop
574
575 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000576 auto RHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000577 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000578 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000579
580 // If BinOp binds less tightly with RHS than the operator after RHS, let
581 // the pending operator take RHS as its LHS.
582 int NextPrec = GetTokPrecedence();
583 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000584 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
585 if (!RHS)
586 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000587 }
588
589 // Merge LHS/RHS.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000590 LHS =
591 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000592 }
593}
594
595/// expression
596/// ::= unary binoprhs
597///
Lang Hames09bf4c12015-08-18 18:11:06 +0000598static std::unique_ptr<ExprAST> ParseExpression() {
599 auto LHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000600 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000601 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000602
Lang Hames09bf4c12015-08-18 18:11:06 +0000603 return ParseBinOpRHS(0, std::move(LHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000604}
605
606/// prototype
607/// ::= id '(' id* ')'
608/// ::= binary LETTER number? (id, id)
609/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000610static std::unique_ptr<PrototypeAST> ParsePrototype() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000611 std::string FnName;
612
Eric Christopher05917fa2014-12-08 18:00:47 +0000613 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
614 unsigned BinaryPrecedence = 30;
615
616 switch (CurTok) {
617 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000618 return LogErrorP("Expected function name in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000619 case tok_identifier:
620 FnName = IdentifierStr;
621 Kind = 0;
622 getNextToken();
623 break;
624 case tok_unary:
625 getNextToken();
626 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000627 return LogErrorP("Expected unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000628 FnName = "unary";
629 FnName += (char)CurTok;
630 Kind = 1;
631 getNextToken();
632 break;
633 case tok_binary:
634 getNextToken();
635 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000636 return LogErrorP("Expected binary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000637 FnName = "binary";
638 FnName += (char)CurTok;
639 Kind = 2;
640 getNextToken();
641
642 // Read the precedence if present.
643 if (CurTok == tok_number) {
644 if (NumVal < 1 || NumVal > 100)
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000645 return LogErrorP("Invalid precedence: must be 1..100");
Eric Christopher05917fa2014-12-08 18:00:47 +0000646 BinaryPrecedence = (unsigned)NumVal;
647 getNextToken();
648 }
649 break;
650 }
651
652 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000653 return LogErrorP("Expected '(' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000654
655 std::vector<std::string> ArgNames;
656 while (getNextToken() == tok_identifier)
657 ArgNames.push_back(IdentifierStr);
658 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000659 return LogErrorP("Expected ')' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000660
661 // success.
662 getNextToken(); // eat ')'.
663
664 // Verify right number of names for operator.
665 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000666 return LogErrorP("Invalid number of operands for operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000667
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000668 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
Lang Hames09bf4c12015-08-18 18:11:06 +0000669 BinaryPrecedence);
Eric Christopher05917fa2014-12-08 18:00:47 +0000670}
671
672/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000673static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000674 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000675 auto Proto = ParsePrototype();
676 if (!Proto)
677 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000678
Lang Hames09bf4c12015-08-18 18:11:06 +0000679 if (auto E = ParseExpression())
680 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
681 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000682}
683
684/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000685static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000686 if (auto E = ParseExpression()) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000687 // Make an anonymous proto.
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000688 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
Lang Hames59b0da82015-08-19 18:15:58 +0000689 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000690 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Eric Christopher05917fa2014-12-08 18:00:47 +0000691 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000692 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000693}
694
695/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000696static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000697 getNextToken(); // eat extern.
698 return ParsePrototype();
699}
700
701//===----------------------------------------------------------------------===//
Eric Christopher05917fa2014-12-08 18:00:47 +0000702// Code Generation
703//===----------------------------------------------------------------------===//
704
Wilfred Hughes945f43e2016-07-02 17:01:59 +0000705static LLVMContext TheContext;
706static IRBuilder<> Builder(TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +0000707static std::unique_ptr<Module> TheModule;
Eric Christopher05917fa2014-12-08 18:00:47 +0000708static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000709static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Eric Christopher05917fa2014-12-08 18:00:47 +0000710
Lang Hamesf9878c52016-03-25 17:33:32 +0000711Value *LogErrorV(const char *Str) {
712 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000713 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000714}
715
Lang Hames2d789c32015-08-26 03:07:41 +0000716Function *getFunction(std::string Name) {
717 // First, see if the function has already been added to the current module.
718 if (auto *F = TheModule->getFunction(Name))
719 return F;
720
721 // If not, check whether we can codegen the declaration from some existing
722 // prototype.
723 auto FI = FunctionProtos.find(Name);
724 if (FI != FunctionProtos.end())
725 return FI->second->codegen();
726
727 // If no existing prototype exists, return null.
728 return nullptr;
729}
730
Eric Christopher05917fa2014-12-08 18:00:47 +0000731/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
732/// the function. This is used for mutable variables etc.
733static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
734 const std::string &VarName) {
735 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
736 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000737 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Eric Christopher05917fa2014-12-08 18:00:47 +0000738}
739
Lang Hames2d789c32015-08-26 03:07:41 +0000740Value *NumberExprAST::codegen() {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000741 return ConstantFP::get(TheContext, APFloat(Val));
Eric Christopher05917fa2014-12-08 18:00:47 +0000742}
743
Lang Hames2d789c32015-08-26 03:07:41 +0000744Value *VariableExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000745 // Look this variable up in the function.
746 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000747 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000748 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000749
Eric Christopher05917fa2014-12-08 18:00:47 +0000750 // Load the value.
751 return Builder.CreateLoad(V, Name.c_str());
752}
753
Lang Hames2d789c32015-08-26 03:07:41 +0000754Value *UnaryExprAST::codegen() {
755 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000756 if (!OperandV)
757 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000758
Lang Hames2d789c32015-08-26 03:07:41 +0000759 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000760 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000761 return LogErrorV("Unknown unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000762
Eric Christopher05917fa2014-12-08 18:00:47 +0000763 return Builder.CreateCall(F, OperandV, "unop");
764}
765
Lang Hames2d789c32015-08-26 03:07:41 +0000766Value *BinaryExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000767 // Special case '=' because we don't want to emit the LHS as an expression.
768 if (Op == '=') {
769 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000770 // This assume we're building without RTTI because LLVM builds that way by
771 // default. If you build LLVM with RTTI this can be changed to a
772 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000773 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Eric Christopher05917fa2014-12-08 18:00:47 +0000774 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000775 return LogErrorV("destination of '=' must be a variable");
Eric Christopher05917fa2014-12-08 18:00:47 +0000776 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000777 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000778 if (!Val)
779 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000780
781 // Look up the name.
782 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000783 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000784 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000785
786 Builder.CreateStore(Val, Variable);
787 return Val;
788 }
789
Lang Hames2d789c32015-08-26 03:07:41 +0000790 Value *L = LHS->codegen();
791 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000792 if (!L || !R)
793 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000794
795 switch (Op) {
796 case '+':
797 return Builder.CreateFAdd(L, R, "addtmp");
798 case '-':
799 return Builder.CreateFSub(L, R, "subtmp");
800 case '*':
801 return Builder.CreateFMul(L, R, "multmp");
802 case '<':
803 L = Builder.CreateFCmpULT(L, R, "cmptmp");
804 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000805 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopher05917fa2014-12-08 18:00:47 +0000806 default:
807 break;
808 }
809
810 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
811 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000812 Function *F = getFunction(std::string("binary") + Op);
Eric Christopher05917fa2014-12-08 18:00:47 +0000813 assert(F && "binary operator not found!");
814
Lang Hames59b0da82015-08-19 18:15:58 +0000815 Value *Ops[] = {L, R};
Eric Christopher05917fa2014-12-08 18:00:47 +0000816 return Builder.CreateCall(F, Ops, "binop");
817}
818
Lang Hames2d789c32015-08-26 03:07:41 +0000819Value *CallExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000820 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000821 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000822 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +0000823 return LogErrorV("Unknown function referenced");
Eric Christopher05917fa2014-12-08 18:00:47 +0000824
825 // If argument mismatch error.
826 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +0000827 return LogErrorV("Incorrect # arguments passed");
Eric Christopher05917fa2014-12-08 18:00:47 +0000828
829 std::vector<Value *> ArgsV;
830 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000831 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000832 if (!ArgsV.back())
833 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000834 }
835
836 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
837}
838
Lang Hames2d789c32015-08-26 03:07:41 +0000839Value *IfExprAST::codegen() {
Lang Hames2d789c32015-08-26 03:07:41 +0000840 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000841 if (!CondV)
842 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000843
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000844 // Convert condition to a bool by comparing non-equal to 0.0.
Eric Christopher05917fa2014-12-08 18:00:47 +0000845 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000846 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopher05917fa2014-12-08 18:00:47 +0000847
848 Function *TheFunction = Builder.GetInsertBlock()->getParent();
849
850 // Create blocks for the then and else cases. Insert the 'then' block at the
851 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000852 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
853 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
854 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopher05917fa2014-12-08 18:00:47 +0000855
856 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
857
858 // Emit then value.
859 Builder.SetInsertPoint(ThenBB);
860
Lang Hames2d789c32015-08-26 03:07:41 +0000861 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000862 if (!ThenV)
863 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000864
865 Builder.CreateBr(MergeBB);
866 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
867 ThenBB = Builder.GetInsertBlock();
868
869 // Emit else block.
870 TheFunction->getBasicBlockList().push_back(ElseBB);
871 Builder.SetInsertPoint(ElseBB);
872
Lang Hames2d789c32015-08-26 03:07:41 +0000873 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000874 if (!ElseV)
875 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000876
877 Builder.CreateBr(MergeBB);
878 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
879 ElseBB = Builder.GetInsertBlock();
880
881 // Emit merge block.
882 TheFunction->getBasicBlockList().push_back(MergeBB);
883 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000884 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopher05917fa2014-12-08 18:00:47 +0000885
886 PN->addIncoming(ThenV, ThenBB);
887 PN->addIncoming(ElseV, ElseBB);
888 return PN;
889}
890
Lang Hames59b0da82015-08-19 18:15:58 +0000891// Output for-loop as:
892// var = alloca double
893// ...
894// start = startexpr
895// store start -> var
896// goto loop
897// loop:
898// ...
899// bodyexpr
900// ...
901// loopend:
902// step = stepexpr
903// endcond = endexpr
904//
905// curvar = load var
906// nextvar = curvar + step
907// store nextvar -> var
908// br endcond, loop, endloop
909// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +0000910Value *ForExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000911 Function *TheFunction = Builder.GetInsertBlock()->getParent();
912
913 // Create an alloca for the variable in the entry block.
914 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
915
Eric Christopher05917fa2014-12-08 18:00:47 +0000916 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +0000917 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000918 if (!StartVal)
919 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000920
921 // Store the value into the alloca.
922 Builder.CreateStore(StartVal, Alloca);
923
924 // Make the new basic block for the loop header, inserting after current
925 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000926 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +0000927
928 // Insert an explicit fall through from the current block to the LoopBB.
929 Builder.CreateBr(LoopBB);
930
931 // Start insertion in LoopBB.
932 Builder.SetInsertPoint(LoopBB);
933
934 // Within the loop, the variable is defined equal to the PHI node. If it
935 // shadows an existing variable, we have to restore it, so save it now.
936 AllocaInst *OldVal = NamedValues[VarName];
937 NamedValues[VarName] = Alloca;
938
939 // Emit the body of the loop. This, like any other expr, can change the
940 // current BB. Note that we ignore the value computed by the body, but don't
941 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +0000942 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +0000943 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000944
945 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000946 Value *StepVal = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000947 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +0000948 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000949 if (!StepVal)
950 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000951 } else {
952 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000953 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Eric Christopher05917fa2014-12-08 18:00:47 +0000954 }
955
956 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +0000957 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000958 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000959 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000960
961 // Reload, increment, and restore the alloca. This handles the case where
962 // the body of the loop mutates the variable.
963 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
964 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
965 Builder.CreateStore(NextVar, Alloca);
966
Mehdi Aminibb6805d2017-02-11 21:26:52 +0000967 // Convert condition to a bool by comparing non-equal to 0.0.
Eric Christopher05917fa2014-12-08 18:00:47 +0000968 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +0000969 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopher05917fa2014-12-08 18:00:47 +0000970
971 // Create the "after loop" block and insert it.
972 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +0000973 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +0000974
975 // Insert the conditional branch into the end of LoopEndBB.
976 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
977
978 // Any new code will be inserted in AfterBB.
979 Builder.SetInsertPoint(AfterBB);
980
981 // Restore the unshadowed variable.
982 if (OldVal)
983 NamedValues[VarName] = OldVal;
984 else
985 NamedValues.erase(VarName);
986
987 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000988 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +0000989}
990
Lang Hames2d789c32015-08-26 03:07:41 +0000991Value *VarExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000992 std::vector<AllocaInst *> OldBindings;
993
994 Function *TheFunction = Builder.GetInsertBlock()->getParent();
995
996 // Register all variables and emit their initializer.
997 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
998 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000999 ExprAST *Init = VarNames[i].second.get();
Eric Christopher05917fa2014-12-08 18:00:47 +00001000
1001 // Emit the initializer before adding the variable to scope, this prevents
1002 // the initializer from referencing the variable itself, and permits stuff
1003 // like this:
1004 // var a = 1 in
1005 // var a = a in ... # refers to outer 'a'.
1006 Value *InitVal;
1007 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +00001008 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001009 if (!InitVal)
1010 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001011 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001012 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Eric Christopher05917fa2014-12-08 18:00:47 +00001013 }
1014
1015 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1016 Builder.CreateStore(InitVal, Alloca);
1017
1018 // Remember the old variable binding so that we can restore the binding when
1019 // we unrecurse.
1020 OldBindings.push_back(NamedValues[VarName]);
1021
1022 // Remember this binding.
1023 NamedValues[VarName] = Alloca;
1024 }
1025
Eric Christopher05917fa2014-12-08 18:00:47 +00001026 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001027 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001028 if (!BodyVal)
1029 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001030
1031 // Pop all our variables from scope.
1032 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1033 NamedValues[VarNames[i].first] = OldBindings[i];
1034
1035 // Return the body computation.
1036 return BodyVal;
1037}
1038
Lang Hames2d789c32015-08-26 03:07:41 +00001039Function *PrototypeAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001040 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001041 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +00001042 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001043 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopher05917fa2014-12-08 18:00:47 +00001044
1045 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001046 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopher05917fa2014-12-08 18:00:47 +00001047
1048 // Set names for all arguments.
1049 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001050 for (auto &Arg : F->args())
1051 Arg.setName(Args[Idx++]);
1052
1053 return F;
1054}
1055
1056Function *FunctionAST::codegen() {
1057 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1058 // reference to it for use below.
1059 auto &P = *Proto;
1060 FunctionProtos[Proto->getName()] = std::move(Proto);
1061 Function *TheFunction = getFunction(P.getName());
1062 if (!TheFunction)
1063 return nullptr;
1064
1065 // If this is an operator, install it.
1066 if (P.isBinaryOp())
1067 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1068
1069 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001070 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Lang Hames2d789c32015-08-26 03:07:41 +00001071 Builder.SetInsertPoint(BB);
Eric Christopher05917fa2014-12-08 18:00:47 +00001072
Lang Hames2d789c32015-08-26 03:07:41 +00001073 // Record the function arguments in the NamedValues map.
1074 NamedValues.clear();
Lang Hames2d789c32015-08-26 03:07:41 +00001075 for (auto &Arg : TheFunction->args()) {
1076 // Create an alloca for this variable.
1077 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Eric Christopher05917fa2014-12-08 18:00:47 +00001078
Lang Hames2d789c32015-08-26 03:07:41 +00001079 // Store the initial value into the alloca.
1080 Builder.CreateStore(&Arg, Alloca);
1081
1082 // Add arguments to variable symbol table.
1083 NamedValues[Arg.getName()] = Alloca;
1084 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001085
Lang Hames2d789c32015-08-26 03:07:41 +00001086 if (Value *RetVal = Body->codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001087 // Finish off the function.
1088 Builder.CreateRet(RetVal);
1089
Eric Christopher05917fa2014-12-08 18:00:47 +00001090 // Validate the generated code, checking for consistency.
1091 verifyFunction(*TheFunction);
1092
Eric Christopher05917fa2014-12-08 18:00:47 +00001093 return TheFunction;
1094 }
1095
1096 // Error reading body, remove function.
1097 TheFunction->eraseFromParent();
1098
Lang Hames2d789c32015-08-26 03:07:41 +00001099 if (P.isBinaryOp())
Peter Szecsi5305d392017-05-07 11:00:01 +00001100 BinopPrecedence.erase(P.getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001101 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001102}
1103
1104//===----------------------------------------------------------------------===//
1105// Top-Level parsing and JIT Driver
1106//===----------------------------------------------------------------------===//
1107
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001108static void InitializeModuleAndPassManager() {
Lang Hames2d789c32015-08-26 03:07:41 +00001109 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001110 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001111}
Eric Christopher05917fa2014-12-08 18:00:47 +00001112
1113static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001114 if (auto FnAST = ParseDefinition()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001115 if (auto *FnIR = FnAST->codegen()) {
1116 fprintf(stderr, "Read function definition:");
Matthias Braun25bcaba2017-01-28 02:47:46 +00001117 FnIR->print(errs());
1118 fprintf(stderr, "\n");
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001119 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001120 } else {
1121 // Skip token for error recovery.
1122 getNextToken();
1123 }
1124}
1125
1126static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001127 if (auto ProtoAST = ParseExtern()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001128 if (auto *FnIR = ProtoAST->codegen()) {
1129 fprintf(stderr, "Read extern: ");
Matthias Braun25bcaba2017-01-28 02:47:46 +00001130 FnIR->print(errs());
1131 fprintf(stderr, "\n");
Lang Hames2d789c32015-08-26 03:07:41 +00001132 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001133 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001134 } else {
1135 // Skip token for error recovery.
1136 getNextToken();
1137 }
1138}
1139
1140static void HandleTopLevelExpression() {
1141 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001142 if (auto FnAST = ParseTopLevelExpr()) {
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001143 FnAST->codegen();
Eric Christopher05917fa2014-12-08 18:00:47 +00001144 } else {
1145 // Skip token for error recovery.
1146 getNextToken();
1147 }
1148}
1149
1150/// top ::= definition | external | expression | ';'
1151static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001152 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001153 switch (CurTok) {
1154 case tok_eof:
1155 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001156 case ';': // ignore top-level semicolons.
Eric Christopher05917fa2014-12-08 18:00:47 +00001157 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001158 break;
Eric Christopher05917fa2014-12-08 18:00:47 +00001159 case tok_def:
1160 HandleDefinition();
1161 break;
1162 case tok_extern:
1163 HandleExtern();
1164 break;
1165 default:
1166 HandleTopLevelExpression();
1167 break;
1168 }
1169 }
1170}
1171
1172//===----------------------------------------------------------------------===//
1173// "Library" functions that can be "extern'd" from user code.
1174//===----------------------------------------------------------------------===//
1175
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001176#ifdef LLVM_ON_WIN32
1177#define DLLEXPORT __declspec(dllexport)
1178#else
1179#define DLLEXPORT
1180#endif
1181
Eric Christopher05917fa2014-12-08 18:00:47 +00001182/// putchard - putchar that takes a double and returns 0.
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001183extern "C" DLLEXPORT double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001184 fputc((char)X, stderr);
Eric Christopher05917fa2014-12-08 18:00:47 +00001185 return 0;
1186}
1187
1188/// printd - printf that takes a double prints it as "%f\n", returning 0.
Mehdi Aminibb6805d2017-02-11 21:26:52 +00001189extern "C" DLLEXPORT double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001190 fprintf(stderr, "%f\n", X);
Eric Christopher05917fa2014-12-08 18:00:47 +00001191 return 0;
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// Main driver code.
1196//===----------------------------------------------------------------------===//
1197
1198int main() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001199 // Install standard binary operators.
1200 // 1 is lowest precedence.
Eric Christopher05917fa2014-12-08 18:00:47 +00001201 BinopPrecedence['<'] = 10;
1202 BinopPrecedence['+'] = 20;
1203 BinopPrecedence['-'] = 20;
1204 BinopPrecedence['*'] = 40; // highest.
1205
1206 // Prime the first token.
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001207 fprintf(stderr, "ready> ");
Eric Christopher05917fa2014-12-08 18:00:47 +00001208 getNextToken();
1209
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001210 InitializeModuleAndPassManager();
Eric Christopher05917fa2014-12-08 18:00:47 +00001211
Eric Christopher05917fa2014-12-08 18:00:47 +00001212 // Run the main "interpreter loop" now.
1213 MainLoop();
1214
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001215 // Initialize the target registry etc.
1216 InitializeAllTargetInfos();
1217 InitializeAllTargets();
1218 InitializeAllTargetMCs();
1219 InitializeAllAsmParsers();
1220 InitializeAllAsmPrinters();
Eric Christopher05917fa2014-12-08 18:00:47 +00001221
Wilfred Hughes945f43e2016-07-02 17:01:59 +00001222 auto TargetTriple = sys::getDefaultTargetTriple();
1223 TheModule->setTargetTriple(TargetTriple);
1224
1225 std::string Error;
1226 auto Target = TargetRegistry::lookupTarget(TargetTriple, Error);
1227
1228 // Print an error and exit if we couldn't find the requested target.
1229 // This generally occurs if we've forgotten to initialise the
1230 // TargetRegistry or we have a bogus target triple.
1231 if (!Target) {
1232 errs() << Error;
1233 return 1;
1234 }
1235
1236 auto CPU = "generic";
1237 auto Features = "";
1238
1239 TargetOptions opt;
1240 auto RM = Optional<Reloc::Model>();
1241 auto TheTargetMachine =
1242 Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);
1243
1244 TheModule->setDataLayout(TheTargetMachine->createDataLayout());
1245
1246 auto Filename = "output.o";
1247 std::error_code EC;
1248 raw_fd_ostream dest(Filename, EC, sys::fs::F_None);
1249
1250 if (EC) {
1251 errs() << "Could not open file: " << EC.message();
1252 return 1;
1253 }
1254
1255 legacy::PassManager pass;
1256 auto FileType = TargetMachine::CGFT_ObjectFile;
1257
1258 if (TheTargetMachine->addPassesToEmitFile(pass, dest, FileType)) {
1259 errs() << "TheTargetMachine can't emit a file of this type";
1260 return 1;
1261 }
1262
1263 pass.run(*TheModule);
1264 dest.flush();
1265
1266 outs() << "Wrote " << Filename << "\n";
Eric Christopher05917fa2014-12-08 18:00:47 +00001267
1268 return 0;
1269}