blob: ed2d9b427ff11181e07a03991197a071350e3a07 [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00002#include "llvm/ADT/Triple.h"
3#include "llvm/Analysis/Passes.h"
4#include "llvm/ExecutionEngine/ExecutionEngine.h"
5#include "llvm/ExecutionEngine/MCJIT.h"
6#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth1f832f72015-02-13 09:14:30 +00007#include "llvm/IR/DIBuilder.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00008#include "llvm/IR/DataLayout.h"
9#include "llvm/IR/DerivedTypes.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000010#include "llvm/IR/IRBuilder.h"
11#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000012#include "llvm/IR/LegacyPassManager.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000013#include "llvm/IR/Module.h"
14#include "llvm/IR/Verifier.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000015#include "llvm/Support/Host.h"
16#include "llvm/Support/TargetSelect.h"
17#include "llvm/Transforms/Scalar.h"
18#include <cctype>
19#include <cstdio>
Chandler Carruth1f832f72015-02-13 09:14:30 +000020#include <iostream>
Eric Christopher05917fa2014-12-08 18:00:47 +000021#include <map>
22#include <string>
23#include <vector>
Eric Christopher05917fa2014-12-08 18:00:47 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27// Lexer
28//===----------------------------------------------------------------------===//
29
30// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31// of these for known things.
32enum Token {
33 tok_eof = -1,
34
35 // commands
36 tok_def = -2,
37 tok_extern = -3,
38
39 // primary
40 tok_identifier = -4,
41 tok_number = -5,
42
43 // control
44 tok_if = -6,
45 tok_then = -7,
46 tok_else = -8,
47 tok_for = -9,
48 tok_in = -10,
49
50 // operators
51 tok_binary = -11,
52 tok_unary = -12,
53
54 // var definition
55 tok_var = -13
56};
57
58std::string getTokName(int Tok) {
59 switch (Tok) {
60 case tok_eof:
61 return "eof";
62 case tok_def:
63 return "def";
64 case tok_extern:
65 return "extern";
66 case tok_identifier:
67 return "identifier";
68 case tok_number:
69 return "number";
70 case tok_if:
71 return "if";
72 case tok_then:
73 return "then";
74 case tok_else:
75 return "else";
76 case tok_for:
77 return "for";
78 case tok_in:
79 return "in";
80 case tok_binary:
81 return "binary";
82 case tok_unary:
83 return "unary";
84 case tok_var:
85 return "var";
86 }
87 return std::string(1, (char)Tok);
88}
89
90namespace {
91class PrototypeAST;
92class ExprAST;
93}
94static IRBuilder<> Builder(getGlobalContext());
95struct DebugInfo {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +000096 DICompileUnit *TheCU;
97 DIType *DblTy;
98 std::vector<DIScope *> LexicalBlocks;
99 std::map<const PrototypeAST *, DIScope *> FnScopeMap;
Eric Christopher05917fa2014-12-08 18:00:47 +0000100
101 void emitLocation(ExprAST *AST);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000102 DIType *getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000103} KSDbgInfo;
104
105static std::string IdentifierStr; // Filled in if tok_identifier
106static double NumVal; // Filled in if tok_number
107struct SourceLocation {
108 int Line;
109 int Col;
110};
111static SourceLocation CurLoc;
112static SourceLocation LexLoc = { 1, 0 };
113
114static int advance() {
115 int LastChar = getchar();
116
117 if (LastChar == '\n' || LastChar == '\r') {
118 LexLoc.Line++;
119 LexLoc.Col = 0;
120 } else
121 LexLoc.Col++;
122 return LastChar;
123}
124
125/// gettok - Return the next token from standard input.
126static int gettok() {
127 static int LastChar = ' ';
128
129 // Skip any whitespace.
130 while (isspace(LastChar))
131 LastChar = advance();
132
133 CurLoc = LexLoc;
134
135 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136 IdentifierStr = LastChar;
137 while (isalnum((LastChar = advance())))
138 IdentifierStr += LastChar;
139
140 if (IdentifierStr == "def")
141 return tok_def;
142 if (IdentifierStr == "extern")
143 return tok_extern;
144 if (IdentifierStr == "if")
145 return tok_if;
146 if (IdentifierStr == "then")
147 return tok_then;
148 if (IdentifierStr == "else")
149 return tok_else;
150 if (IdentifierStr == "for")
151 return tok_for;
152 if (IdentifierStr == "in")
153 return tok_in;
154 if (IdentifierStr == "binary")
155 return tok_binary;
156 if (IdentifierStr == "unary")
157 return tok_unary;
158 if (IdentifierStr == "var")
159 return tok_var;
160 return tok_identifier;
161 }
162
163 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
164 std::string NumStr;
165 do {
166 NumStr += LastChar;
167 LastChar = advance();
168 } while (isdigit(LastChar) || LastChar == '.');
169
170 NumVal = strtod(NumStr.c_str(), 0);
171 return tok_number;
172 }
173
174 if (LastChar == '#') {
175 // Comment until end of line.
176 do
177 LastChar = advance();
178 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
179
180 if (LastChar != EOF)
181 return gettok();
182 }
183
184 // Check for end of file. Don't eat the EOF.
185 if (LastChar == EOF)
186 return tok_eof;
187
188 // Otherwise, just return the character as its ascii value.
189 int ThisChar = LastChar;
190 LastChar = advance();
191 return ThisChar;
192}
193
194//===----------------------------------------------------------------------===//
195// Abstract Syntax Tree (aka Parse Tree)
196//===----------------------------------------------------------------------===//
197namespace {
198
199std::ostream &indent(std::ostream &O, int size) {
200 return O << std::string(size, ' ');
201}
202
203/// ExprAST - Base class for all expression nodes.
204class ExprAST {
205 SourceLocation Loc;
Eric Christopher05917fa2014-12-08 18:00:47 +0000206public:
207 int getLine() const { return Loc.Line; }
208 int getCol() const { return Loc.Col; }
209 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
210 virtual std::ostream &dump(std::ostream &out, int ind) {
211 return out << ':' << getLine() << ':' << getCol() << '\n';
212 }
213 virtual ~ExprAST() {}
214 virtual Value *Codegen() = 0;
215};
216
217/// NumberExprAST - Expression class for numeric literals like "1.0".
218class NumberExprAST : public ExprAST {
219 double Val;
Eric Christopher05917fa2014-12-08 18:00:47 +0000220public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000221 NumberExprAST(double Val) : Val(Val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000222 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000223 return ExprAST::dump(out << Val, ind);
224 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000225 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000226};
227
228/// VariableExprAST - Expression class for referencing a variable, like "a".
229class VariableExprAST : public ExprAST {
230 std::string Name;
Eric Christopher05917fa2014-12-08 18:00:47 +0000231public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000232 VariableExprAST(SourceLocation Loc, const std::string &Name)
233 : ExprAST(Loc), Name(Name) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000234 const std::string &getName() const { return Name; }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000235 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000236 return ExprAST::dump(out << Name, ind);
237 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000238 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000239};
240
241/// UnaryExprAST - Expression class for a unary operator.
242class UnaryExprAST : public ExprAST {
243 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000244 std::unique_ptr<ExprAST> Operand;
Eric Christopher05917fa2014-12-08 18:00:47 +0000245public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000246 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
247 : Opcode(Opcode), Operand(std::move(Operand)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000248 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000249 ExprAST::dump(out << "unary" << Opcode, ind);
250 Operand->dump(out, ind + 1);
251 return out;
252 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000253 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000254};
255
256/// BinaryExprAST - Expression class for a binary operator.
257class BinaryExprAST : public ExprAST {
258 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000259 std::unique_ptr<ExprAST> LHS, RHS;
Eric Christopher05917fa2014-12-08 18:00:47 +0000260public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000261 BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr<ExprAST> LHS,
262 std::unique_ptr<ExprAST> RHS)
263 : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000264 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000265 ExprAST::dump(out << "binary" << Op, ind);
266 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
267 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
268 return out;
269 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000270 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000271};
272
273/// CallExprAST - Expression class for function calls.
274class CallExprAST : public ExprAST {
275 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000276 std::vector<std::unique_ptr<ExprAST>> Args;
Eric Christopher05917fa2014-12-08 18:00:47 +0000277public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000278 CallExprAST(SourceLocation Loc, const std::string &Callee,
279 std::vector<std::unique_ptr<ExprAST>> Args)
280 : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000281 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000282 ExprAST::dump(out << "call " << Callee, ind);
Lang Hames09bf4c12015-08-18 18:11:06 +0000283 for (const auto &Arg : Args)
Eric Christopher05917fa2014-12-08 18:00:47 +0000284 Arg->dump(indent(out, ind + 1), ind + 1);
285 return out;
286 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000287 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000288};
289
290/// IfExprAST - Expression class for if/then/else.
291class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000292 std::unique_ptr<ExprAST> Cond, Then, Else;
Eric Christopher05917fa2014-12-08 18:00:47 +0000293public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000294 IfExprAST(SourceLocation Loc, std::unique_ptr<ExprAST> Cond,
295 std::unique_ptr<ExprAST> Then, std::unique_ptr<ExprAST> Else)
296 : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000297 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000298 ExprAST::dump(out << "if", ind);
299 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
300 Then->dump(indent(out, ind) << "Then:", ind + 1);
301 Else->dump(indent(out, ind) << "Else:", ind + 1);
302 return out;
303 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000304 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000305};
306
307/// ForExprAST - Expression class for for/in.
308class ForExprAST : public ExprAST {
309 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000310 std::unique_ptr<ExprAST> Start, End, Step, Body;
Eric Christopher05917fa2014-12-08 18:00:47 +0000311public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000312 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
313 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
314 std::unique_ptr<ExprAST> Body)
315 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
316 Step(std::move(Step)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000317 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000318 ExprAST::dump(out << "for", ind);
319 Start->dump(indent(out, ind) << "Cond:", ind + 1);
320 End->dump(indent(out, ind) << "End:", ind + 1);
321 Step->dump(indent(out, ind) << "Step:", ind + 1);
322 Body->dump(indent(out, ind) << "Body:", ind + 1);
323 return out;
324 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000325 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000326};
327
328/// VarExprAST - Expression class for var/in
329class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000330 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
331 std::unique_ptr<ExprAST> Body;
Eric Christopher05917fa2014-12-08 18:00:47 +0000332public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000333 VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
334 std::unique_ptr<ExprAST> Body)
335 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000336 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000337 ExprAST::dump(out << "var", ind);
338 for (const auto &NamedVar : VarNames)
339 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
340 Body->dump(indent(out, ind) << "Body:", ind + 1);
341 return out;
342 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000343 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000344};
345
346/// PrototypeAST - This class represents the "prototype" for a function,
347/// which captures its argument names as well as if it is an operator.
348class PrototypeAST {
349 std::string Name;
350 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000351 bool IsOperator;
Eric Christopher05917fa2014-12-08 18:00:47 +0000352 unsigned Precedence; // Precedence if a binary op.
353 int Line;
Eric Christopher05917fa2014-12-08 18:00:47 +0000354public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000355 PrototypeAST(SourceLocation Loc, const std::string &Name,
356 std::vector<std::string> Args, bool IsOperator = false,
357 unsigned Prec = 0)
358 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
359 Precedence(Prec), Line(Loc.Line) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000360
Lang Hames09bf4c12015-08-18 18:11:06 +0000361 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
362 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000363
364 char getOperatorName() const {
365 assert(isUnaryOp() || isBinaryOp());
366 return Name[Name.size() - 1];
367 }
368
369 unsigned getBinaryPrecedence() const { return Precedence; }
370
371 Function *Codegen();
372
373 void CreateArgumentAllocas(Function *F);
374 const std::vector<std::string> &getArgs() const { return Args; }
375};
376
377/// FunctionAST - This class represents a function definition itself.
378class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000379 std::unique_ptr<PrototypeAST> Proto;
380 std::unique_ptr<ExprAST> Body;
Eric Christopher05917fa2014-12-08 18:00:47 +0000381public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000382 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
383 std::unique_ptr<ExprAST> Body)
384 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000385
386 std::ostream &dump(std::ostream &out, int ind) {
387 indent(out, ind) << "FunctionAST\n";
388 ++ind;
389 indent(out, ind) << "Body:";
390 return Body ? Body->dump(out, ind) : out << "null\n";
391 }
392
393 Function *Codegen();
394};
395} // end anonymous namespace
396
397//===----------------------------------------------------------------------===//
398// Parser
399//===----------------------------------------------------------------------===//
400
401/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
402/// token the parser is looking at. getNextToken reads another token from the
403/// lexer and updates CurTok with its results.
404static int CurTok;
405static int getNextToken() { return CurTok = gettok(); }
406
407/// BinopPrecedence - This holds the precedence for each binary operator that is
408/// defined.
409static std::map<char, int> BinopPrecedence;
410
411/// GetTokPrecedence - Get the precedence of the pending binary operator token.
412static int GetTokPrecedence() {
413 if (!isascii(CurTok))
414 return -1;
415
416 // Make sure it's a declared binop.
417 int TokPrec = BinopPrecedence[CurTok];
418 if (TokPrec <= 0)
419 return -1;
420 return TokPrec;
421}
422
423/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000424std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000425 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000426 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000427}
Lang Hames09bf4c12015-08-18 18:11:06 +0000428std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000429 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000430 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000431}
Lang Hames09bf4c12015-08-18 18:11:06 +0000432std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000433 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000434 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000435}
436
Lang Hames09bf4c12015-08-18 18:11:06 +0000437static std::unique_ptr<ExprAST> ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000438
439/// identifierexpr
440/// ::= identifier
441/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000442 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000443 std::string IdName = IdentifierStr;
444
445 SourceLocation LitLoc = CurLoc;
446
447 getNextToken(); // eat identifier.
448
449 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000450 return llvm::make_unique<VariableExprAST>(LitLoc, IdName);
Eric Christopher05917fa2014-12-08 18:00:47 +0000451
452 // Call.
453 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000454 std::vector<std::unique_ptr<ExprAST>> Args;
Eric Christopher05917fa2014-12-08 18:00:47 +0000455 if (CurTok != ')') {
456 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000457 auto Arg = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000458 if (!Arg)
Lang Hames09bf4c12015-08-18 18:11:06 +0000459 return nullptr;
460 Args.push_back(std::move(Arg));
Eric Christopher05917fa2014-12-08 18:00:47 +0000461
462 if (CurTok == ')')
463 break;
464
465 if (CurTok != ',')
466 return Error("Expected ')' or ',' in argument list");
467 getNextToken();
468 }
469 }
470
471 // Eat the ')'.
472 getNextToken();
473
Lang Hames09bf4c12015-08-18 18:11:06 +0000474 return llvm::make_unique<CallExprAST>(LitLoc, IdName, std::move(Args));
Eric Christopher05917fa2014-12-08 18:00:47 +0000475}
476
477/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000478static std::unique_ptr<ExprAST> ParseNumberExpr() {
479 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Eric Christopher05917fa2014-12-08 18:00:47 +0000480 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000481 return std::move(Result);
Eric Christopher05917fa2014-12-08 18:00:47 +0000482}
483
484/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000485static std::unique_ptr<ExprAST> ParseParenExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000486 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000487 auto V = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000488 if (!V)
Lang Hames09bf4c12015-08-18 18:11:06 +0000489 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000490
491 if (CurTok != ')')
492 return Error("expected ')'");
493 getNextToken(); // eat ).
494 return V;
495}
496
497/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000498static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000499 SourceLocation IfLoc = CurLoc;
500
501 getNextToken(); // eat the if.
502
503 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000504 auto Cond = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000505 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000506 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000507
508 if (CurTok != tok_then)
509 return Error("expected then");
510 getNextToken(); // eat the then
511
Lang Hames09bf4c12015-08-18 18:11:06 +0000512 auto Then = ParseExpression();
513 if (!Then)
514 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000515
516 if (CurTok != tok_else)
517 return Error("expected else");
518
519 getNextToken();
520
Lang Hames09bf4c12015-08-18 18:11:06 +0000521 auto Else = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000522 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000523 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000524
Lang Hames09bf4c12015-08-18 18:11:06 +0000525 return llvm::make_unique<IfExprAST>(IfLoc, std::move(Cond), std::move(Then),
526 std::move(Else));
Eric Christopher05917fa2014-12-08 18:00:47 +0000527}
528
529/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000530static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000531 getNextToken(); // eat the for.
532
533 if (CurTok != tok_identifier)
534 return Error("expected identifier after for");
535
536 std::string IdName = IdentifierStr;
537 getNextToken(); // eat identifier.
538
539 if (CurTok != '=')
540 return Error("expected '=' after for");
541 getNextToken(); // eat '='.
542
Lang Hames09bf4c12015-08-18 18:11:06 +0000543 auto Start = ParseExpression();
544 if (!Start)
545 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000546 if (CurTok != ',')
547 return Error("expected ',' after for start value");
548 getNextToken();
549
Lang Hames09bf4c12015-08-18 18:11:06 +0000550 auto End = ParseExpression();
551 if (!End)
552 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000553
554 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 std::unique_ptr<ExprAST> Step;
Eric Christopher05917fa2014-12-08 18:00:47 +0000556 if (CurTok == ',') {
557 getNextToken();
558 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000559 if (!Step)
560 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000561 }
562
563 if (CurTok != tok_in)
564 return Error("expected 'in' after for");
565 getNextToken(); // eat 'in'.
566
Lang Hames09bf4c12015-08-18 18:11:06 +0000567 auto Body = ParseExpression();
568 if (!Body)
569 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000570
Lang Hames09bf4c12015-08-18 18:11:06 +0000571 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
572 std::move(Step), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000573}
574
575/// varexpr ::= 'var' identifier ('=' expression)?
576// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000577static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000578 getNextToken(); // eat the var.
579
Lang Hames09bf4c12015-08-18 18:11:06 +0000580 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Eric Christopher05917fa2014-12-08 18:00:47 +0000581
582 // At least one variable name is required.
583 if (CurTok != tok_identifier)
584 return Error("expected identifier after var");
585
586 while (1) {
587 std::string Name = IdentifierStr;
588 getNextToken(); // eat identifier.
589
590 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000591 std::unique_ptr<ExprAST> Init = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000592 if (CurTok == '=') {
593 getNextToken(); // eat the '='.
594
595 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000596 if (!Init)
597 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000598 }
599
Lang Hames09bf4c12015-08-18 18:11:06 +0000600 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopher05917fa2014-12-08 18:00:47 +0000601
602 // End of var list, exit loop.
603 if (CurTok != ',')
604 break;
605 getNextToken(); // eat the ','.
606
607 if (CurTok != tok_identifier)
608 return Error("expected identifier list after var");
609 }
610
611 // At this point, we have to have 'in'.
612 if (CurTok != tok_in)
613 return Error("expected 'in' keyword after 'var'");
614 getNextToken(); // eat 'in'.
615
Lang Hames09bf4c12015-08-18 18:11:06 +0000616 auto Body = ParseExpression();
617 if (!Body)
618 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000619
Lang Hames09bf4c12015-08-18 18:11:06 +0000620 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000621}
622
623/// primary
624/// ::= identifierexpr
625/// ::= numberexpr
626/// ::= parenexpr
627/// ::= ifexpr
628/// ::= forexpr
629/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000630static std::unique_ptr<ExprAST> ParsePrimary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000631 switch (CurTok) {
632 default:
633 return Error("unknown token when expecting an expression");
634 case tok_identifier:
635 return ParseIdentifierExpr();
636 case tok_number:
637 return ParseNumberExpr();
638 case '(':
639 return ParseParenExpr();
640 case tok_if:
641 return ParseIfExpr();
642 case tok_for:
643 return ParseForExpr();
644 case tok_var:
645 return ParseVarExpr();
646 }
647}
648
649/// unary
650/// ::= primary
651/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000652static std::unique_ptr<ExprAST> ParseUnary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000653 // If the current token is not an operator, it must be a primary expr.
654 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
655 return ParsePrimary();
656
657 // If this is a unary operator, read it.
658 int Opc = CurTok;
659 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000660 if (auto Operand = ParseUnary())
661 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
662 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000663}
664
665/// binoprhs
666/// ::= ('+' unary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000667static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000668 // If this is a binop, find its precedence.
669 while (1) {
670 int TokPrec = GetTokPrecedence();
671
672 // If this is a binop that binds at least as tightly as the current binop,
673 // consume it, otherwise we are done.
674 if (TokPrec < ExprPrec)
675 return LHS;
676
677 // Okay, we know this is a binop.
678 int BinOp = CurTok;
679 SourceLocation BinLoc = CurLoc;
680 getNextToken(); // eat binop
681
682 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000683 auto RHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000684 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000685 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000686
687 // If BinOp binds less tightly with RHS than the operator after RHS, let
688 // the pending operator take RHS as its LHS.
689 int NextPrec = GetTokPrecedence();
690 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000691 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
692 if (!RHS)
693 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000694 }
695
696 // Merge LHS/RHS.
Lang Hames09bf4c12015-08-18 18:11:06 +0000697 LHS = llvm::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
698 std::move(RHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000699 }
700}
701
702/// expression
703/// ::= unary binoprhs
704///
Lang Hames09bf4c12015-08-18 18:11:06 +0000705static std::unique_ptr<ExprAST> ParseExpression() {
706 auto LHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000707 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000708 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000709
Lang Hames09bf4c12015-08-18 18:11:06 +0000710 return ParseBinOpRHS(0, std::move(LHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000711}
712
713/// prototype
714/// ::= id '(' id* ')'
715/// ::= binary LETTER number? (id, id)
716/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000717static std::unique_ptr<PrototypeAST> ParsePrototype() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000718 std::string FnName;
719
720 SourceLocation FnLoc = CurLoc;
721
722 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
723 unsigned BinaryPrecedence = 30;
724
725 switch (CurTok) {
726 default:
727 return ErrorP("Expected function name in prototype");
728 case tok_identifier:
729 FnName = IdentifierStr;
730 Kind = 0;
731 getNextToken();
732 break;
733 case tok_unary:
734 getNextToken();
735 if (!isascii(CurTok))
736 return ErrorP("Expected unary operator");
737 FnName = "unary";
738 FnName += (char)CurTok;
739 Kind = 1;
740 getNextToken();
741 break;
742 case tok_binary:
743 getNextToken();
744 if (!isascii(CurTok))
745 return ErrorP("Expected binary operator");
746 FnName = "binary";
747 FnName += (char)CurTok;
748 Kind = 2;
749 getNextToken();
750
751 // Read the precedence if present.
752 if (CurTok == tok_number) {
753 if (NumVal < 1 || NumVal > 100)
754 return ErrorP("Invalid precedecnce: must be 1..100");
755 BinaryPrecedence = (unsigned)NumVal;
756 getNextToken();
757 }
758 break;
759 }
760
761 if (CurTok != '(')
762 return ErrorP("Expected '(' in prototype");
763
764 std::vector<std::string> ArgNames;
765 while (getNextToken() == tok_identifier)
766 ArgNames.push_back(IdentifierStr);
767 if (CurTok != ')')
768 return ErrorP("Expected ')' in prototype");
769
770 // success.
771 getNextToken(); // eat ')'.
772
773 // Verify right number of names for operator.
774 if (Kind && ArgNames.size() != Kind)
775 return ErrorP("Invalid number of operands for operator");
776
Lang Hames09bf4c12015-08-18 18:11:06 +0000777 return llvm::make_unique<PrototypeAST>(FnLoc, FnName, ArgNames, Kind != 0,
778 BinaryPrecedence);
Eric Christopher05917fa2014-12-08 18:00:47 +0000779}
780
781/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000782static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000783 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000784 auto Proto = ParsePrototype();
785 if (!Proto)
786 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000787
Lang Hames09bf4c12015-08-18 18:11:06 +0000788 if (auto E = ParseExpression())
789 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
790 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000791}
792
793/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000794static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000795 SourceLocation FnLoc = CurLoc;
Lang Hames09bf4c12015-08-18 18:11:06 +0000796 if (auto E = ParseExpression()) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000797 // Make an anonymous proto.
Lang Hames09bf4c12015-08-18 18:11:06 +0000798 auto Proto =
799 llvm::make_unique<PrototypeAST>(FnLoc, "main", std::vector<std::string>());
800 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Eric Christopher05917fa2014-12-08 18:00:47 +0000801 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000802 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000803}
804
805/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000806static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000807 getNextToken(); // eat extern.
808 return ParsePrototype();
809}
810
811//===----------------------------------------------------------------------===//
812// Debug Info Support
813//===----------------------------------------------------------------------===//
814
815static DIBuilder *DBuilder;
816
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000817DIType *DebugInfo::getDoubleTy() {
Duncan P. N. Exon Smith1d1a8e02015-04-15 23:49:09 +0000818 if (DblTy)
Eric Christopher05917fa2014-12-08 18:00:47 +0000819 return DblTy;
820
821 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
822 return DblTy;
823}
824
825void DebugInfo::emitLocation(ExprAST *AST) {
826 if (!AST)
827 return Builder.SetCurrentDebugLocation(DebugLoc());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000828 DIScope *Scope;
Eric Christopher05917fa2014-12-08 18:00:47 +0000829 if (LexicalBlocks.empty())
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000830 Scope = TheCU;
Eric Christopher05917fa2014-12-08 18:00:47 +0000831 else
Duncan P. N. Exon Smith3b6f1d52015-04-20 21:29:44 +0000832 Scope = LexicalBlocks.back();
Eric Christopher05917fa2014-12-08 18:00:47 +0000833 Builder.SetCurrentDebugLocation(
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000834 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
Eric Christopher05917fa2014-12-08 18:00:47 +0000835}
836
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000837static DISubroutineType *CreateFunctionType(unsigned NumArgs, DIFile *Unit) {
Duncan P. N. Exon Smith4e752fb2015-01-06 23:48:22 +0000838 SmallVector<Metadata *, 8> EltTys;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000839 DIType *DblTy = KSDbgInfo.getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000840
841 // Add the result type.
842 EltTys.push_back(DblTy);
843
844 for (unsigned i = 0, e = NumArgs; i != e; ++i)
845 EltTys.push_back(DblTy);
846
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +0000847 return DBuilder->createSubroutineType(Unit,
848 DBuilder->getOrCreateTypeArray(EltTys));
Eric Christopher05917fa2014-12-08 18:00:47 +0000849}
850
851//===----------------------------------------------------------------------===//
852// Code Generation
853//===----------------------------------------------------------------------===//
854
855static Module *TheModule;
856static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000857static legacy::FunctionPassManager *TheFPM;
Eric Christopher05917fa2014-12-08 18:00:47 +0000858
859Value *ErrorV(const char *Str) {
860 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000861 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000862}
863
864/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
865/// the function. This is used for mutable variables etc.
866static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
867 const std::string &VarName) {
868 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
869 TheFunction->getEntryBlock().begin());
870 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
871 VarName.c_str());
872}
873
874Value *NumberExprAST::Codegen() {
875 KSDbgInfo.emitLocation(this);
876 return ConstantFP::get(getGlobalContext(), APFloat(Val));
877}
878
879Value *VariableExprAST::Codegen() {
880 // Look this variable up in the function.
881 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000882 if (!V)
Eric Christopher05917fa2014-12-08 18:00:47 +0000883 return ErrorV("Unknown variable name");
884
885 KSDbgInfo.emitLocation(this);
886 // Load the value.
887 return Builder.CreateLoad(V, Name.c_str());
888}
889
890Value *UnaryExprAST::Codegen() {
891 Value *OperandV = Operand->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000892 if (!OperandV)
893 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000894
895 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000896 if (!F)
Eric Christopher05917fa2014-12-08 18:00:47 +0000897 return ErrorV("Unknown unary operator");
898
899 KSDbgInfo.emitLocation(this);
900 return Builder.CreateCall(F, OperandV, "unop");
901}
902
903Value *BinaryExprAST::Codegen() {
904 KSDbgInfo.emitLocation(this);
905
906 // Special case '=' because we don't want to emit the LHS as an expression.
907 if (Op == '=') {
908 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000909 // This assume we're building without RTTI because LLVM builds that way by
910 // default. If you build LLVM with RTTI this can be changed to a
911 // dynamic_cast for automatic error checking.
Lang Hames09bf4c12015-08-18 18:11:06 +0000912 VariableExprAST *LHSE = static_cast<VariableExprAST*>(LHS.get());
Eric Christopher05917fa2014-12-08 18:00:47 +0000913 if (!LHSE)
914 return ErrorV("destination of '=' must be a variable");
915 // Codegen the RHS.
916 Value *Val = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000917 if (!Val)
918 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000919
920 // Look up the name.
921 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000922 if (!Variable)
Eric Christopher05917fa2014-12-08 18:00:47 +0000923 return ErrorV("Unknown variable name");
924
925 Builder.CreateStore(Val, Variable);
926 return Val;
927 }
928
929 Value *L = LHS->Codegen();
930 Value *R = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000931 if (!L || !R)
932 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000933
934 switch (Op) {
935 case '+':
936 return Builder.CreateFAdd(L, R, "addtmp");
937 case '-':
938 return Builder.CreateFSub(L, R, "subtmp");
939 case '*':
940 return Builder.CreateFMul(L, R, "multmp");
941 case '<':
942 L = Builder.CreateFCmpULT(L, R, "cmptmp");
943 // Convert bool 0/1 to double 0.0 or 1.0
944 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
945 "booltmp");
946 default:
947 break;
948 }
949
950 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
951 // a call to it.
952 Function *F = TheModule->getFunction(std::string("binary") + Op);
953 assert(F && "binary operator not found!");
954
955 Value *Ops[] = { L, R };
956 return Builder.CreateCall(F, Ops, "binop");
957}
958
959Value *CallExprAST::Codegen() {
960 KSDbgInfo.emitLocation(this);
961
962 // Look up the name in the global module table.
963 Function *CalleeF = TheModule->getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000964 if (!CalleeF)
Eric Christopher05917fa2014-12-08 18:00:47 +0000965 return ErrorV("Unknown function referenced");
966
967 // If argument mismatch error.
968 if (CalleeF->arg_size() != Args.size())
969 return ErrorV("Incorrect # arguments passed");
970
971 std::vector<Value *> ArgsV;
972 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
973 ArgsV.push_back(Args[i]->Codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000974 if (!ArgsV.back())
975 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000976 }
977
978 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
979}
980
981Value *IfExprAST::Codegen() {
982 KSDbgInfo.emitLocation(this);
983
984 Value *CondV = Cond->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000985 if (!CondV)
986 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000987
988 // Convert condition to a bool by comparing equal to 0.0.
989 CondV = Builder.CreateFCmpONE(
990 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
991
992 Function *TheFunction = Builder.GetInsertBlock()->getParent();
993
994 // Create blocks for the then and else cases. Insert the 'then' block at the
995 // end of the function.
996 BasicBlock *ThenBB =
997 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
998 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
999 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
1000
1001 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1002
1003 // Emit then value.
1004 Builder.SetInsertPoint(ThenBB);
1005
1006 Value *ThenV = Then->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001007 if (!ThenV)
1008 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001009
1010 Builder.CreateBr(MergeBB);
1011 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1012 ThenBB = Builder.GetInsertBlock();
1013
1014 // Emit else block.
1015 TheFunction->getBasicBlockList().push_back(ElseBB);
1016 Builder.SetInsertPoint(ElseBB);
1017
1018 Value *ElseV = Else->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001019 if (!ElseV)
1020 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001021
1022 Builder.CreateBr(MergeBB);
1023 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1024 ElseBB = Builder.GetInsertBlock();
1025
1026 // Emit merge block.
1027 TheFunction->getBasicBlockList().push_back(MergeBB);
1028 Builder.SetInsertPoint(MergeBB);
1029 PHINode *PN =
1030 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1031
1032 PN->addIncoming(ThenV, ThenBB);
1033 PN->addIncoming(ElseV, ElseBB);
1034 return PN;
1035}
1036
1037Value *ForExprAST::Codegen() {
1038 // Output this as:
1039 // var = alloca double
1040 // ...
1041 // start = startexpr
1042 // store start -> var
1043 // goto loop
1044 // loop:
1045 // ...
1046 // bodyexpr
1047 // ...
1048 // loopend:
1049 // step = stepexpr
1050 // endcond = endexpr
1051 //
1052 // curvar = load var
1053 // nextvar = curvar + step
1054 // store nextvar -> var
1055 // br endcond, loop, endloop
1056 // outloop:
1057
1058 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1059
1060 // Create an alloca for the variable in the entry block.
1061 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1062
1063 KSDbgInfo.emitLocation(this);
1064
1065 // Emit the start code first, without 'variable' in scope.
1066 Value *StartVal = Start->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001067 if (!StartVal)
1068 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001069
1070 // Store the value into the alloca.
1071 Builder.CreateStore(StartVal, Alloca);
1072
1073 // Make the new basic block for the loop header, inserting after current
1074 // block.
1075 BasicBlock *LoopBB =
1076 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1077
1078 // Insert an explicit fall through from the current block to the LoopBB.
1079 Builder.CreateBr(LoopBB);
1080
1081 // Start insertion in LoopBB.
1082 Builder.SetInsertPoint(LoopBB);
1083
1084 // Within the loop, the variable is defined equal to the PHI node. If it
1085 // shadows an existing variable, we have to restore it, so save it now.
1086 AllocaInst *OldVal = NamedValues[VarName];
1087 NamedValues[VarName] = Alloca;
1088
1089 // Emit the body of the loop. This, like any other expr, can change the
1090 // current BB. Note that we ignore the value computed by the body, but don't
1091 // allow an error.
Lang Hames09bf4c12015-08-18 18:11:06 +00001092 if (!Body->Codegen())
1093 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001094
1095 // Emit the step value.
1096 Value *StepVal;
1097 if (Step) {
1098 StepVal = Step->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001099 if (!StepVal)
1100 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001101 } else {
1102 // If not specified, use 1.0.
1103 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1104 }
1105
1106 // Compute the end condition.
1107 Value *EndCond = End->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001108 if (!EndCond)
Eric Christopher05917fa2014-12-08 18:00:47 +00001109 return EndCond;
1110
1111 // Reload, increment, and restore the alloca. This handles the case where
1112 // the body of the loop mutates the variable.
1113 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1114 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1115 Builder.CreateStore(NextVar, Alloca);
1116
1117 // Convert condition to a bool by comparing equal to 0.0.
1118 EndCond = Builder.CreateFCmpONE(
1119 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1120
1121 // Create the "after loop" block and insert it.
1122 BasicBlock *AfterBB =
1123 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1124
1125 // Insert the conditional branch into the end of LoopEndBB.
1126 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1127
1128 // Any new code will be inserted in AfterBB.
1129 Builder.SetInsertPoint(AfterBB);
1130
1131 // Restore the unshadowed variable.
1132 if (OldVal)
1133 NamedValues[VarName] = OldVal;
1134 else
1135 NamedValues.erase(VarName);
1136
1137 // for expr always returns 0.0.
1138 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1139}
1140
1141Value *VarExprAST::Codegen() {
1142 std::vector<AllocaInst *> OldBindings;
1143
1144 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1145
1146 // Register all variables and emit their initializer.
1147 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1148 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +00001149 ExprAST *Init = VarNames[i].second.get();
Eric Christopher05917fa2014-12-08 18:00:47 +00001150
1151 // Emit the initializer before adding the variable to scope, this prevents
1152 // the initializer from referencing the variable itself, and permits stuff
1153 // like this:
1154 // var a = 1 in
1155 // var a = a in ... # refers to outer 'a'.
1156 Value *InitVal;
1157 if (Init) {
1158 InitVal = Init->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001159 if (!InitVal)
1160 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001161 } else { // If not specified, use 0.0.
1162 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1163 }
1164
1165 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1166 Builder.CreateStore(InitVal, Alloca);
1167
1168 // Remember the old variable binding so that we can restore the binding when
1169 // we unrecurse.
1170 OldBindings.push_back(NamedValues[VarName]);
1171
1172 // Remember this binding.
1173 NamedValues[VarName] = Alloca;
1174 }
1175
1176 KSDbgInfo.emitLocation(this);
1177
1178 // Codegen the body, now that all vars are in scope.
1179 Value *BodyVal = Body->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001180 if (!BodyVal)
1181 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001182
1183 // Pop all our variables from scope.
1184 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1185 NamedValues[VarNames[i].first] = OldBindings[i];
1186
1187 // Return the body computation.
1188 return BodyVal;
1189}
1190
1191Function *PrototypeAST::Codegen() {
1192 // Make the function type: double(double,double) etc.
1193 std::vector<Type *> Doubles(Args.size(),
1194 Type::getDoubleTy(getGlobalContext()));
1195 FunctionType *FT =
1196 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1197
1198 Function *F =
1199 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1200
1201 // If F conflicted, there was already something named 'Name'. If it has a
1202 // body, don't allow redefinition or reextern.
1203 if (F->getName() != Name) {
1204 // Delete the one we just made and get the existing one.
1205 F->eraseFromParent();
1206 F = TheModule->getFunction(Name);
1207
1208 // If F already has a body, reject this.
1209 if (!F->empty()) {
1210 ErrorF("redefinition of function");
Lang Hames09bf4c12015-08-18 18:11:06 +00001211 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001212 }
1213
1214 // If F took a different number of args, reject.
1215 if (F->arg_size() != Args.size()) {
1216 ErrorF("redefinition of function with different # args");
Lang Hames09bf4c12015-08-18 18:11:06 +00001217 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001218 }
1219 }
1220
1221 // Set names for all arguments.
1222 unsigned Idx = 0;
1223 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1224 ++AI, ++Idx)
1225 AI->setName(Args[Idx]);
1226
1227 // Create a subprogram DIE for this function.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001228 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001229 KSDbgInfo.TheCU->getDirectory());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001230 DIScope *FContext = Unit;
Eric Christopher05917fa2014-12-08 18:00:47 +00001231 unsigned LineNo = Line;
1232 unsigned ScopeLine = Line;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001233 DISubprogram *SP = DBuilder->createFunction(
Eric Christopher05917fa2014-12-08 18:00:47 +00001234 FContext, Name, StringRef(), Unit, LineNo,
1235 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001236 true /* definition */, ScopeLine, DINode::FlagPrototyped, false, F);
Eric Christopher05917fa2014-12-08 18:00:47 +00001237
Duncan P. N. Exon Smith754cf792015-04-14 16:19:44 +00001238 KSDbgInfo.FnScopeMap[this] = SP;
Eric Christopher05917fa2014-12-08 18:00:47 +00001239 return F;
1240}
1241
1242/// CreateArgumentAllocas - Create an alloca for each argument and register the
1243/// argument in the symbol table so that references to it will succeed.
1244void PrototypeAST::CreateArgumentAllocas(Function *F) {
1245 Function::arg_iterator AI = F->arg_begin();
1246 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1247 // Create an alloca for this variable.
1248 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1249
1250 // Create a debug descriptor for the variable.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001251 DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
1252 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001253 KSDbgInfo.TheCU->getDirectory());
Duncan P. N. Exon Smith1e40dc42015-07-31 17:55:53 +00001254 DILocalVariable *D = DBuilder->createParameterVariable(
1255 Scope, Args[Idx], Idx + 1, Unit, Line, KSDbgInfo.getDoubleTy(), true);
Eric Christopher05917fa2014-12-08 18:00:47 +00001256
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001257 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001258 DebugLoc::get(Line, 0, Scope),
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001259 Builder.GetInsertBlock());
Eric Christopher05917fa2014-12-08 18:00:47 +00001260
1261 // Store the initial value into the alloca.
1262 Builder.CreateStore(AI, Alloca);
1263
1264 // Add arguments to variable symbol table.
1265 NamedValues[Args[Idx]] = Alloca;
1266 }
1267}
1268
1269Function *FunctionAST::Codegen() {
1270 NamedValues.clear();
1271
1272 Function *TheFunction = Proto->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001273 if (!TheFunction)
1274 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001275
1276 // Push the current scope.
Lang Hames09bf4c12015-08-18 18:11:06 +00001277 KSDbgInfo.LexicalBlocks.push_back(KSDbgInfo.FnScopeMap[Proto.get()]);
Eric Christopher05917fa2014-12-08 18:00:47 +00001278
1279 // Unset the location for the prologue emission (leading instructions with no
1280 // location in a function are considered part of the prologue and the debugger
1281 // will run past them when breaking on a function)
1282 KSDbgInfo.emitLocation(nullptr);
1283
1284 // If this is an operator, install it.
1285 if (Proto->isBinaryOp())
1286 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1287
1288 // Create a new basic block to start insertion into.
1289 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1290 Builder.SetInsertPoint(BB);
1291
1292 // Add all arguments to the symbol table and create their allocas.
1293 Proto->CreateArgumentAllocas(TheFunction);
1294
Lang Hames09bf4c12015-08-18 18:11:06 +00001295 KSDbgInfo.emitLocation(Body.get());
Eric Christopher05917fa2014-12-08 18:00:47 +00001296
1297 if (Value *RetVal = Body->Codegen()) {
1298 // Finish off the function.
1299 Builder.CreateRet(RetVal);
1300
1301 // Pop off the lexical block for the function.
1302 KSDbgInfo.LexicalBlocks.pop_back();
1303
1304 // Validate the generated code, checking for consistency.
1305 verifyFunction(*TheFunction);
1306
1307 // Optimize the function.
1308 TheFPM->run(*TheFunction);
1309
1310 return TheFunction;
1311 }
1312
1313 // Error reading body, remove function.
1314 TheFunction->eraseFromParent();
1315
1316 if (Proto->isBinaryOp())
1317 BinopPrecedence.erase(Proto->getOperatorName());
1318
1319 // Pop off the lexical block for the function since we added it
1320 // unconditionally.
1321 KSDbgInfo.LexicalBlocks.pop_back();
1322
Lang Hames09bf4c12015-08-18 18:11:06 +00001323 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001324}
1325
1326//===----------------------------------------------------------------------===//
1327// Top-Level parsing and JIT Driver
1328//===----------------------------------------------------------------------===//
1329
1330static ExecutionEngine *TheExecutionEngine;
1331
1332static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001333 if (auto FnAST = ParseDefinition()) {
1334 if (!FnAST->Codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001335 fprintf(stderr, "Error reading function definition:");
1336 }
1337 } else {
1338 // Skip token for error recovery.
1339 getNextToken();
1340 }
1341}
1342
1343static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001344 if (auto ProtoAST = ParseExtern()) {
1345 if (!ProtoAST->Codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001346 fprintf(stderr, "Error reading extern");
1347 }
1348 } else {
1349 // Skip token for error recovery.
1350 getNextToken();
1351 }
1352}
1353
1354static void HandleTopLevelExpression() {
1355 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001356 if (auto FnAST = ParseTopLevelExpr()) {
1357 if (!FnAST->Codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001358 fprintf(stderr, "Error generating code for top level expr");
1359 }
1360 } else {
1361 // Skip token for error recovery.
1362 getNextToken();
1363 }
1364}
1365
1366/// top ::= definition | external | expression | ';'
1367static void MainLoop() {
1368 while (1) {
1369 switch (CurTok) {
1370 case tok_eof:
1371 return;
1372 case ';':
1373 getNextToken();
1374 break; // ignore top-level semicolons.
1375 case tok_def:
1376 HandleDefinition();
1377 break;
1378 case tok_extern:
1379 HandleExtern();
1380 break;
1381 default:
1382 HandleTopLevelExpression();
1383 break;
1384 }
1385 }
1386}
1387
1388//===----------------------------------------------------------------------===//
1389// "Library" functions that can be "extern'd" from user code.
1390//===----------------------------------------------------------------------===//
1391
1392/// putchard - putchar that takes a double and returns 0.
1393extern "C" double putchard(double X) {
1394 putchar((char)X);
1395 return 0;
1396}
1397
1398/// printd - printf that takes a double prints it as "%f\n", returning 0.
1399extern "C" double printd(double X) {
1400 printf("%f\n", X);
1401 return 0;
1402}
1403
1404//===----------------------------------------------------------------------===//
1405// Main driver code.
1406//===----------------------------------------------------------------------===//
1407
1408int main() {
1409 InitializeNativeTarget();
1410 InitializeNativeTargetAsmPrinter();
1411 InitializeNativeTargetAsmParser();
1412 LLVMContext &Context = getGlobalContext();
1413
1414 // Install standard binary operators.
1415 // 1 is lowest precedence.
1416 BinopPrecedence['='] = 2;
1417 BinopPrecedence['<'] = 10;
1418 BinopPrecedence['+'] = 20;
1419 BinopPrecedence['-'] = 20;
1420 BinopPrecedence['*'] = 40; // highest.
1421
1422 // Prime the first token.
1423 getNextToken();
1424
1425 // Make the module, which holds all the code.
1426 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1427 TheModule = Owner.get();
1428
1429 // Add the current debug info version into the module.
1430 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1431 DEBUG_METADATA_VERSION);
1432
1433 // Darwin only supports dwarf2.
1434 if (Triple(sys::getProcessTriple()).isOSDarwin())
1435 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1436
1437 // Construct the DIBuilder, we do this here because we need the module.
1438 DBuilder = new DIBuilder(*TheModule);
1439
1440 // Create the compile unit for the module.
1441 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1442 // but we'd like actual source locations.
1443 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1444 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1445
1446 // Create the JIT. This takes ownership of the module.
1447 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001448 TheExecutionEngine =
1449 EngineBuilder(std::move(Owner))
1450 .setErrorStr(&ErrStr)
1451 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1452 .create();
Eric Christopher05917fa2014-12-08 18:00:47 +00001453 if (!TheExecutionEngine) {
1454 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1455 exit(1);
1456 }
1457
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001458 legacy::FunctionPassManager OurFPM(TheModule);
Eric Christopher05917fa2014-12-08 18:00:47 +00001459
1460 // Set up the optimizer pipeline. Start with registering info about how the
1461 // target lays out data structures.
Mehdi Aminicd253da2015-07-16 16:47:18 +00001462 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
Eric Christopher05917fa2014-12-08 18:00:47 +00001463#if 0
1464 // Provide basic AliasAnalysis support for GVN.
1465 OurFPM.add(createBasicAliasAnalysisPass());
1466 // Promote allocas to registers.
1467 OurFPM.add(createPromoteMemoryToRegisterPass());
1468 // Do simple "peephole" optimizations and bit-twiddling optzns.
1469 OurFPM.add(createInstructionCombiningPass());
1470 // Reassociate expressions.
1471 OurFPM.add(createReassociatePass());
1472 // Eliminate Common SubExpressions.
1473 OurFPM.add(createGVNPass());
1474 // Simplify the control flow graph (deleting unreachable blocks, etc).
1475 OurFPM.add(createCFGSimplificationPass());
1476 #endif
1477 OurFPM.doInitialization();
1478
1479 // Set the global so the code gen can use this.
1480 TheFPM = &OurFPM;
1481
1482 // Run the main "interpreter loop" now.
1483 MainLoop();
1484
1485 TheFPM = 0;
1486
1487 // Finalize the debug info.
1488 DBuilder->finalize();
1489
1490 // Print out all of the generated code.
1491 TheModule->dump();
1492
1493 return 0;
1494}