blob: 99ff52bc1b4ead3f193c91a286aca854db61ac64 [file] [log] [blame]
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001#include "llvm/ADT/APFloat.h"
2#include "llvm/ADT/SmallVector.h"
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00003#include "llvm/ADT/STLExtras.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +00004#include "llvm/ADT/StringRef.h"
5#include "llvm/ADT/Triple.h"
6#include "llvm/IR/BasicBlock.h"
7#include "llvm/IR/Constants.h"
8#include "llvm/IR/DebugInfoMetadata.h"
9#include "llvm/IR/DebugLoc.h"
10#include "llvm/IR/DerivedTypes.h"
Chandler Carruth1f832f72015-02-13 09:14:30 +000011#include "llvm/IR/DIBuilder.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000012#include "llvm/IR/Function.h"
13#include "llvm/IR/Instructions.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000014#include "llvm/IR/IRBuilder.h"
15#include "llvm/IR/LLVMContext.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000016#include "llvm/IR/Metadata.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000017#include "llvm/IR/Module.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000018#include "llvm/IR/Type.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000019#include "llvm/IR/Verifier.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000020#include "llvm/Support/Host.h"
21#include "llvm/Support/raw_ostream.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000022#include "llvm/Support/TargetSelect.h"
Eugene Zelenkof981ec42016-05-19 01:08:04 +000023#include "llvm/Target/TargetMachine.h"
24#include "../include/KaleidoscopeJIT.h"
25#include <cassert>
Eric Christopher05917fa2014-12-08 18:00:47 +000026#include <cctype>
27#include <cstdio>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000028#include <cstdlib>
Eric Christopher05917fa2014-12-08 18:00:47 +000029#include <map>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000030#include <memory>
Eric Christopher05917fa2014-12-08 18:00:47 +000031#include <string>
Eugene Zelenkof981ec42016-05-19 01:08:04 +000032#include <utility>
Eric Christopher05917fa2014-12-08 18:00:47 +000033#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000034
Eric Christopher05917fa2014-12-08 18:00:47 +000035using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000036using namespace llvm::orc;
Eric Christopher05917fa2014-12-08 18:00:47 +000037
38//===----------------------------------------------------------------------===//
39// Lexer
40//===----------------------------------------------------------------------===//
41
42// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
43// of these for known things.
44enum Token {
45 tok_eof = -1,
46
47 // commands
48 tok_def = -2,
49 tok_extern = -3,
50
51 // primary
52 tok_identifier = -4,
53 tok_number = -5,
54
55 // control
56 tok_if = -6,
57 tok_then = -7,
58 tok_else = -8,
59 tok_for = -9,
60 tok_in = -10,
61
62 // operators
63 tok_binary = -11,
64 tok_unary = -12,
65
66 // var definition
67 tok_var = -13
68};
69
70std::string getTokName(int Tok) {
71 switch (Tok) {
72 case tok_eof:
73 return "eof";
74 case tok_def:
75 return "def";
76 case tok_extern:
77 return "extern";
78 case tok_identifier:
79 return "identifier";
80 case tok_number:
81 return "number";
82 case tok_if:
83 return "if";
84 case tok_then:
85 return "then";
86 case tok_else:
87 return "else";
88 case tok_for:
89 return "for";
90 case tok_in:
91 return "in";
92 case tok_binary:
93 return "binary";
94 case tok_unary:
95 return "unary";
96 case tok_var:
97 return "var";
98 }
99 return std::string(1, (char)Tok);
100}
101
102namespace {
Eric Christopher05917fa2014-12-08 18:00:47 +0000103class ExprAST;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000104} // end anonymous namespace
105
Mehdi Amini03b42e42016-04-14 21:59:01 +0000106static LLVMContext TheContext;
107static IRBuilder<> Builder(TheContext);
Eric Christopher05917fa2014-12-08 18:00:47 +0000108struct DebugInfo {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000109 DICompileUnit *TheCU;
110 DIType *DblTy;
111 std::vector<DIScope *> LexicalBlocks;
Eric Christopher05917fa2014-12-08 18:00:47 +0000112
113 void emitLocation(ExprAST *AST);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000114 DIType *getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000115} KSDbgInfo;
116
Eric Christopher05917fa2014-12-08 18:00:47 +0000117struct SourceLocation {
118 int Line;
119 int Col;
120};
121static SourceLocation CurLoc;
Lang Hames59b0da82015-08-19 18:15:58 +0000122static SourceLocation LexLoc = {1, 0};
Eric Christopher05917fa2014-12-08 18:00:47 +0000123
124static int advance() {
125 int LastChar = getchar();
126
127 if (LastChar == '\n' || LastChar == '\r') {
128 LexLoc.Line++;
129 LexLoc.Col = 0;
130 } else
131 LexLoc.Col++;
132 return LastChar;
133}
134
Lang Hames2d789c32015-08-26 03:07:41 +0000135static std::string IdentifierStr; // Filled in if tok_identifier
136static double NumVal; // Filled in if tok_number
137
Eric Christopher05917fa2014-12-08 18:00:47 +0000138/// gettok - Return the next token from standard input.
139static int gettok() {
140 static int LastChar = ' ';
141
142 // Skip any whitespace.
143 while (isspace(LastChar))
144 LastChar = advance();
145
146 CurLoc = LexLoc;
147
148 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
149 IdentifierStr = LastChar;
150 while (isalnum((LastChar = advance())))
151 IdentifierStr += LastChar;
152
153 if (IdentifierStr == "def")
154 return tok_def;
155 if (IdentifierStr == "extern")
156 return tok_extern;
157 if (IdentifierStr == "if")
158 return tok_if;
159 if (IdentifierStr == "then")
160 return tok_then;
161 if (IdentifierStr == "else")
162 return tok_else;
163 if (IdentifierStr == "for")
164 return tok_for;
165 if (IdentifierStr == "in")
166 return tok_in;
167 if (IdentifierStr == "binary")
168 return tok_binary;
169 if (IdentifierStr == "unary")
170 return tok_unary;
171 if (IdentifierStr == "var")
172 return tok_var;
173 return tok_identifier;
174 }
175
176 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
177 std::string NumStr;
178 do {
179 NumStr += LastChar;
180 LastChar = advance();
181 } while (isdigit(LastChar) || LastChar == '.');
182
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000183 NumVal = strtod(NumStr.c_str(), nullptr);
Eric Christopher05917fa2014-12-08 18:00:47 +0000184 return tok_number;
185 }
186
187 if (LastChar == '#') {
188 // Comment until end of line.
189 do
190 LastChar = advance();
191 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
192
193 if (LastChar != EOF)
194 return gettok();
195 }
196
197 // Check for end of file. Don't eat the EOF.
198 if (LastChar == EOF)
199 return tok_eof;
200
201 // Otherwise, just return the character as its ascii value.
202 int ThisChar = LastChar;
203 LastChar = advance();
204 return ThisChar;
205}
206
207//===----------------------------------------------------------------------===//
208// Abstract Syntax Tree (aka Parse Tree)
209//===----------------------------------------------------------------------===//
210namespace {
211
Lang Hames59b0da82015-08-19 18:15:58 +0000212raw_ostream &indent(raw_ostream &O, int size) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000213 return O << std::string(size, ' ');
214}
215
216/// ExprAST - Base class for all expression nodes.
217class ExprAST {
218 SourceLocation Loc;
Lang Hames59b0da82015-08-19 18:15:58 +0000219
Eric Christopher05917fa2014-12-08 18:00:47 +0000220public:
Eric Christopher05917fa2014-12-08 18:00:47 +0000221 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000222 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000223 virtual Value *codegen() = 0;
Lang Hames59b0da82015-08-19 18:15:58 +0000224 int getLine() const { return Loc.Line; }
225 int getCol() const { return Loc.Col; }
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000226
Lang Hames59b0da82015-08-19 18:15:58 +0000227 virtual raw_ostream &dump(raw_ostream &out, int ind) {
228 return out << ':' << getLine() << ':' << getCol() << '\n';
229 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000230};
231
232/// NumberExprAST - Expression class for numeric literals like "1.0".
233class NumberExprAST : public ExprAST {
234 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000235
Eric Christopher05917fa2014-12-08 18:00:47 +0000236public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000237 NumberExprAST(double Val) : Val(Val) {}
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000238 Value *codegen() override;
239
Lang Hames59b0da82015-08-19 18:15:58 +0000240 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000241 return ExprAST::dump(out << Val, ind);
242 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000243};
244
245/// VariableExprAST - Expression class for referencing a variable, like "a".
246class VariableExprAST : public ExprAST {
247 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000248
Eric Christopher05917fa2014-12-08 18:00:47 +0000249public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000250 VariableExprAST(SourceLocation Loc, const std::string &Name)
251 : ExprAST(Loc), Name(Name) {}
Eric Christopher05917fa2014-12-08 18:00:47 +0000252 const std::string &getName() const { return Name; }
Lang Hames2d789c32015-08-26 03:07:41 +0000253 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000254
Lang Hames59b0da82015-08-19 18:15:58 +0000255 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000256 return ExprAST::dump(out << Name, ind);
257 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000258};
259
260/// UnaryExprAST - Expression class for a unary operator.
261class UnaryExprAST : public ExprAST {
262 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000263 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000264
Eric Christopher05917fa2014-12-08 18:00:47 +0000265public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000266 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
267 : Opcode(Opcode), Operand(std::move(Operand)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000268 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000269
Lang Hames59b0da82015-08-19 18:15:58 +0000270 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000271 ExprAST::dump(out << "unary" << Opcode, ind);
272 Operand->dump(out, ind + 1);
273 return out;
274 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000275};
276
277/// BinaryExprAST - Expression class for a binary operator.
278class BinaryExprAST : public ExprAST {
279 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000280 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000281
Eric Christopher05917fa2014-12-08 18:00:47 +0000282public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000283 BinaryExprAST(SourceLocation Loc, char Op, std::unique_ptr<ExprAST> LHS,
284 std::unique_ptr<ExprAST> RHS)
285 : ExprAST(Loc), Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000286 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000287
Lang Hames59b0da82015-08-19 18:15:58 +0000288 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000289 ExprAST::dump(out << "binary" << Op, ind);
290 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
291 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
292 return out;
293 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000294};
295
296/// CallExprAST - Expression class for function calls.
297class CallExprAST : public ExprAST {
298 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000299 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000300
Eric Christopher05917fa2014-12-08 18:00:47 +0000301public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000302 CallExprAST(SourceLocation Loc, const std::string &Callee,
303 std::vector<std::unique_ptr<ExprAST>> Args)
304 : ExprAST(Loc), Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000305 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000306
Lang Hames59b0da82015-08-19 18:15:58 +0000307 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000308 ExprAST::dump(out << "call " << Callee, ind);
Lang Hames09bf4c12015-08-18 18:11:06 +0000309 for (const auto &Arg : Args)
Eric Christopher05917fa2014-12-08 18:00:47 +0000310 Arg->dump(indent(out, ind + 1), ind + 1);
311 return out;
312 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000313};
314
315/// IfExprAST - Expression class for if/then/else.
316class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000317 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000318
Eric Christopher05917fa2014-12-08 18:00:47 +0000319public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000320 IfExprAST(SourceLocation Loc, std::unique_ptr<ExprAST> Cond,
321 std::unique_ptr<ExprAST> Then, std::unique_ptr<ExprAST> Else)
Lang Hames59b0da82015-08-19 18:15:58 +0000322 : ExprAST(Loc), Cond(std::move(Cond)), Then(std::move(Then)),
323 Else(std::move(Else)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000324 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000325
Lang Hames59b0da82015-08-19 18:15:58 +0000326 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000327 ExprAST::dump(out << "if", ind);
328 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
329 Then->dump(indent(out, ind) << "Then:", ind + 1);
330 Else->dump(indent(out, ind) << "Else:", ind + 1);
331 return out;
332 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000333};
334
335/// ForExprAST - Expression class for for/in.
336class ForExprAST : public ExprAST {
337 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000338 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000339
Eric Christopher05917fa2014-12-08 18:00:47 +0000340public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000341 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
342 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
343 std::unique_ptr<ExprAST> Body)
344 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
345 Step(std::move(Step)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000346 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000347
Lang Hames59b0da82015-08-19 18:15:58 +0000348 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000349 ExprAST::dump(out << "for", ind);
350 Start->dump(indent(out, ind) << "Cond:", ind + 1);
351 End->dump(indent(out, ind) << "End:", ind + 1);
352 Step->dump(indent(out, ind) << "Step:", ind + 1);
353 Body->dump(indent(out, ind) << "Body:", ind + 1);
354 return out;
355 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000356};
357
358/// VarExprAST - Expression class for var/in
359class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000360 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
361 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000362
Eric Christopher05917fa2014-12-08 18:00:47 +0000363public:
Lang Hames59b0da82015-08-19 18:15:58 +0000364 VarExprAST(
365 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
366 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000367 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000368 Value *codegen() override;
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000369
Lang Hames59b0da82015-08-19 18:15:58 +0000370 raw_ostream &dump(raw_ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000371 ExprAST::dump(out << "var", ind);
372 for (const auto &NamedVar : VarNames)
373 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
374 Body->dump(indent(out, ind) << "Body:", ind + 1);
375 return out;
376 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000377};
378
379/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000380/// which captures its name, and its argument names (thus implicitly the number
381/// of arguments the function takes), as well as if it is an operator.
Eric Christopher05917fa2014-12-08 18:00:47 +0000382class PrototypeAST {
383 std::string Name;
384 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000385 bool IsOperator;
Eric Christopher05917fa2014-12-08 18:00:47 +0000386 unsigned Precedence; // Precedence if a binary op.
387 int Line;
Lang Hames59b0da82015-08-19 18:15:58 +0000388
Eric Christopher05917fa2014-12-08 18:00:47 +0000389public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000390 PrototypeAST(SourceLocation Loc, const std::string &Name,
391 std::vector<std::string> Args, bool IsOperator = false,
392 unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000393 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
394 Precedence(Prec), Line(Loc.Line) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000395 Function *codegen();
396 const std::string &getName() const { return Name; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000397
Lang Hames09bf4c12015-08-18 18:11:06 +0000398 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
399 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000400
401 char getOperatorName() const {
402 assert(isUnaryOp() || isBinaryOp());
403 return Name[Name.size() - 1];
404 }
405
406 unsigned getBinaryPrecedence() const { return Precedence; }
Lang Hames2d789c32015-08-26 03:07:41 +0000407 int getLine() const { return Line; }
Eric Christopher05917fa2014-12-08 18:00:47 +0000408};
409
410/// FunctionAST - This class represents a function definition itself.
411class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000412 std::unique_ptr<PrototypeAST> Proto;
413 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000414
Eric Christopher05917fa2014-12-08 18:00:47 +0000415public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000416 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
417 std::unique_ptr<ExprAST> Body)
418 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000419 Function *codegen();
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000420
Lang Hames59b0da82015-08-19 18:15:58 +0000421 raw_ostream &dump(raw_ostream &out, int ind) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000422 indent(out, ind) << "FunctionAST\n";
423 ++ind;
424 indent(out, ind) << "Body:";
425 return Body ? Body->dump(out, ind) : out << "null\n";
426 }
Eric Christopher05917fa2014-12-08 18:00:47 +0000427};
428} // end anonymous namespace
429
430//===----------------------------------------------------------------------===//
431// Parser
432//===----------------------------------------------------------------------===//
433
434/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
435/// token the parser is looking at. getNextToken reads another token from the
436/// lexer and updates CurTok with its results.
437static int CurTok;
438static int getNextToken() { return CurTok = gettok(); }
439
440/// BinopPrecedence - This holds the precedence for each binary operator that is
441/// defined.
442static std::map<char, int> BinopPrecedence;
443
444/// GetTokPrecedence - Get the precedence of the pending binary operator token.
445static int GetTokPrecedence() {
446 if (!isascii(CurTok))
447 return -1;
448
449 // Make sure it's a declared binop.
450 int TokPrec = BinopPrecedence[CurTok];
451 if (TokPrec <= 0)
452 return -1;
453 return TokPrec;
454}
455
Lang Hamesf9878c52016-03-25 17:33:32 +0000456/// LogError* - These are little helper functions for error handling.
457std::unique_ptr<ExprAST> LogError(const char *Str) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000458 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000459 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000460}
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000461
Lang Hamesf9878c52016-03-25 17:33:32 +0000462std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
463 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000464 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000465}
Eric Christopher05917fa2014-12-08 18:00:47 +0000466
Lang Hames09bf4c12015-08-18 18:11:06 +0000467static std::unique_ptr<ExprAST> ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000468
Eric Christopher05917fa2014-12-08 18:00:47 +0000469/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000470static std::unique_ptr<ExprAST> ParseNumberExpr() {
471 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Eric Christopher05917fa2014-12-08 18:00:47 +0000472 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000473 return std::move(Result);
Eric Christopher05917fa2014-12-08 18:00:47 +0000474}
475
476/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000477static std::unique_ptr<ExprAST> ParseParenExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000478 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000479 auto V = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000480 if (!V)
Lang Hames09bf4c12015-08-18 18:11:06 +0000481 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000482
483 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000484 return LogError("expected ')'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000485 getNextToken(); // eat ).
486 return V;
487}
488
Lang Hames59b0da82015-08-19 18:15:58 +0000489/// identifierexpr
490/// ::= identifier
491/// ::= identifier '(' expression* ')'
492static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
493 std::string IdName = IdentifierStr;
494
495 SourceLocation LitLoc = CurLoc;
496
497 getNextToken(); // eat identifier.
498
499 if (CurTok != '(') // Simple variable ref.
500 return llvm::make_unique<VariableExprAST>(LitLoc, IdName);
501
502 // Call.
503 getNextToken(); // eat (
504 std::vector<std::unique_ptr<ExprAST>> Args;
505 if (CurTok != ')') {
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000506 while (true) {
Lang Hames59b0da82015-08-19 18:15:58 +0000507 if (auto Arg = ParseExpression())
508 Args.push_back(std::move(Arg));
509 else
510 return nullptr;
511
512 if (CurTok == ')')
513 break;
514
515 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000516 return LogError("Expected ')' or ',' in argument list");
Lang Hames59b0da82015-08-19 18:15:58 +0000517 getNextToken();
518 }
519 }
520
521 // Eat the ')'.
522 getNextToken();
523
524 return llvm::make_unique<CallExprAST>(LitLoc, IdName, std::move(Args));
525}
526
Eric Christopher05917fa2014-12-08 18:00:47 +0000527/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000528static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000529 SourceLocation IfLoc = CurLoc;
530
531 getNextToken(); // eat the if.
532
533 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000534 auto Cond = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000535 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000536 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000537
538 if (CurTok != tok_then)
Lang Hamesf9878c52016-03-25 17:33:32 +0000539 return LogError("expected then");
Eric Christopher05917fa2014-12-08 18:00:47 +0000540 getNextToken(); // eat the then
541
Lang Hames09bf4c12015-08-18 18:11:06 +0000542 auto Then = ParseExpression();
543 if (!Then)
544 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000545
546 if (CurTok != tok_else)
Lang Hamesf9878c52016-03-25 17:33:32 +0000547 return LogError("expected else");
Eric Christopher05917fa2014-12-08 18:00:47 +0000548
549 getNextToken();
550
Lang Hames09bf4c12015-08-18 18:11:06 +0000551 auto Else = ParseExpression();
Eric Christopher05917fa2014-12-08 18:00:47 +0000552 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000553 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000554
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 return llvm::make_unique<IfExprAST>(IfLoc, std::move(Cond), std::move(Then),
556 std::move(Else));
Eric Christopher05917fa2014-12-08 18:00:47 +0000557}
558
559/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000560static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000561 getNextToken(); // eat the for.
562
563 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000564 return LogError("expected identifier after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000565
566 std::string IdName = IdentifierStr;
567 getNextToken(); // eat identifier.
568
569 if (CurTok != '=')
Lang Hamesf9878c52016-03-25 17:33:32 +0000570 return LogError("expected '=' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000571 getNextToken(); // eat '='.
572
Lang Hames09bf4c12015-08-18 18:11:06 +0000573 auto Start = ParseExpression();
574 if (!Start)
575 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000576 if (CurTok != ',')
Lang Hamesf9878c52016-03-25 17:33:32 +0000577 return LogError("expected ',' after for start value");
Eric Christopher05917fa2014-12-08 18:00:47 +0000578 getNextToken();
579
Lang Hames09bf4c12015-08-18 18:11:06 +0000580 auto End = ParseExpression();
581 if (!End)
582 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000583
584 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000585 std::unique_ptr<ExprAST> Step;
Eric Christopher05917fa2014-12-08 18:00:47 +0000586 if (CurTok == ',') {
587 getNextToken();
588 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000589 if (!Step)
590 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000591 }
592
593 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000594 return LogError("expected 'in' after for");
Eric Christopher05917fa2014-12-08 18:00:47 +0000595 getNextToken(); // eat 'in'.
596
Lang Hames09bf4c12015-08-18 18:11:06 +0000597 auto Body = ParseExpression();
598 if (!Body)
599 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000600
Lang Hames09bf4c12015-08-18 18:11:06 +0000601 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
602 std::move(Step), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000603}
604
605/// varexpr ::= 'var' identifier ('=' expression)?
606// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000607static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000608 getNextToken(); // eat the var.
609
Lang Hames09bf4c12015-08-18 18:11:06 +0000610 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Eric Christopher05917fa2014-12-08 18:00:47 +0000611
612 // At least one variable name is required.
613 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000614 return LogError("expected identifier after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000615
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000616 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000617 std::string Name = IdentifierStr;
618 getNextToken(); // eat identifier.
619
620 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000621 std::unique_ptr<ExprAST> Init = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000622 if (CurTok == '=') {
623 getNextToken(); // eat the '='.
624
625 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000626 if (!Init)
627 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000628 }
629
Lang Hames09bf4c12015-08-18 18:11:06 +0000630 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopher05917fa2014-12-08 18:00:47 +0000631
632 // End of var list, exit loop.
633 if (CurTok != ',')
634 break;
635 getNextToken(); // eat the ','.
636
637 if (CurTok != tok_identifier)
Lang Hamesf9878c52016-03-25 17:33:32 +0000638 return LogError("expected identifier list after var");
Eric Christopher05917fa2014-12-08 18:00:47 +0000639 }
640
641 // At this point, we have to have 'in'.
642 if (CurTok != tok_in)
Lang Hamesf9878c52016-03-25 17:33:32 +0000643 return LogError("expected 'in' keyword after 'var'");
Eric Christopher05917fa2014-12-08 18:00:47 +0000644 getNextToken(); // eat 'in'.
645
Lang Hames09bf4c12015-08-18 18:11:06 +0000646 auto Body = ParseExpression();
647 if (!Body)
648 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000649
Lang Hames09bf4c12015-08-18 18:11:06 +0000650 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Eric Christopher05917fa2014-12-08 18:00:47 +0000651}
652
653/// primary
654/// ::= identifierexpr
655/// ::= numberexpr
656/// ::= parenexpr
657/// ::= ifexpr
658/// ::= forexpr
659/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000660static std::unique_ptr<ExprAST> ParsePrimary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000661 switch (CurTok) {
662 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000663 return LogError("unknown token when expecting an expression");
Eric Christopher05917fa2014-12-08 18:00:47 +0000664 case tok_identifier:
665 return ParseIdentifierExpr();
666 case tok_number:
667 return ParseNumberExpr();
668 case '(':
669 return ParseParenExpr();
670 case tok_if:
671 return ParseIfExpr();
672 case tok_for:
673 return ParseForExpr();
674 case tok_var:
675 return ParseVarExpr();
676 }
677}
678
679/// unary
680/// ::= primary
681/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000682static std::unique_ptr<ExprAST> ParseUnary() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000683 // If the current token is not an operator, it must be a primary expr.
684 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
685 return ParsePrimary();
686
687 // If this is a unary operator, read it.
688 int Opc = CurTok;
689 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000690 if (auto Operand = ParseUnary())
691 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
692 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000693}
694
695/// binoprhs
696/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000697static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
698 std::unique_ptr<ExprAST> LHS) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000699 // If this is a binop, find its precedence.
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000700 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000701 int TokPrec = GetTokPrecedence();
702
703 // If this is a binop that binds at least as tightly as the current binop,
704 // consume it, otherwise we are done.
705 if (TokPrec < ExprPrec)
706 return LHS;
707
708 // Okay, we know this is a binop.
709 int BinOp = CurTok;
710 SourceLocation BinLoc = CurLoc;
711 getNextToken(); // eat binop
712
713 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000714 auto RHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000715 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000716 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000717
718 // If BinOp binds less tightly with RHS than the operator after RHS, let
719 // the pending operator take RHS as its LHS.
720 int NextPrec = GetTokPrecedence();
721 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000722 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
723 if (!RHS)
724 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000725 }
726
727 // Merge LHS/RHS.
Lang Hames09bf4c12015-08-18 18:11:06 +0000728 LHS = llvm::make_unique<BinaryExprAST>(BinLoc, BinOp, std::move(LHS),
729 std::move(RHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000730 }
731}
732
733/// expression
734/// ::= unary binoprhs
735///
Lang Hames09bf4c12015-08-18 18:11:06 +0000736static std::unique_ptr<ExprAST> ParseExpression() {
737 auto LHS = ParseUnary();
Eric Christopher05917fa2014-12-08 18:00:47 +0000738 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000739 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000740
Lang Hames09bf4c12015-08-18 18:11:06 +0000741 return ParseBinOpRHS(0, std::move(LHS));
Eric Christopher05917fa2014-12-08 18:00:47 +0000742}
743
744/// prototype
745/// ::= id '(' id* ')'
746/// ::= binary LETTER number? (id, id)
747/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000748static std::unique_ptr<PrototypeAST> ParsePrototype() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000749 std::string FnName;
750
751 SourceLocation FnLoc = CurLoc;
752
753 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
754 unsigned BinaryPrecedence = 30;
755
756 switch (CurTok) {
757 default:
Lang Hamesf9878c52016-03-25 17:33:32 +0000758 return LogErrorP("Expected function name in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000759 case tok_identifier:
760 FnName = IdentifierStr;
761 Kind = 0;
762 getNextToken();
763 break;
764 case tok_unary:
765 getNextToken();
766 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000767 return LogErrorP("Expected unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000768 FnName = "unary";
769 FnName += (char)CurTok;
770 Kind = 1;
771 getNextToken();
772 break;
773 case tok_binary:
774 getNextToken();
775 if (!isascii(CurTok))
Lang Hamesf9878c52016-03-25 17:33:32 +0000776 return LogErrorP("Expected binary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000777 FnName = "binary";
778 FnName += (char)CurTok;
779 Kind = 2;
780 getNextToken();
781
782 // Read the precedence if present.
783 if (CurTok == tok_number) {
784 if (NumVal < 1 || NumVal > 100)
Lang Hamesf9878c52016-03-25 17:33:32 +0000785 return LogErrorP("Invalid precedecnce: must be 1..100");
Eric Christopher05917fa2014-12-08 18:00:47 +0000786 BinaryPrecedence = (unsigned)NumVal;
787 getNextToken();
788 }
789 break;
790 }
791
792 if (CurTok != '(')
Lang Hamesf9878c52016-03-25 17:33:32 +0000793 return LogErrorP("Expected '(' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000794
795 std::vector<std::string> ArgNames;
796 while (getNextToken() == tok_identifier)
797 ArgNames.push_back(IdentifierStr);
798 if (CurTok != ')')
Lang Hamesf9878c52016-03-25 17:33:32 +0000799 return LogErrorP("Expected ')' in prototype");
Eric Christopher05917fa2014-12-08 18:00:47 +0000800
801 // success.
802 getNextToken(); // eat ')'.
803
804 // Verify right number of names for operator.
805 if (Kind && ArgNames.size() != Kind)
Lang Hamesf9878c52016-03-25 17:33:32 +0000806 return LogErrorP("Invalid number of operands for operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000807
Lang Hames09bf4c12015-08-18 18:11:06 +0000808 return llvm::make_unique<PrototypeAST>(FnLoc, FnName, ArgNames, Kind != 0,
809 BinaryPrecedence);
Eric Christopher05917fa2014-12-08 18:00:47 +0000810}
811
812/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000813static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000814 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000815 auto Proto = ParsePrototype();
816 if (!Proto)
817 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000818
Lang Hames09bf4c12015-08-18 18:11:06 +0000819 if (auto E = ParseExpression())
820 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
821 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000822}
823
824/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000825static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000826 SourceLocation FnLoc = CurLoc;
Lang Hames09bf4c12015-08-18 18:11:06 +0000827 if (auto E = ParseExpression()) {
Eric Christopher05917fa2014-12-08 18:00:47 +0000828 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000829 auto Proto = llvm::make_unique<PrototypeAST>(FnLoc, "__anon_expr",
Lang Hames59b0da82015-08-19 18:15:58 +0000830 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000831 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Eric Christopher05917fa2014-12-08 18:00:47 +0000832 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000833 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000834}
835
836/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000837static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000838 getNextToken(); // eat extern.
839 return ParsePrototype();
840}
841
842//===----------------------------------------------------------------------===//
843// Debug Info Support
844//===----------------------------------------------------------------------===//
845
Lang Hames2d789c32015-08-26 03:07:41 +0000846static std::unique_ptr<DIBuilder> DBuilder;
Eric Christopher05917fa2014-12-08 18:00:47 +0000847
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000848DIType *DebugInfo::getDoubleTy() {
Duncan P. N. Exon Smith1d1a8e02015-04-15 23:49:09 +0000849 if (DblTy)
Eric Christopher05917fa2014-12-08 18:00:47 +0000850 return DblTy;
851
852 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
853 return DblTy;
854}
855
856void DebugInfo::emitLocation(ExprAST *AST) {
857 if (!AST)
858 return Builder.SetCurrentDebugLocation(DebugLoc());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000859 DIScope *Scope;
Eric Christopher05917fa2014-12-08 18:00:47 +0000860 if (LexicalBlocks.empty())
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000861 Scope = TheCU;
Eric Christopher05917fa2014-12-08 18:00:47 +0000862 else
Duncan P. N. Exon Smith3b6f1d52015-04-20 21:29:44 +0000863 Scope = LexicalBlocks.back();
Eric Christopher05917fa2014-12-08 18:00:47 +0000864 Builder.SetCurrentDebugLocation(
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000865 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
Eric Christopher05917fa2014-12-08 18:00:47 +0000866}
867
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000868static DISubroutineType *CreateFunctionType(unsigned NumArgs, DIFile *Unit) {
Duncan P. N. Exon Smith4e752fb2015-01-06 23:48:22 +0000869 SmallVector<Metadata *, 8> EltTys;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000870 DIType *DblTy = KSDbgInfo.getDoubleTy();
Eric Christopher05917fa2014-12-08 18:00:47 +0000871
872 // Add the result type.
873 EltTys.push_back(DblTy);
874
875 for (unsigned i = 0, e = NumArgs; i != e; ++i)
876 EltTys.push_back(DblTy);
877
Eric Christopher73f00412015-10-15 07:01:16 +0000878 return DBuilder->createSubroutineType(DBuilder->getOrCreateTypeArray(EltTys));
Eric Christopher05917fa2014-12-08 18:00:47 +0000879}
880
881//===----------------------------------------------------------------------===//
882// Code Generation
883//===----------------------------------------------------------------------===//
884
Lang Hames2d789c32015-08-26 03:07:41 +0000885static std::unique_ptr<Module> TheModule;
Eric Christopher05917fa2014-12-08 18:00:47 +0000886static std::map<std::string, AllocaInst *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000887static std::unique_ptr<KaleidoscopeJIT> TheJIT;
888static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Eric Christopher05917fa2014-12-08 18:00:47 +0000889
Lang Hamesf9878c52016-03-25 17:33:32 +0000890Value *LogErrorV(const char *Str) {
891 LogError(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000892 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000893}
894
Lang Hames2d789c32015-08-26 03:07:41 +0000895Function *getFunction(std::string Name) {
896 // First, see if the function has already been added to the current module.
897 if (auto *F = TheModule->getFunction(Name))
898 return F;
899
900 // If not, check whether we can codegen the declaration from some existing
901 // prototype.
902 auto FI = FunctionProtos.find(Name);
903 if (FI != FunctionProtos.end())
904 return FI->second->codegen();
905
906 // If no existing prototype exists, return null.
907 return nullptr;
908}
909
Eric Christopher05917fa2014-12-08 18:00:47 +0000910/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
911/// the function. This is used for mutable variables etc.
912static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
913 const std::string &VarName) {
914 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
915 TheFunction->getEntryBlock().begin());
Eugene Zelenkof981ec42016-05-19 01:08:04 +0000916 return TmpB.CreateAlloca(Type::getDoubleTy(TheContext), nullptr, VarName);
Eric Christopher05917fa2014-12-08 18:00:47 +0000917}
918
Lang Hames2d789c32015-08-26 03:07:41 +0000919Value *NumberExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000920 KSDbgInfo.emitLocation(this);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000921 return ConstantFP::get(TheContext, APFloat(Val));
Eric Christopher05917fa2014-12-08 18:00:47 +0000922}
923
Lang Hames2d789c32015-08-26 03:07:41 +0000924Value *VariableExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000925 // Look this variable up in the function.
926 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000927 if (!V)
Lang Hamesf9878c52016-03-25 17:33:32 +0000928 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000929
930 KSDbgInfo.emitLocation(this);
931 // Load the value.
932 return Builder.CreateLoad(V, Name.c_str());
933}
934
Lang Hames2d789c32015-08-26 03:07:41 +0000935Value *UnaryExprAST::codegen() {
936 Value *OperandV = Operand->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000937 if (!OperandV)
938 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000939
Lang Hames2d789c32015-08-26 03:07:41 +0000940 Function *F = getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000941 if (!F)
Lang Hamesf9878c52016-03-25 17:33:32 +0000942 return LogErrorV("Unknown unary operator");
Eric Christopher05917fa2014-12-08 18:00:47 +0000943
944 KSDbgInfo.emitLocation(this);
945 return Builder.CreateCall(F, OperandV, "unop");
946}
947
Lang Hames2d789c32015-08-26 03:07:41 +0000948Value *BinaryExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +0000949 KSDbgInfo.emitLocation(this);
950
951 // Special case '=' because we don't want to emit the LHS as an expression.
952 if (Op == '=') {
953 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000954 // This assume we're building without RTTI because LLVM builds that way by
955 // default. If you build LLVM with RTTI this can be changed to a
956 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000957 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Eric Christopher05917fa2014-12-08 18:00:47 +0000958 if (!LHSE)
Lang Hamesf9878c52016-03-25 17:33:32 +0000959 return LogErrorV("destination of '=' must be a variable");
Eric Christopher05917fa2014-12-08 18:00:47 +0000960 // Codegen the RHS.
Lang Hames2d789c32015-08-26 03:07:41 +0000961 Value *Val = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000962 if (!Val)
963 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000964
965 // Look up the name.
966 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000967 if (!Variable)
Lang Hamesf9878c52016-03-25 17:33:32 +0000968 return LogErrorV("Unknown variable name");
Eric Christopher05917fa2014-12-08 18:00:47 +0000969
970 Builder.CreateStore(Val, Variable);
971 return Val;
972 }
973
Lang Hames2d789c32015-08-26 03:07:41 +0000974 Value *L = LHS->codegen();
975 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000976 if (!L || !R)
977 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +0000978
979 switch (Op) {
980 case '+':
981 return Builder.CreateFAdd(L, R, "addtmp");
982 case '-':
983 return Builder.CreateFSub(L, R, "subtmp");
984 case '*':
985 return Builder.CreateFMul(L, R, "multmp");
986 case '<':
987 L = Builder.CreateFCmpULT(L, R, "cmptmp");
988 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000989 return Builder.CreateUIToFP(L, Type::getDoubleTy(TheContext), "booltmp");
Eric Christopher05917fa2014-12-08 18:00:47 +0000990 default:
991 break;
992 }
993
994 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
995 // a call to it.
Lang Hames2d789c32015-08-26 03:07:41 +0000996 Function *F = getFunction(std::string("binary") + Op);
Eric Christopher05917fa2014-12-08 18:00:47 +0000997 assert(F && "binary operator not found!");
998
Lang Hames59b0da82015-08-19 18:15:58 +0000999 Value *Ops[] = {L, R};
Eric Christopher05917fa2014-12-08 18:00:47 +00001000 return Builder.CreateCall(F, Ops, "binop");
1001}
1002
Lang Hames2d789c32015-08-26 03:07:41 +00001003Value *CallExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001004 KSDbgInfo.emitLocation(this);
1005
1006 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +00001007 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +00001008 if (!CalleeF)
Lang Hamesf9878c52016-03-25 17:33:32 +00001009 return LogErrorV("Unknown function referenced");
Eric Christopher05917fa2014-12-08 18:00:47 +00001010
1011 // If argument mismatch error.
1012 if (CalleeF->arg_size() != Args.size())
Lang Hamesf9878c52016-03-25 17:33:32 +00001013 return LogErrorV("Incorrect # arguments passed");
Eric Christopher05917fa2014-12-08 18:00:47 +00001014
1015 std::vector<Value *> ArgsV;
1016 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +00001017 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +00001018 if (!ArgsV.back())
1019 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001020 }
1021
1022 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
1023}
1024
Lang Hames2d789c32015-08-26 03:07:41 +00001025Value *IfExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001026 KSDbgInfo.emitLocation(this);
1027
Lang Hames2d789c32015-08-26 03:07:41 +00001028 Value *CondV = Cond->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001029 if (!CondV)
1030 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001031
1032 // Convert condition to a bool by comparing equal to 0.0.
1033 CondV = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +00001034 CondV, ConstantFP::get(TheContext, APFloat(0.0)), "ifcond");
Eric Christopher05917fa2014-12-08 18:00:47 +00001035
1036 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1037
1038 // Create blocks for the then and else cases. Insert the 'then' block at the
1039 // end of the function.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001040 BasicBlock *ThenBB = BasicBlock::Create(TheContext, "then", TheFunction);
1041 BasicBlock *ElseBB = BasicBlock::Create(TheContext, "else");
1042 BasicBlock *MergeBB = BasicBlock::Create(TheContext, "ifcont");
Eric Christopher05917fa2014-12-08 18:00:47 +00001043
1044 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1045
1046 // Emit then value.
1047 Builder.SetInsertPoint(ThenBB);
1048
Lang Hames2d789c32015-08-26 03:07:41 +00001049 Value *ThenV = Then->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001050 if (!ThenV)
1051 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001052
1053 Builder.CreateBr(MergeBB);
1054 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1055 ThenBB = Builder.GetInsertBlock();
1056
1057 // Emit else block.
1058 TheFunction->getBasicBlockList().push_back(ElseBB);
1059 Builder.SetInsertPoint(ElseBB);
1060
Lang Hames2d789c32015-08-26 03:07:41 +00001061 Value *ElseV = Else->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001062 if (!ElseV)
1063 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001064
1065 Builder.CreateBr(MergeBB);
1066 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1067 ElseBB = Builder.GetInsertBlock();
1068
1069 // Emit merge block.
1070 TheFunction->getBasicBlockList().push_back(MergeBB);
1071 Builder.SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +00001072 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(TheContext), 2, "iftmp");
Eric Christopher05917fa2014-12-08 18:00:47 +00001073
1074 PN->addIncoming(ThenV, ThenBB);
1075 PN->addIncoming(ElseV, ElseBB);
1076 return PN;
1077}
1078
Lang Hames59b0da82015-08-19 18:15:58 +00001079// Output for-loop as:
1080// var = alloca double
1081// ...
1082// start = startexpr
1083// store start -> var
1084// goto loop
1085// loop:
1086// ...
1087// bodyexpr
1088// ...
1089// loopend:
1090// step = stepexpr
1091// endcond = endexpr
1092//
1093// curvar = load var
1094// nextvar = curvar + step
1095// store nextvar -> var
1096// br endcond, loop, endloop
1097// outloop:
Lang Hames2d789c32015-08-26 03:07:41 +00001098Value *ForExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001099 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1100
1101 // Create an alloca for the variable in the entry block.
1102 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1103
1104 KSDbgInfo.emitLocation(this);
1105
1106 // Emit the start code first, without 'variable' in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001107 Value *StartVal = Start->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001108 if (!StartVal)
1109 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001110
1111 // Store the value into the alloca.
1112 Builder.CreateStore(StartVal, Alloca);
1113
1114 // Make the new basic block for the loop header, inserting after current
1115 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001116 BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +00001117
1118 // Insert an explicit fall through from the current block to the LoopBB.
1119 Builder.CreateBr(LoopBB);
1120
1121 // Start insertion in LoopBB.
1122 Builder.SetInsertPoint(LoopBB);
1123
1124 // Within the loop, the variable is defined equal to the PHI node. If it
1125 // shadows an existing variable, we have to restore it, so save it now.
1126 AllocaInst *OldVal = NamedValues[VarName];
1127 NamedValues[VarName] = Alloca;
1128
1129 // Emit the body of the loop. This, like any other expr, can change the
1130 // current BB. Note that we ignore the value computed by the body, but don't
1131 // allow an error.
Lang Hames2d789c32015-08-26 03:07:41 +00001132 if (!Body->codegen())
Lang Hames09bf4c12015-08-18 18:11:06 +00001133 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001134
1135 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +00001136 Value *StepVal = nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001137 if (Step) {
Lang Hames2d789c32015-08-26 03:07:41 +00001138 StepVal = Step->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001139 if (!StepVal)
1140 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001141 } else {
1142 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001143 StepVal = ConstantFP::get(TheContext, APFloat(1.0));
Eric Christopher05917fa2014-12-08 18:00:47 +00001144 }
1145
1146 // Compute the end condition.
Lang Hames2d789c32015-08-26 03:07:41 +00001147 Value *EndCond = End->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001148 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +00001149 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001150
1151 // Reload, increment, and restore the alloca. This handles the case where
1152 // the body of the loop mutates the variable.
1153 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1154 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1155 Builder.CreateStore(NextVar, Alloca);
1156
1157 // Convert condition to a bool by comparing equal to 0.0.
1158 EndCond = Builder.CreateFCmpONE(
Mehdi Amini03b42e42016-04-14 21:59:01 +00001159 EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");
Eric Christopher05917fa2014-12-08 18:00:47 +00001160
1161 // Create the "after loop" block and insert it.
1162 BasicBlock *AfterBB =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001163 BasicBlock::Create(TheContext, "afterloop", TheFunction);
Eric Christopher05917fa2014-12-08 18:00:47 +00001164
1165 // Insert the conditional branch into the end of LoopEndBB.
1166 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1167
1168 // Any new code will be inserted in AfterBB.
1169 Builder.SetInsertPoint(AfterBB);
1170
1171 // Restore the unshadowed variable.
1172 if (OldVal)
1173 NamedValues[VarName] = OldVal;
1174 else
1175 NamedValues.erase(VarName);
1176
1177 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001178 return Constant::getNullValue(Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +00001179}
1180
Lang Hames2d789c32015-08-26 03:07:41 +00001181Value *VarExprAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001182 std::vector<AllocaInst *> OldBindings;
1183
1184 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1185
1186 // Register all variables and emit their initializer.
1187 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1188 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +00001189 ExprAST *Init = VarNames[i].second.get();
Eric Christopher05917fa2014-12-08 18:00:47 +00001190
1191 // Emit the initializer before adding the variable to scope, this prevents
1192 // the initializer from referencing the variable itself, and permits stuff
1193 // like this:
1194 // var a = 1 in
1195 // var a = a in ... # refers to outer 'a'.
1196 Value *InitVal;
1197 if (Init) {
Lang Hames2d789c32015-08-26 03:07:41 +00001198 InitVal = Init->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001199 if (!InitVal)
1200 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001201 } else { // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001202 InitVal = ConstantFP::get(TheContext, APFloat(0.0));
Eric Christopher05917fa2014-12-08 18:00:47 +00001203 }
1204
1205 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1206 Builder.CreateStore(InitVal, Alloca);
1207
1208 // Remember the old variable binding so that we can restore the binding when
1209 // we unrecurse.
1210 OldBindings.push_back(NamedValues[VarName]);
1211
1212 // Remember this binding.
1213 NamedValues[VarName] = Alloca;
1214 }
1215
1216 KSDbgInfo.emitLocation(this);
1217
1218 // Codegen the body, now that all vars are in scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001219 Value *BodyVal = Body->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001220 if (!BodyVal)
1221 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001222
1223 // Pop all our variables from scope.
1224 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1225 NamedValues[VarNames[i].first] = OldBindings[i];
1226
1227 // Return the body computation.
1228 return BodyVal;
1229}
1230
Lang Hames2d789c32015-08-26 03:07:41 +00001231Function *PrototypeAST::codegen() {
Eric Christopher05917fa2014-12-08 18:00:47 +00001232 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001233 std::vector<Type *> Doubles(Args.size(), Type::getDoubleTy(TheContext));
Eric Christopher05917fa2014-12-08 18:00:47 +00001234 FunctionType *FT =
Mehdi Amini03b42e42016-04-14 21:59:01 +00001235 FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Eric Christopher05917fa2014-12-08 18:00:47 +00001236
1237 Function *F =
Lang Hames2d789c32015-08-26 03:07:41 +00001238 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopher05917fa2014-12-08 18:00:47 +00001239
1240 // Set names for all arguments.
1241 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +00001242 for (auto &Arg : F->args())
1243 Arg.setName(Args[Idx++]);
1244
1245 return F;
1246}
1247
1248Function *FunctionAST::codegen() {
1249 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1250 // reference to it for use below.
1251 auto &P = *Proto;
1252 FunctionProtos[Proto->getName()] = std::move(Proto);
1253 Function *TheFunction = getFunction(P.getName());
1254 if (!TheFunction)
1255 return nullptr;
1256
1257 // If this is an operator, install it.
1258 if (P.isBinaryOp())
1259 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1260
1261 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001262 BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Lang Hames2d789c32015-08-26 03:07:41 +00001263 Builder.SetInsertPoint(BB);
Eric Christopher05917fa2014-12-08 18:00:47 +00001264
1265 // Create a subprogram DIE for this function.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001266 DIFile *Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
Duncan P. N. Exon Smithbe9e4fe2015-04-20 18:32:29 +00001267 KSDbgInfo.TheCU->getDirectory());
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001268 DIScope *FContext = Unit;
Lang Hames2d789c32015-08-26 03:07:41 +00001269 unsigned LineNo = P.getLine();
1270 unsigned ScopeLine = LineNo;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001271 DISubprogram *SP = DBuilder->createFunction(
Lang Hames2d789c32015-08-26 03:07:41 +00001272 FContext, P.getName(), StringRef(), Unit, LineNo,
1273 CreateFunctionType(TheFunction->arg_size(), Unit),
1274 false /* internal linkage */, true /* definition */, ScopeLine,
Peter Collingbournea252ea02015-11-05 22:18:31 +00001275 DINode::FlagPrototyped, false);
1276 TheFunction->setSubprogram(SP);
Eric Christopher05917fa2014-12-08 18:00:47 +00001277
1278 // Push the current scope.
Lang Hames2d789c32015-08-26 03:07:41 +00001279 KSDbgInfo.LexicalBlocks.push_back(SP);
Eric Christopher05917fa2014-12-08 18:00:47 +00001280
1281 // Unset the location for the prologue emission (leading instructions with no
1282 // location in a function are considered part of the prologue and the debugger
1283 // will run past them when breaking on a function)
1284 KSDbgInfo.emitLocation(nullptr);
1285
Lang Hames2d789c32015-08-26 03:07:41 +00001286 // Record the function arguments in the NamedValues map.
1287 NamedValues.clear();
1288 unsigned ArgIdx = 0;
1289 for (auto &Arg : TheFunction->args()) {
1290 // Create an alloca for this variable.
1291 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
Eric Christopher05917fa2014-12-08 18:00:47 +00001292
Lang Hames2d789c32015-08-26 03:07:41 +00001293 // Create a debug descriptor for the variable.
1294 DILocalVariable *D = DBuilder->createParameterVariable(
1295 SP, Arg.getName(), ++ArgIdx, Unit, LineNo, KSDbgInfo.getDoubleTy(),
1296 true);
Eric Christopher05917fa2014-12-08 18:00:47 +00001297
Lang Hames2d789c32015-08-26 03:07:41 +00001298 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
1299 DebugLoc::get(LineNo, 0, SP),
1300 Builder.GetInsertBlock());
1301
1302 // Store the initial value into the alloca.
1303 Builder.CreateStore(&Arg, Alloca);
1304
1305 // Add arguments to variable symbol table.
1306 NamedValues[Arg.getName()] = Alloca;
1307 }
Eric Christopher05917fa2014-12-08 18:00:47 +00001308
Lang Hames09bf4c12015-08-18 18:11:06 +00001309 KSDbgInfo.emitLocation(Body.get());
Eric Christopher05917fa2014-12-08 18:00:47 +00001310
Lang Hames2d789c32015-08-26 03:07:41 +00001311 if (Value *RetVal = Body->codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001312 // Finish off the function.
1313 Builder.CreateRet(RetVal);
1314
1315 // Pop off the lexical block for the function.
1316 KSDbgInfo.LexicalBlocks.pop_back();
1317
1318 // Validate the generated code, checking for consistency.
1319 verifyFunction(*TheFunction);
1320
Eric Christopher05917fa2014-12-08 18:00:47 +00001321 return TheFunction;
1322 }
1323
1324 // Error reading body, remove function.
1325 TheFunction->eraseFromParent();
1326
Lang Hames2d789c32015-08-26 03:07:41 +00001327 if (P.isBinaryOp())
Eric Christopher05917fa2014-12-08 18:00:47 +00001328 BinopPrecedence.erase(Proto->getOperatorName());
1329
1330 // Pop off the lexical block for the function since we added it
1331 // unconditionally.
1332 KSDbgInfo.LexicalBlocks.pop_back();
1333
Lang Hames09bf4c12015-08-18 18:11:06 +00001334 return nullptr;
Eric Christopher05917fa2014-12-08 18:00:47 +00001335}
1336
1337//===----------------------------------------------------------------------===//
1338// Top-Level parsing and JIT Driver
1339//===----------------------------------------------------------------------===//
1340
Lang Hames2d789c32015-08-26 03:07:41 +00001341static void InitializeModule() {
1342 // Open a new module.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001343 TheModule = llvm::make_unique<Module>("my cool jit", TheContext);
Lang Hames2d789c32015-08-26 03:07:41 +00001344 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1345}
Eric Christopher05917fa2014-12-08 18:00:47 +00001346
1347static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001348 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001349 if (!FnAST->codegen())
Eric Christopher05917fa2014-12-08 18:00:47 +00001350 fprintf(stderr, "Error reading function definition:");
Eric Christopher05917fa2014-12-08 18:00:47 +00001351 } else {
1352 // Skip token for error recovery.
1353 getNextToken();
1354 }
1355}
1356
1357static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001358 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001359 if (!ProtoAST->codegen())
Eric Christopher05917fa2014-12-08 18:00:47 +00001360 fprintf(stderr, "Error reading extern");
Lang Hames2d789c32015-08-26 03:07:41 +00001361 else
1362 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Eric Christopher05917fa2014-12-08 18:00:47 +00001363 } else {
1364 // Skip token for error recovery.
1365 getNextToken();
1366 }
1367}
1368
1369static void HandleTopLevelExpression() {
1370 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001371 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +00001372 if (!FnAST->codegen()) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001373 fprintf(stderr, "Error generating code for top level expr");
1374 }
1375 } else {
1376 // Skip token for error recovery.
1377 getNextToken();
1378 }
1379}
1380
1381/// top ::= definition | external | expression | ';'
1382static void MainLoop() {
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001383 while (true) {
Eric Christopher05917fa2014-12-08 18:00:47 +00001384 switch (CurTok) {
1385 case tok_eof:
1386 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001387 case ';': // ignore top-level semicolons.
Eric Christopher05917fa2014-12-08 18:00:47 +00001388 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001389 break;
Eric Christopher05917fa2014-12-08 18:00:47 +00001390 case tok_def:
1391 HandleDefinition();
1392 break;
1393 case tok_extern:
1394 HandleExtern();
1395 break;
1396 default:
1397 HandleTopLevelExpression();
1398 break;
1399 }
1400 }
1401}
1402
1403//===----------------------------------------------------------------------===//
1404// "Library" functions that can be "extern'd" from user code.
1405//===----------------------------------------------------------------------===//
1406
1407/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001408extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001409 fputc((char)X, stderr);
Eric Christopher05917fa2014-12-08 18:00:47 +00001410 return 0;
1411}
1412
1413/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +00001414extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +00001415 fprintf(stderr, "%f\n", X);
Eric Christopher05917fa2014-12-08 18:00:47 +00001416 return 0;
1417}
1418
1419//===----------------------------------------------------------------------===//
1420// Main driver code.
1421//===----------------------------------------------------------------------===//
1422
1423int main() {
1424 InitializeNativeTarget();
1425 InitializeNativeTargetAsmPrinter();
1426 InitializeNativeTargetAsmParser();
Eric Christopher05917fa2014-12-08 18:00:47 +00001427
1428 // Install standard binary operators.
1429 // 1 is lowest precedence.
1430 BinopPrecedence['='] = 2;
1431 BinopPrecedence['<'] = 10;
1432 BinopPrecedence['+'] = 20;
1433 BinopPrecedence['-'] = 20;
1434 BinopPrecedence['*'] = 40; // highest.
1435
1436 // Prime the first token.
1437 getNextToken();
1438
Lang Hames2d789c32015-08-26 03:07:41 +00001439 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1440
1441 InitializeModule();
Eric Christopher05917fa2014-12-08 18:00:47 +00001442
1443 // Add the current debug info version into the module.
1444 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1445 DEBUG_METADATA_VERSION);
1446
1447 // Darwin only supports dwarf2.
1448 if (Triple(sys::getProcessTriple()).isOSDarwin())
1449 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1450
1451 // Construct the DIBuilder, we do this here because we need the module.
Lang Hames2d789c32015-08-26 03:07:41 +00001452 DBuilder = llvm::make_unique<DIBuilder>(*TheModule);
Eric Christopher05917fa2014-12-08 18:00:47 +00001453
1454 // Create the compile unit for the module.
1455 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1456 // but we'd like actual source locations.
1457 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
Eugene Zelenkof981ec42016-05-19 01:08:04 +00001458 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", false, "", 0);
Eric Christopher05917fa2014-12-08 18:00:47 +00001459
Eric Christopher05917fa2014-12-08 18:00:47 +00001460 // Run the main "interpreter loop" now.
1461 MainLoop();
1462
Eric Christopher05917fa2014-12-08 18:00:47 +00001463 // Finalize the debug info.
1464 DBuilder->finalize();
1465
1466 // Print out all of the generated code.
1467 TheModule->dump();
1468
1469 return 0;
1470}