blob: 77c8db46ba9fa13dc351ac834602238c2a932845 [file] [log] [blame]
Lang Hamesd855e452015-02-06 22:52:04 +00001#include "llvm/Analysis/Passes.h"
2#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
3#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
Lang Hames633fe142015-03-30 03:37:06 +00004#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
Lang Hamesd855e452015-02-06 22:52:04 +00005#include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
6#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
7#include "llvm/IR/DataLayout.h"
8#include "llvm/IR/DerivedTypes.h"
9#include "llvm/IR/IRBuilder.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000010#include "llvm/IR/LegacyPassManager.h"
Lang Hames0db567f2015-02-25 20:58:28 +000011#include "llvm/IR/LLVMContext.h"
Lang Hamesd855e452015-02-06 22:52:04 +000012#include "llvm/IR/Module.h"
13#include "llvm/IR/Verifier.h"
Lang Hamesd855e452015-02-06 22:52:04 +000014#include "llvm/Support/TargetSelect.h"
15#include "llvm/Transforms/Scalar.h"
16#include <cctype>
Lang Hamesbe9df342015-02-08 19:14:56 +000017#include <iomanip>
18#include <iostream>
Lang Hamesd855e452015-02-06 22:52:04 +000019#include <map>
Lang Hamesbe9df342015-02-08 19:14:56 +000020#include <sstream>
Lang Hamesd855e452015-02-06 22:52:04 +000021#include <string>
22#include <vector>
Lang Hamese7380612015-02-21 20:44:36 +000023
Lang Hamesd855e452015-02-06 22:52:04 +000024using namespace llvm;
Lang Hamese7380612015-02-21 20:44:36 +000025using namespace llvm::orc;
Lang Hamesd855e452015-02-06 22:52:04 +000026
27//===----------------------------------------------------------------------===//
28// Lexer
29//===----------------------------------------------------------------------===//
30
31// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
32// of these for known things.
33enum Token {
34 tok_eof = -1,
35
36 // commands
37 tok_def = -2, tok_extern = -3,
38
39 // primary
40 tok_identifier = -4, tok_number = -5,
Lang Hames172d7122015-09-18 06:16:49 +000041
Lang Hamesd855e452015-02-06 22:52:04 +000042 // control
43 tok_if = -6, tok_then = -7, tok_else = -8,
44 tok_for = -9, tok_in = -10,
Lang Hames172d7122015-09-18 06:16:49 +000045
Lang Hamesd855e452015-02-06 22:52:04 +000046 // operators
47 tok_binary = -11, tok_unary = -12,
Lang Hames172d7122015-09-18 06:16:49 +000048
Lang Hamesd855e452015-02-06 22:52:04 +000049 // var definition
50 tok_var = -13
51};
52
53static std::string IdentifierStr; // Filled in if tok_identifier
54static double NumVal; // Filled in if tok_number
55
56/// gettok - Return the next token from standard input.
57static int gettok() {
58 static int LastChar = ' ';
59
60 // Skip any whitespace.
61 while (isspace(LastChar))
62 LastChar = getchar();
63
64 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
65 IdentifierStr = LastChar;
66 while (isalnum((LastChar = getchar())))
67 IdentifierStr += LastChar;
68
69 if (IdentifierStr == "def") return tok_def;
70 if (IdentifierStr == "extern") return tok_extern;
71 if (IdentifierStr == "if") return tok_if;
72 if (IdentifierStr == "then") return tok_then;
73 if (IdentifierStr == "else") return tok_else;
74 if (IdentifierStr == "for") return tok_for;
75 if (IdentifierStr == "in") return tok_in;
76 if (IdentifierStr == "binary") return tok_binary;
77 if (IdentifierStr == "unary") return tok_unary;
78 if (IdentifierStr == "var") return tok_var;
79 return tok_identifier;
80 }
81
82 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
83 std::string NumStr;
84 do {
85 NumStr += LastChar;
86 LastChar = getchar();
87 } while (isdigit(LastChar) || LastChar == '.');
88
Hans Wennborgcc9deb42015-09-29 18:02:48 +000089 NumVal = strtod(NumStr.c_str(), nullptr);
Lang Hamesd855e452015-02-06 22:52:04 +000090 return tok_number;
91 }
92
93 if (LastChar == '#') {
94 // Comment until end of line.
95 do LastChar = getchar();
96 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Lang Hames172d7122015-09-18 06:16:49 +000097
Lang Hamesd855e452015-02-06 22:52:04 +000098 if (LastChar != EOF)
99 return gettok();
100 }
Lang Hames172d7122015-09-18 06:16:49 +0000101
Lang Hamesd855e452015-02-06 22:52:04 +0000102 // Check for end of file. Don't eat the EOF.
103 if (LastChar == EOF)
104 return tok_eof;
105
106 // Otherwise, just return the character as its ascii value.
107 int ThisChar = LastChar;
108 LastChar = getchar();
109 return ThisChar;
110}
111
112//===----------------------------------------------------------------------===//
113// Abstract Syntax Tree (aka Parse Tree)
114//===----------------------------------------------------------------------===//
115
116class IRGenContext;
117
118/// ExprAST - Base class for all expression nodes.
119struct ExprAST {
120 virtual ~ExprAST() {}
David Blaikie055811e2015-02-08 20:15:01 +0000121 virtual Value *IRGen(IRGenContext &C) const = 0;
Lang Hamesd855e452015-02-06 22:52:04 +0000122};
123
124/// NumberExprAST - Expression class for numeric literals like "1.0".
125struct NumberExprAST : public ExprAST {
126 NumberExprAST(double Val) : Val(Val) {}
David Blaikie055811e2015-02-08 20:15:01 +0000127 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000128
129 double Val;
130};
131
132/// VariableExprAST - Expression class for referencing a variable, like "a".
133struct VariableExprAST : public ExprAST {
134 VariableExprAST(std::string Name) : Name(std::move(Name)) {}
David Blaikie055811e2015-02-08 20:15:01 +0000135 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000136
137 std::string Name;
138};
139
140/// UnaryExprAST - Expression class for a unary operator.
141struct UnaryExprAST : public ExprAST {
Lang Hames172d7122015-09-18 06:16:49 +0000142 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
Lang Hamesd855e452015-02-06 22:52:04 +0000143 : Opcode(std::move(Opcode)), Operand(std::move(Operand)) {}
144
David Blaikie055811e2015-02-08 20:15:01 +0000145 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000146
147 char Opcode;
148 std::unique_ptr<ExprAST> Operand;
149};
150
151/// BinaryExprAST - Expression class for a binary operator.
152struct BinaryExprAST : public ExprAST {
153 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
Lang Hames172d7122015-09-18 06:16:49 +0000154 std::unique_ptr<ExprAST> RHS)
Lang Hamesd855e452015-02-06 22:52:04 +0000155 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
156
David Blaikie055811e2015-02-08 20:15:01 +0000157 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000158
159 char Op;
160 std::unique_ptr<ExprAST> LHS, RHS;
161};
162
163/// CallExprAST - Expression class for function calls.
164struct CallExprAST : public ExprAST {
165 CallExprAST(std::string CalleeName,
166 std::vector<std::unique_ptr<ExprAST>> Args)
167 : CalleeName(std::move(CalleeName)), Args(std::move(Args)) {}
168
David Blaikie055811e2015-02-08 20:15:01 +0000169 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000170
171 std::string CalleeName;
172 std::vector<std::unique_ptr<ExprAST>> Args;
173};
174
175/// IfExprAST - Expression class for if/then/else.
176struct IfExprAST : public ExprAST {
177 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
178 std::unique_ptr<ExprAST> Else)
179 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
David Blaikie055811e2015-02-08 20:15:01 +0000180 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000181
182 std::unique_ptr<ExprAST> Cond, Then, Else;
183};
184
185/// ForExprAST - Expression class for for/in.
186struct ForExprAST : public ExprAST {
187 ForExprAST(std::string VarName, std::unique_ptr<ExprAST> Start,
188 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
189 std::unique_ptr<ExprAST> Body)
190 : VarName(std::move(VarName)), Start(std::move(Start)), End(std::move(End)),
191 Step(std::move(Step)), Body(std::move(Body)) {}
192
David Blaikie055811e2015-02-08 20:15:01 +0000193 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000194
195 std::string VarName;
196 std::unique_ptr<ExprAST> Start, End, Step, Body;
197};
198
199/// VarExprAST - Expression class for var/in
200struct VarExprAST : public ExprAST {
201 typedef std::pair<std::string, std::unique_ptr<ExprAST>> Binding;
202 typedef std::vector<Binding> BindingList;
203
204 VarExprAST(BindingList VarBindings, std::unique_ptr<ExprAST> Body)
205 : VarBindings(std::move(VarBindings)), Body(std::move(Body)) {}
David Blaikie055811e2015-02-08 20:15:01 +0000206
207 Value *IRGen(IRGenContext &C) const override;
Lang Hamesd855e452015-02-06 22:52:04 +0000208
209 BindingList VarBindings;
210 std::unique_ptr<ExprAST> Body;
211};
212
213/// PrototypeAST - This class represents the "prototype" for a function,
214/// which captures its argument names as well as if it is an operator.
215struct PrototypeAST {
216 PrototypeAST(std::string Name, std::vector<std::string> Args,
217 bool IsOperator = false, unsigned Precedence = 0)
218 : Name(std::move(Name)), Args(std::move(Args)), IsOperator(IsOperator),
219 Precedence(Precedence) {}
220
David Blaikie055811e2015-02-08 20:15:01 +0000221 Function *IRGen(IRGenContext &C) const;
Lang Hamesd855e452015-02-06 22:52:04 +0000222 void CreateArgumentAllocas(Function *F, IRGenContext &C);
223
224 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
225 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Lang Hames172d7122015-09-18 06:16:49 +0000226
Lang Hamesd855e452015-02-06 22:52:04 +0000227 char getOperatorName() const {
228 assert(isUnaryOp() || isBinaryOp());
229 return Name[Name.size()-1];
230 }
231
232 std::string Name;
233 std::vector<std::string> Args;
234 bool IsOperator;
235 unsigned Precedence; // Precedence if a binary op.
236};
237
238/// FunctionAST - This class represents a function definition itself.
239struct FunctionAST {
240 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
241 std::unique_ptr<ExprAST> Body)
242 : Proto(std::move(Proto)), Body(std::move(Body)) {}
243
David Blaikie055811e2015-02-08 20:15:01 +0000244 Function *IRGen(IRGenContext &C) const;
Lang Hamesd855e452015-02-06 22:52:04 +0000245
246 std::unique_ptr<PrototypeAST> Proto;
247 std::unique_ptr<ExprAST> Body;
248};
249
250//===----------------------------------------------------------------------===//
251// Parser
252//===----------------------------------------------------------------------===//
253
254/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
255/// token the parser is looking at. getNextToken reads another token from the
256/// lexer and updates CurTok with its results.
257static int CurTok;
258static int getNextToken() {
259 return CurTok = gettok();
260}
261
262/// BinopPrecedence - This holds the precedence for each binary operator that is
263/// defined.
264static std::map<char, int> BinopPrecedence;
265
266/// GetTokPrecedence - Get the precedence of the pending binary operator token.
267static int GetTokPrecedence() {
268 if (!isascii(CurTok))
269 return -1;
Lang Hames172d7122015-09-18 06:16:49 +0000270
Lang Hamesd855e452015-02-06 22:52:04 +0000271 // Make sure it's a declared binop.
272 int TokPrec = BinopPrecedence[CurTok];
273 if (TokPrec <= 0) return -1;
274 return TokPrec;
275}
276
277template <typename T>
Lang Hamesbe9df342015-02-08 19:14:56 +0000278std::unique_ptr<T> ErrorU(const std::string &Str) {
279 std::cerr << "Error: " << Str << "\n";
Lang Hamesd855e452015-02-06 22:52:04 +0000280 return nullptr;
281}
282
283template <typename T>
Lang Hamesbe9df342015-02-08 19:14:56 +0000284T* ErrorP(const std::string &Str) {
285 std::cerr << "Error: " << Str << "\n";
Lang Hamesd855e452015-02-06 22:52:04 +0000286 return nullptr;
287}
288
289static std::unique_ptr<ExprAST> ParseExpression();
290
291/// identifierexpr
292/// ::= identifier
293/// ::= identifier '(' expression* ')'
294static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
295 std::string IdName = IdentifierStr;
Lang Hames172d7122015-09-18 06:16:49 +0000296
Lang Hamesd855e452015-02-06 22:52:04 +0000297 getNextToken(); // eat identifier.
Lang Hames172d7122015-09-18 06:16:49 +0000298
Lang Hamesd855e452015-02-06 22:52:04 +0000299 if (CurTok != '(') // Simple variable ref.
300 return llvm::make_unique<VariableExprAST>(IdName);
Lang Hames172d7122015-09-18 06:16:49 +0000301
Lang Hamesd855e452015-02-06 22:52:04 +0000302 // Call.
303 getNextToken(); // eat (
304 std::vector<std::unique_ptr<ExprAST>> Args;
305 if (CurTok != ')') {
306 while (1) {
307 auto Arg = ParseExpression();
308 if (!Arg) return nullptr;
309 Args.push_back(std::move(Arg));
310
311 if (CurTok == ')') break;
312
313 if (CurTok != ',')
314 return ErrorU<CallExprAST>("Expected ')' or ',' in argument list");
315 getNextToken();
316 }
317 }
318
319 // Eat the ')'.
320 getNextToken();
Lang Hames172d7122015-09-18 06:16:49 +0000321
Lang Hamesd855e452015-02-06 22:52:04 +0000322 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
323}
324
325/// numberexpr ::= number
326static std::unique_ptr<NumberExprAST> ParseNumberExpr() {
327 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
328 getNextToken(); // consume the number
329 return Result;
330}
331
332/// parenexpr ::= '(' expression ')'
333static std::unique_ptr<ExprAST> ParseParenExpr() {
334 getNextToken(); // eat (.
335 auto V = ParseExpression();
336 if (!V)
337 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000338
Lang Hamesd855e452015-02-06 22:52:04 +0000339 if (CurTok != ')')
340 return ErrorU<ExprAST>("expected ')'");
341 getNextToken(); // eat ).
342 return V;
343}
344
345/// ifexpr ::= 'if' expression 'then' expression 'else' expression
346static std::unique_ptr<ExprAST> ParseIfExpr() {
347 getNextToken(); // eat the if.
Lang Hames172d7122015-09-18 06:16:49 +0000348
Lang Hamesd855e452015-02-06 22:52:04 +0000349 // condition.
350 auto Cond = ParseExpression();
351 if (!Cond)
352 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000353
Lang Hamesd855e452015-02-06 22:52:04 +0000354 if (CurTok != tok_then)
355 return ErrorU<ExprAST>("expected then");
356 getNextToken(); // eat the then
Lang Hames172d7122015-09-18 06:16:49 +0000357
Lang Hamesd855e452015-02-06 22:52:04 +0000358 auto Then = ParseExpression();
359 if (!Then)
360 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000361
Lang Hamesd855e452015-02-06 22:52:04 +0000362 if (CurTok != tok_else)
363 return ErrorU<ExprAST>("expected else");
Lang Hames172d7122015-09-18 06:16:49 +0000364
Lang Hamesd855e452015-02-06 22:52:04 +0000365 getNextToken();
Lang Hames172d7122015-09-18 06:16:49 +0000366
Lang Hamesd855e452015-02-06 22:52:04 +0000367 auto Else = ParseExpression();
368 if (!Else)
369 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000370
Lang Hamesd855e452015-02-06 22:52:04 +0000371 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
372 std::move(Else));
373}
374
375/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
376static std::unique_ptr<ForExprAST> ParseForExpr() {
377 getNextToken(); // eat the for.
378
379 if (CurTok != tok_identifier)
380 return ErrorU<ForExprAST>("expected identifier after for");
Lang Hames172d7122015-09-18 06:16:49 +0000381
Lang Hamesd855e452015-02-06 22:52:04 +0000382 std::string IdName = IdentifierStr;
383 getNextToken(); // eat identifier.
Lang Hames172d7122015-09-18 06:16:49 +0000384
Lang Hamesd855e452015-02-06 22:52:04 +0000385 if (CurTok != '=')
386 return ErrorU<ForExprAST>("expected '=' after for");
387 getNextToken(); // eat '='.
Lang Hames172d7122015-09-18 06:16:49 +0000388
Lang Hamesd855e452015-02-06 22:52:04 +0000389 auto Start = ParseExpression();
390 if (!Start)
391 return nullptr;
392 if (CurTok != ',')
393 return ErrorU<ForExprAST>("expected ',' after for start value");
394 getNextToken();
Lang Hames172d7122015-09-18 06:16:49 +0000395
Lang Hamesd855e452015-02-06 22:52:04 +0000396 auto End = ParseExpression();
397 if (!End)
398 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000399
Lang Hamesd855e452015-02-06 22:52:04 +0000400 // The step value is optional.
401 std::unique_ptr<ExprAST> Step;
402 if (CurTok == ',') {
403 getNextToken();
404 Step = ParseExpression();
405 if (!Step)
406 return nullptr;
407 }
Lang Hames172d7122015-09-18 06:16:49 +0000408
Lang Hamesd855e452015-02-06 22:52:04 +0000409 if (CurTok != tok_in)
410 return ErrorU<ForExprAST>("expected 'in' after for");
411 getNextToken(); // eat 'in'.
Lang Hames172d7122015-09-18 06:16:49 +0000412
Lang Hamesd855e452015-02-06 22:52:04 +0000413 auto Body = ParseExpression();
414 if (Body)
415 return nullptr;
416
417 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
418 std::move(Step), std::move(Body));
419}
420
Lang Hames172d7122015-09-18 06:16:49 +0000421/// varexpr ::= 'var' identifier ('=' expression)?
Lang Hamesd855e452015-02-06 22:52:04 +0000422// (',' identifier ('=' expression)?)* 'in' expression
423static std::unique_ptr<VarExprAST> ParseVarExpr() {
424 getNextToken(); // eat the var.
425
426 VarExprAST::BindingList VarBindings;
427
428 // At least one variable name is required.
429 if (CurTok != tok_identifier)
430 return ErrorU<VarExprAST>("expected identifier after var");
Lang Hames172d7122015-09-18 06:16:49 +0000431
Lang Hamesd855e452015-02-06 22:52:04 +0000432 while (1) {
433 std::string Name = IdentifierStr;
434 getNextToken(); // eat identifier.
435
436 // Read the optional initializer.
437 std::unique_ptr<ExprAST> Init;
438 if (CurTok == '=') {
439 getNextToken(); // eat the '='.
Lang Hames172d7122015-09-18 06:16:49 +0000440
Lang Hamesd855e452015-02-06 22:52:04 +0000441 Init = ParseExpression();
442 if (!Init)
443 return nullptr;
444 }
Lang Hames172d7122015-09-18 06:16:49 +0000445
Lang Hamesd855e452015-02-06 22:52:04 +0000446 VarBindings.push_back(VarExprAST::Binding(Name, std::move(Init)));
Lang Hames172d7122015-09-18 06:16:49 +0000447
Lang Hamesd855e452015-02-06 22:52:04 +0000448 // End of var list, exit loop.
449 if (CurTok != ',') break;
450 getNextToken(); // eat the ','.
Lang Hames172d7122015-09-18 06:16:49 +0000451
Lang Hamesd855e452015-02-06 22:52:04 +0000452 if (CurTok != tok_identifier)
453 return ErrorU<VarExprAST>("expected identifier list after var");
454 }
Lang Hames172d7122015-09-18 06:16:49 +0000455
Lang Hamesd855e452015-02-06 22:52:04 +0000456 // At this point, we have to have 'in'.
457 if (CurTok != tok_in)
458 return ErrorU<VarExprAST>("expected 'in' keyword after 'var'");
459 getNextToken(); // eat 'in'.
Lang Hames172d7122015-09-18 06:16:49 +0000460
Lang Hamesd855e452015-02-06 22:52:04 +0000461 auto Body = ParseExpression();
462 if (!Body)
463 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000464
Lang Hamesd855e452015-02-06 22:52:04 +0000465 return llvm::make_unique<VarExprAST>(std::move(VarBindings), std::move(Body));
466}
467
468/// primary
469/// ::= identifierexpr
470/// ::= numberexpr
471/// ::= parenexpr
472/// ::= ifexpr
473/// ::= forexpr
474/// ::= varexpr
475static std::unique_ptr<ExprAST> ParsePrimary() {
476 switch (CurTok) {
477 default: return ErrorU<ExprAST>("unknown token when expecting an expression");
478 case tok_identifier: return ParseIdentifierExpr();
479 case tok_number: return ParseNumberExpr();
480 case '(': return ParseParenExpr();
481 case tok_if: return ParseIfExpr();
482 case tok_for: return ParseForExpr();
483 case tok_var: return ParseVarExpr();
484 }
485}
486
487/// unary
488/// ::= primary
489/// ::= '!' unary
490static std::unique_ptr<ExprAST> ParseUnary() {
491 // If the current token is not an operator, it must be a primary expr.
492 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
493 return ParsePrimary();
Lang Hames172d7122015-09-18 06:16:49 +0000494
Lang Hamesd855e452015-02-06 22:52:04 +0000495 // If this is a unary operator, read it.
496 int Opc = CurTok;
497 getNextToken();
498 if (auto Operand = ParseUnary())
499 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
500 return nullptr;
501}
502
503/// binoprhs
504/// ::= ('+' unary)*
505static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
506 std::unique_ptr<ExprAST> LHS) {
507 // If this is a binop, find its precedence.
508 while (1) {
509 int TokPrec = GetTokPrecedence();
Lang Hames172d7122015-09-18 06:16:49 +0000510
Lang Hamesd855e452015-02-06 22:52:04 +0000511 // If this is a binop that binds at least as tightly as the current binop,
512 // consume it, otherwise we are done.
513 if (TokPrec < ExprPrec)
514 return LHS;
Lang Hames172d7122015-09-18 06:16:49 +0000515
Lang Hamesd855e452015-02-06 22:52:04 +0000516 // Okay, we know this is a binop.
517 int BinOp = CurTok;
518 getNextToken(); // eat binop
Lang Hames172d7122015-09-18 06:16:49 +0000519
Lang Hamesd855e452015-02-06 22:52:04 +0000520 // Parse the unary expression after the binary operator.
521 auto RHS = ParseUnary();
522 if (!RHS)
523 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000524
Lang Hamesd855e452015-02-06 22:52:04 +0000525 // If BinOp binds less tightly with RHS than the operator after RHS, let
526 // the pending operator take RHS as its LHS.
527 int NextPrec = GetTokPrecedence();
528 if (TokPrec < NextPrec) {
529 RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
530 if (!RHS)
531 return nullptr;
532 }
Lang Hames172d7122015-09-18 06:16:49 +0000533
Lang Hamesd855e452015-02-06 22:52:04 +0000534 // Merge LHS/RHS.
535 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
536 }
537}
538
539/// expression
540/// ::= unary binoprhs
541///
542static std::unique_ptr<ExprAST> ParseExpression() {
543 auto LHS = ParseUnary();
544 if (!LHS)
545 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000546
Lang Hamesd855e452015-02-06 22:52:04 +0000547 return ParseBinOpRHS(0, std::move(LHS));
548}
549
550/// prototype
551/// ::= id '(' id* ')'
552/// ::= binary LETTER number? (id, id)
553/// ::= unary LETTER (id)
554static std::unique_ptr<PrototypeAST> ParsePrototype() {
555 std::string FnName;
Lang Hames172d7122015-09-18 06:16:49 +0000556
Lang Hamesd855e452015-02-06 22:52:04 +0000557 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
558 unsigned BinaryPrecedence = 30;
Lang Hames172d7122015-09-18 06:16:49 +0000559
Lang Hamesd855e452015-02-06 22:52:04 +0000560 switch (CurTok) {
561 default:
562 return ErrorU<PrototypeAST>("Expected function name in prototype");
563 case tok_identifier:
564 FnName = IdentifierStr;
565 Kind = 0;
566 getNextToken();
567 break;
568 case tok_unary:
569 getNextToken();
570 if (!isascii(CurTok))
571 return ErrorU<PrototypeAST>("Expected unary operator");
572 FnName = "unary";
573 FnName += (char)CurTok;
574 Kind = 1;
575 getNextToken();
576 break;
577 case tok_binary:
578 getNextToken();
579 if (!isascii(CurTok))
580 return ErrorU<PrototypeAST>("Expected binary operator");
581 FnName = "binary";
582 FnName += (char)CurTok;
583 Kind = 2;
584 getNextToken();
Lang Hames172d7122015-09-18 06:16:49 +0000585
Lang Hamesd855e452015-02-06 22:52:04 +0000586 // Read the precedence if present.
587 if (CurTok == tok_number) {
588 if (NumVal < 1 || NumVal > 100)
589 return ErrorU<PrototypeAST>("Invalid precedecnce: must be 1..100");
590 BinaryPrecedence = (unsigned)NumVal;
591 getNextToken();
592 }
593 break;
594 }
Lang Hames172d7122015-09-18 06:16:49 +0000595
Lang Hamesd855e452015-02-06 22:52:04 +0000596 if (CurTok != '(')
597 return ErrorU<PrototypeAST>("Expected '(' in prototype");
Lang Hames172d7122015-09-18 06:16:49 +0000598
Lang Hamesd855e452015-02-06 22:52:04 +0000599 std::vector<std::string> ArgNames;
600 while (getNextToken() == tok_identifier)
601 ArgNames.push_back(IdentifierStr);
602 if (CurTok != ')')
603 return ErrorU<PrototypeAST>("Expected ')' in prototype");
Lang Hames172d7122015-09-18 06:16:49 +0000604
Lang Hamesd855e452015-02-06 22:52:04 +0000605 // success.
606 getNextToken(); // eat ')'.
Lang Hames172d7122015-09-18 06:16:49 +0000607
Lang Hamesd855e452015-02-06 22:52:04 +0000608 // Verify right number of names for operator.
609 if (Kind && ArgNames.size() != Kind)
610 return ErrorU<PrototypeAST>("Invalid number of operands for operator");
Lang Hames172d7122015-09-18 06:16:49 +0000611
Lang Hamesd855e452015-02-06 22:52:04 +0000612 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames), Kind != 0,
613 BinaryPrecedence);
614}
615
616/// definition ::= 'def' prototype expression
617static std::unique_ptr<FunctionAST> ParseDefinition() {
618 getNextToken(); // eat def.
619 auto Proto = ParsePrototype();
620 if (!Proto)
621 return nullptr;
622
623 if (auto Body = ParseExpression())
624 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(Body));
625 return nullptr;
626}
627
628/// toplevelexpr ::= expression
629static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
630 if (auto E = ParseExpression()) {
631 // Make an anonymous proto.
632 auto Proto =
633 llvm::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
634 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
635 }
636 return nullptr;
637}
638
639/// external ::= 'extern' prototype
640static std::unique_ptr<PrototypeAST> ParseExtern() {
641 getNextToken(); // eat extern.
642 return ParsePrototype();
643}
644
645//===----------------------------------------------------------------------===//
646// Code Generation
647//===----------------------------------------------------------------------===//
648
649// FIXME: Obviously we can do better than this
Lang Hamesbe9df342015-02-08 19:14:56 +0000650std::string GenerateUniqueName(const std::string &Root) {
Lang Hamesd855e452015-02-06 22:52:04 +0000651 static int i = 0;
Lang Hamesbe9df342015-02-08 19:14:56 +0000652 std::ostringstream NameStream;
653 NameStream << Root << ++i;
654 return NameStream.str();
Lang Hamesd855e452015-02-06 22:52:04 +0000655}
656
657std::string MakeLegalFunctionName(std::string Name)
658{
659 std::string NewName;
660 assert(!Name.empty() && "Base name must not be empty");
661
662 // Start with what we have
663 NewName = Name;
664
665 // Look for a numberic first character
666 if (NewName.find_first_of("0123456789") == 0) {
667 NewName.insert(0, 1, 'n');
668 }
669
670 // Replace illegal characters with their ASCII equivalent
671 std::string legal_elements = "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
672 size_t pos;
673 while ((pos = NewName.find_first_not_of(legal_elements)) != std::string::npos) {
Lang Hamesbe9df342015-02-08 19:14:56 +0000674 std::ostringstream NumStream;
675 NumStream << (int)NewName.at(pos);
676 NewName = NewName.replace(pos, 1, NumStream.str());
Lang Hamesd855e452015-02-06 22:52:04 +0000677 }
678
679 return NewName;
680}
681
682class SessionContext {
683public:
Lang Hames0db567f2015-02-25 20:58:28 +0000684 SessionContext(LLVMContext &C)
685 : Context(C), TM(EngineBuilder().selectTarget()) {}
Lang Hamesd855e452015-02-06 22:52:04 +0000686 LLVMContext& getLLVMContext() const { return Context; }
Lang Hames0db567f2015-02-25 20:58:28 +0000687 TargetMachine& getTarget() { return *TM; }
Lang Hamesd855e452015-02-06 22:52:04 +0000688 void addPrototypeAST(std::unique_ptr<PrototypeAST> P);
689 PrototypeAST* getPrototypeAST(const std::string &Name);
690private:
691 typedef std::map<std::string, std::unique_ptr<PrototypeAST>> PrototypeMap;
Lang Hames172d7122015-09-18 06:16:49 +0000692
Lang Hamesd855e452015-02-06 22:52:04 +0000693 LLVMContext &Context;
Lang Hames0db567f2015-02-25 20:58:28 +0000694 std::unique_ptr<TargetMachine> TM;
Lang Hames172d7122015-09-18 06:16:49 +0000695
Lang Hamesd855e452015-02-06 22:52:04 +0000696 PrototypeMap Prototypes;
697};
698
699void SessionContext::addPrototypeAST(std::unique_ptr<PrototypeAST> P) {
700 Prototypes[P->Name] = std::move(P);
701}
702
703PrototypeAST* SessionContext::getPrototypeAST(const std::string &Name) {
704 PrototypeMap::iterator I = Prototypes.find(Name);
705 if (I != Prototypes.end())
706 return I->second.get();
707 return nullptr;
Lang Hamesbe9df342015-02-08 19:14:56 +0000708}
Lang Hamesd855e452015-02-06 22:52:04 +0000709
710class IRGenContext {
711public:
712
713 IRGenContext(SessionContext &S)
714 : Session(S),
715 M(new Module(GenerateUniqueName("jit_module_"),
716 Session.getLLVMContext())),
Lang Hames0db567f2015-02-25 20:58:28 +0000717 Builder(Session.getLLVMContext()) {
Mehdi Amini26d48132015-07-24 16:04:22 +0000718 M->setDataLayout(Session.getTarget().createDataLayout());
Lang Hames0db567f2015-02-25 20:58:28 +0000719 }
Lang Hamesd855e452015-02-06 22:52:04 +0000720
721 SessionContext& getSession() { return Session; }
722 Module& getM() const { return *M; }
723 std::unique_ptr<Module> takeM() { return std::move(M); }
724 IRBuilder<>& getBuilder() { return Builder; }
725 LLVMContext& getLLVMContext() { return Session.getLLVMContext(); }
726 Function* getPrototype(const std::string &Name);
727
728 std::map<std::string, AllocaInst*> NamedValues;
729private:
730 SessionContext &Session;
731 std::unique_ptr<Module> M;
732 IRBuilder<> Builder;
733};
734
735Function* IRGenContext::getPrototype(const std::string &Name) {
736 if (Function *ExistingProto = M->getFunction(Name))
737 return ExistingProto;
738 if (PrototypeAST *ProtoAST = Session.getPrototypeAST(Name))
739 return ProtoAST->IRGen(*this);
740 return nullptr;
741}
742
743/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
744/// the function. This is used for mutable variables etc.
745static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
746 const std::string &VarName) {
747 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
748 TheFunction->getEntryBlock().begin());
Mehdi Amini03b42e42016-04-14 21:59:01 +0000749 return TmpB.CreateAlloca(Type::getDoubleTy(TheFunction->getContext()),
750 nullptr, VarName.c_str());
Lang Hamesd855e452015-02-06 22:52:04 +0000751}
752
David Blaikie055811e2015-02-08 20:15:01 +0000753Value *NumberExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000754 return ConstantFP::get(C.getLLVMContext(), APFloat(Val));
755}
756
David Blaikie055811e2015-02-08 20:15:01 +0000757Value *VariableExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000758 // Look this variable up in the function.
759 Value *V = C.NamedValues[Name];
760
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000761 if (!V)
Lang Hamesbe9df342015-02-08 19:14:56 +0000762 return ErrorP<Value>("Unknown variable name '" + Name + "'");
Lang Hamesd855e452015-02-06 22:52:04 +0000763
764 // Load the value.
765 return C.getBuilder().CreateLoad(V, Name.c_str());
766}
767
David Blaikie055811e2015-02-08 20:15:01 +0000768Value *UnaryExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000769 if (Value *OperandV = Operand->IRGen(C)) {
770 std::string FnName = MakeLegalFunctionName(std::string("unary")+Opcode);
771 if (Function *F = C.getPrototype(FnName))
772 return C.getBuilder().CreateCall(F, OperandV, "unop");
773 return ErrorP<Value>("Unknown unary operator");
774 }
775
776 // Could not codegen operand - return null.
777 return nullptr;
778}
779
David Blaikie055811e2015-02-08 20:15:01 +0000780Value *BinaryExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000781 // Special case '=' because we don't want to emit the LHS as an expression.
782 if (Op == '=') {
783 // Assignment requires the LHS to be an identifier.
David Blaikiead60be92015-10-08 17:22:12 +0000784 auto &LHSVar = static_cast<VariableExprAST &>(*LHS);
Lang Hamesd855e452015-02-06 22:52:04 +0000785 // Codegen the RHS.
786 Value *Val = RHS->IRGen(C);
787 if (!Val) return nullptr;
788
789 // Look up the name.
790 if (auto Variable = C.NamedValues[LHSVar.Name]) {
791 C.getBuilder().CreateStore(Val, Variable);
792 return Val;
793 }
794 return ErrorP<Value>("Unknown variable name");
795 }
Lang Hames172d7122015-09-18 06:16:49 +0000796
Lang Hamesd855e452015-02-06 22:52:04 +0000797 Value *L = LHS->IRGen(C);
798 Value *R = RHS->IRGen(C);
799 if (!L || !R) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000800
Lang Hamesd855e452015-02-06 22:52:04 +0000801 switch (Op) {
802 case '+': return C.getBuilder().CreateFAdd(L, R, "addtmp");
803 case '-': return C.getBuilder().CreateFSub(L, R, "subtmp");
804 case '*': return C.getBuilder().CreateFMul(L, R, "multmp");
805 case '/': return C.getBuilder().CreateFDiv(L, R, "divtmp");
806 case '<':
807 L = C.getBuilder().CreateFCmpULT(L, R, "cmptmp");
808 // Convert bool 0/1 to double 0.0 or 1.0
Mehdi Amini03b42e42016-04-14 21:59:01 +0000809 return C.getBuilder().CreateUIToFP(L, Type::getDoubleTy(C.getLLVMContext()),
810 "booltmp");
Lang Hamesd855e452015-02-06 22:52:04 +0000811 default: break;
812 }
Lang Hames172d7122015-09-18 06:16:49 +0000813
Lang Hamesd855e452015-02-06 22:52:04 +0000814 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
815 // a call to it.
816 std::string FnName = MakeLegalFunctionName(std::string("binary")+Op);
817 if (Function *F = C.getPrototype(FnName)) {
818 Value *Ops[] = { L, R };
819 return C.getBuilder().CreateCall(F, Ops, "binop");
820 }
Lang Hames172d7122015-09-18 06:16:49 +0000821
Lang Hamesd855e452015-02-06 22:52:04 +0000822 return ErrorP<Value>("Unknown binary operator");
823}
824
David Blaikie055811e2015-02-08 20:15:01 +0000825Value *CallExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000826 // Look up the name in the global module table.
827 if (auto CalleeF = C.getPrototype(CalleeName)) {
828 // If argument mismatch error.
829 if (CalleeF->arg_size() != Args.size())
830 return ErrorP<Value>("Incorrect # arguments passed");
831
832 std::vector<Value*> ArgsV;
833 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
834 ArgsV.push_back(Args[i]->IRGen(C));
835 if (!ArgsV.back()) return nullptr;
836 }
Lang Hames172d7122015-09-18 06:16:49 +0000837
Lang Hamesd855e452015-02-06 22:52:04 +0000838 return C.getBuilder().CreateCall(CalleeF, ArgsV, "calltmp");
839 }
840
841 return ErrorP<Value>("Unknown function referenced");
842}
843
David Blaikie055811e2015-02-08 20:15:01 +0000844Value *IfExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000845 Value *CondV = Cond->IRGen(C);
846 if (!CondV) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000847
Lang Hamesd855e452015-02-06 22:52:04 +0000848 // Convert condition to a bool by comparing equal to 0.0.
Lang Hames172d7122015-09-18 06:16:49 +0000849 ConstantFP *FPZero =
Lang Hamesd855e452015-02-06 22:52:04 +0000850 ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
851 CondV = C.getBuilder().CreateFCmpONE(CondV, FPZero, "ifcond");
Lang Hames172d7122015-09-18 06:16:49 +0000852
Lang Hamesd855e452015-02-06 22:52:04 +0000853 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
Lang Hames172d7122015-09-18 06:16:49 +0000854
Lang Hamesd855e452015-02-06 22:52:04 +0000855 // Create blocks for the then and else cases. Insert the 'then' block at the
856 // end of the function.
857 BasicBlock *ThenBB = BasicBlock::Create(C.getLLVMContext(), "then", TheFunction);
858 BasicBlock *ElseBB = BasicBlock::Create(C.getLLVMContext(), "else");
859 BasicBlock *MergeBB = BasicBlock::Create(C.getLLVMContext(), "ifcont");
Lang Hames172d7122015-09-18 06:16:49 +0000860
Lang Hamesd855e452015-02-06 22:52:04 +0000861 C.getBuilder().CreateCondBr(CondV, ThenBB, ElseBB);
Lang Hames172d7122015-09-18 06:16:49 +0000862
Lang Hamesd855e452015-02-06 22:52:04 +0000863 // Emit then value.
864 C.getBuilder().SetInsertPoint(ThenBB);
Lang Hames172d7122015-09-18 06:16:49 +0000865
Lang Hamesd855e452015-02-06 22:52:04 +0000866 Value *ThenV = Then->IRGen(C);
867 if (!ThenV) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000868
Lang Hamesd855e452015-02-06 22:52:04 +0000869 C.getBuilder().CreateBr(MergeBB);
870 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
871 ThenBB = C.getBuilder().GetInsertBlock();
Lang Hames172d7122015-09-18 06:16:49 +0000872
Lang Hamesd855e452015-02-06 22:52:04 +0000873 // Emit else block.
874 TheFunction->getBasicBlockList().push_back(ElseBB);
875 C.getBuilder().SetInsertPoint(ElseBB);
Lang Hames172d7122015-09-18 06:16:49 +0000876
Lang Hamesd855e452015-02-06 22:52:04 +0000877 Value *ElseV = Else->IRGen(C);
878 if (!ElseV) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000879
Lang Hamesd855e452015-02-06 22:52:04 +0000880 C.getBuilder().CreateBr(MergeBB);
881 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
882 ElseBB = C.getBuilder().GetInsertBlock();
Lang Hames172d7122015-09-18 06:16:49 +0000883
Lang Hamesd855e452015-02-06 22:52:04 +0000884 // Emit merge block.
885 TheFunction->getBasicBlockList().push_back(MergeBB);
886 C.getBuilder().SetInsertPoint(MergeBB);
Mehdi Amini03b42e42016-04-14 21:59:01 +0000887 PHINode *PN = C.getBuilder().CreatePHI(Type::getDoubleTy(C.getLLVMContext()),
888 2, "iftmp");
Lang Hames172d7122015-09-18 06:16:49 +0000889
Lang Hamesd855e452015-02-06 22:52:04 +0000890 PN->addIncoming(ThenV, ThenBB);
891 PN->addIncoming(ElseV, ElseBB);
892 return PN;
893}
894
David Blaikie055811e2015-02-08 20:15:01 +0000895Value *ForExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000896 // Output this as:
897 // var = alloca double
898 // ...
899 // start = startexpr
900 // store start -> var
901 // goto loop
Lang Hames172d7122015-09-18 06:16:49 +0000902 // loop:
Lang Hamesd855e452015-02-06 22:52:04 +0000903 // ...
904 // bodyexpr
905 // ...
906 // loopend:
907 // step = stepexpr
908 // endcond = endexpr
909 //
910 // curvar = load var
911 // nextvar = curvar + step
912 // store nextvar -> var
913 // br endcond, loop, endloop
914 // outloop:
Lang Hames172d7122015-09-18 06:16:49 +0000915
Lang Hamesd855e452015-02-06 22:52:04 +0000916 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
917
918 // Create an alloca for the variable in the entry block.
919 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Lang Hames172d7122015-09-18 06:16:49 +0000920
Lang Hamesd855e452015-02-06 22:52:04 +0000921 // Emit the start code first, without 'variable' in scope.
922 Value *StartVal = Start->IRGen(C);
923 if (!StartVal) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000924
Lang Hamesd855e452015-02-06 22:52:04 +0000925 // Store the value into the alloca.
926 C.getBuilder().CreateStore(StartVal, Alloca);
Lang Hames172d7122015-09-18 06:16:49 +0000927
Lang Hamesd855e452015-02-06 22:52:04 +0000928 // Make the new basic block for the loop header, inserting after current
929 // block.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000930 BasicBlock *LoopBB =
931 BasicBlock::Create(C.getLLVMContext(), "loop", TheFunction);
Lang Hames172d7122015-09-18 06:16:49 +0000932
Lang Hamesd855e452015-02-06 22:52:04 +0000933 // Insert an explicit fall through from the current block to the LoopBB.
934 C.getBuilder().CreateBr(LoopBB);
935
936 // Start insertion in LoopBB.
937 C.getBuilder().SetInsertPoint(LoopBB);
Lang Hames172d7122015-09-18 06:16:49 +0000938
Lang Hamesd855e452015-02-06 22:52:04 +0000939 // Within the loop, the variable is defined equal to the PHI node. If it
940 // shadows an existing variable, we have to restore it, so save it now.
941 AllocaInst *OldVal = C.NamedValues[VarName];
942 C.NamedValues[VarName] = Alloca;
Lang Hames172d7122015-09-18 06:16:49 +0000943
Lang Hamesd855e452015-02-06 22:52:04 +0000944 // Emit the body of the loop. This, like any other expr, can change the
945 // current BB. Note that we ignore the value computed by the body, but don't
946 // allow an error.
947 if (!Body->IRGen(C))
948 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000949
Lang Hamesd855e452015-02-06 22:52:04 +0000950 // Emit the step value.
951 Value *StepVal;
952 if (Step) {
953 StepVal = Step->IRGen(C);
954 if (!StepVal) return nullptr;
955 } else {
956 // If not specified, use 1.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000957 StepVal = ConstantFP::get(C.getLLVMContext(), APFloat(1.0));
Lang Hamesd855e452015-02-06 22:52:04 +0000958 }
Lang Hames172d7122015-09-18 06:16:49 +0000959
Lang Hamesd855e452015-02-06 22:52:04 +0000960 // Compute the end condition.
961 Value *EndCond = End->IRGen(C);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000962 if (!EndCond) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +0000963
Lang Hamesd855e452015-02-06 22:52:04 +0000964 // Reload, increment, and restore the alloca. This handles the case where
965 // the body of the loop mutates the variable.
966 Value *CurVar = C.getBuilder().CreateLoad(Alloca, VarName.c_str());
967 Value *NextVar = C.getBuilder().CreateFAdd(CurVar, StepVal, "nextvar");
968 C.getBuilder().CreateStore(NextVar, Alloca);
Lang Hames172d7122015-09-18 06:16:49 +0000969
Lang Hamesd855e452015-02-06 22:52:04 +0000970 // Convert condition to a bool by comparing equal to 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000971 EndCond = C.getBuilder().CreateFCmpONE(
972 EndCond, ConstantFP::get(C.getLLVMContext(), APFloat(0.0)), "loopcond");
Lang Hames172d7122015-09-18 06:16:49 +0000973
Lang Hamesd855e452015-02-06 22:52:04 +0000974 // Create the "after loop" block and insert it.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000975 BasicBlock *AfterBB =
976 BasicBlock::Create(C.getLLVMContext(), "afterloop", TheFunction);
Lang Hames172d7122015-09-18 06:16:49 +0000977
Lang Hamesd855e452015-02-06 22:52:04 +0000978 // Insert the conditional branch into the end of LoopEndBB.
979 C.getBuilder().CreateCondBr(EndCond, LoopBB, AfterBB);
Lang Hames172d7122015-09-18 06:16:49 +0000980
Lang Hamesd855e452015-02-06 22:52:04 +0000981 // Any new code will be inserted in AfterBB.
982 C.getBuilder().SetInsertPoint(AfterBB);
Lang Hames172d7122015-09-18 06:16:49 +0000983
Lang Hamesd855e452015-02-06 22:52:04 +0000984 // Restore the unshadowed variable.
985 if (OldVal)
986 C.NamedValues[VarName] = OldVal;
987 else
988 C.NamedValues.erase(VarName);
989
Lang Hamesd855e452015-02-06 22:52:04 +0000990 // for expr always returns 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +0000991 return Constant::getNullValue(Type::getDoubleTy(C.getLLVMContext()));
Lang Hamesd855e452015-02-06 22:52:04 +0000992}
993
David Blaikie055811e2015-02-08 20:15:01 +0000994Value *VarExprAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +0000995 std::vector<AllocaInst *> OldBindings;
Lang Hames172d7122015-09-18 06:16:49 +0000996
Lang Hamesd855e452015-02-06 22:52:04 +0000997 Function *TheFunction = C.getBuilder().GetInsertBlock()->getParent();
998
999 // Register all variables and emit their initializer.
1000 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i) {
1001 auto &VarName = VarBindings[i].first;
1002 auto &Init = VarBindings[i].second;
Lang Hames172d7122015-09-18 06:16:49 +00001003
Lang Hamesd855e452015-02-06 22:52:04 +00001004 // Emit the initializer before adding the variable to scope, this prevents
1005 // the initializer from referencing the variable itself, and permits stuff
1006 // like this:
1007 // var a = 1 in
1008 // var a = a in ... # refers to outer 'a'.
1009 Value *InitVal;
1010 if (Init) {
1011 InitVal = Init->IRGen(C);
1012 if (!InitVal) return nullptr;
1013 } else // If not specified, use 0.0.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001014 InitVal = ConstantFP::get(C.getLLVMContext(), APFloat(0.0));
Lang Hames172d7122015-09-18 06:16:49 +00001015
Lang Hamesd855e452015-02-06 22:52:04 +00001016 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1017 C.getBuilder().CreateStore(InitVal, Alloca);
1018
1019 // Remember the old variable binding so that we can restore the binding when
1020 // we unrecurse.
1021 OldBindings.push_back(C.NamedValues[VarName]);
Lang Hames172d7122015-09-18 06:16:49 +00001022
Lang Hamesd855e452015-02-06 22:52:04 +00001023 // Remember this binding.
1024 C.NamedValues[VarName] = Alloca;
1025 }
Lang Hames172d7122015-09-18 06:16:49 +00001026
Lang Hamesd855e452015-02-06 22:52:04 +00001027 // Codegen the body, now that all vars are in scope.
1028 Value *BodyVal = Body->IRGen(C);
1029 if (!BodyVal) return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +00001030
Lang Hamesd855e452015-02-06 22:52:04 +00001031 // Pop all our variables from scope.
1032 for (unsigned i = 0, e = VarBindings.size(); i != e; ++i)
1033 C.NamedValues[VarBindings[i].first] = OldBindings[i];
1034
1035 // Return the body computation.
1036 return BodyVal;
1037}
1038
David Blaikie055811e2015-02-08 20:15:01 +00001039Function *PrototypeAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +00001040 std::string FnName = MakeLegalFunctionName(Name);
1041
1042 // Make the function type: double(double,double) etc.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001043 std::vector<Type *> Doubles(Args.size(),
1044 Type::getDoubleTy(C.getLLVMContext()));
1045 FunctionType *FT =
1046 FunctionType::get(Type::getDoubleTy(C.getLLVMContext()), Doubles, false);
Lang Hamesd855e452015-02-06 22:52:04 +00001047 Function *F = Function::Create(FT, Function::ExternalLinkage, FnName,
1048 &C.getM());
1049
1050 // If F conflicted, there was already something named 'FnName'. If it has a
1051 // body, don't allow redefinition or reextern.
1052 if (F->getName() != FnName) {
1053 // Delete the one we just made and get the existing one.
1054 F->eraseFromParent();
1055 F = C.getM().getFunction(Name);
Lang Hames172d7122015-09-18 06:16:49 +00001056
Lang Hamesd855e452015-02-06 22:52:04 +00001057 // If F already has a body, reject this.
1058 if (!F->empty()) {
1059 ErrorP<Function>("redefinition of function");
1060 return nullptr;
1061 }
Lang Hames172d7122015-09-18 06:16:49 +00001062
Lang Hamesd855e452015-02-06 22:52:04 +00001063 // If F took a different number of args, reject.
1064 if (F->arg_size() != Args.size()) {
1065 ErrorP<Function>("redefinition of function with different # args");
1066 return nullptr;
1067 }
1068 }
Lang Hames172d7122015-09-18 06:16:49 +00001069
Lang Hamesd855e452015-02-06 22:52:04 +00001070 // Set names for all arguments.
1071 unsigned Idx = 0;
1072 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1073 ++AI, ++Idx)
1074 AI->setName(Args[Idx]);
Lang Hames172d7122015-09-18 06:16:49 +00001075
Lang Hamesd855e452015-02-06 22:52:04 +00001076 return F;
1077}
1078
1079/// CreateArgumentAllocas - Create an alloca for each argument and register the
1080/// argument in the symbol table so that references to it will succeed.
1081void PrototypeAST::CreateArgumentAllocas(Function *F, IRGenContext &C) {
1082 Function::arg_iterator AI = F->arg_begin();
1083 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1084 // Create an alloca for this variable.
1085 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1086
1087 // Store the initial value into the alloca.
Duncan P. N. Exon Smith5717ecb2015-11-07 00:55:46 +00001088 C.getBuilder().CreateStore(&*AI, Alloca);
Lang Hamesd855e452015-02-06 22:52:04 +00001089
1090 // Add arguments to variable symbol table.
1091 C.NamedValues[Args[Idx]] = Alloca;
1092 }
1093}
1094
David Blaikie055811e2015-02-08 20:15:01 +00001095Function *FunctionAST::IRGen(IRGenContext &C) const {
Lang Hamesd855e452015-02-06 22:52:04 +00001096 C.NamedValues.clear();
Lang Hames172d7122015-09-18 06:16:49 +00001097
Lang Hamesd855e452015-02-06 22:52:04 +00001098 Function *TheFunction = Proto->IRGen(C);
1099 if (!TheFunction)
1100 return nullptr;
Lang Hames172d7122015-09-18 06:16:49 +00001101
Lang Hamesd855e452015-02-06 22:52:04 +00001102 // If this is an operator, install it.
1103 if (Proto->isBinaryOp())
1104 BinopPrecedence[Proto->getOperatorName()] = Proto->Precedence;
Lang Hames172d7122015-09-18 06:16:49 +00001105
Lang Hamesd855e452015-02-06 22:52:04 +00001106 // Create a new basic block to start insertion into.
Mehdi Amini03b42e42016-04-14 21:59:01 +00001107 BasicBlock *BB = BasicBlock::Create(C.getLLVMContext(), "entry", TheFunction);
Lang Hamesd855e452015-02-06 22:52:04 +00001108 C.getBuilder().SetInsertPoint(BB);
Lang Hames172d7122015-09-18 06:16:49 +00001109
Lang Hamesd855e452015-02-06 22:52:04 +00001110 // Add all arguments to the symbol table and create their allocas.
1111 Proto->CreateArgumentAllocas(TheFunction, C);
1112
1113 if (Value *RetVal = Body->IRGen(C)) {
1114 // Finish off the function.
1115 C.getBuilder().CreateRet(RetVal);
1116
1117 // Validate the generated code, checking for consistency.
1118 verifyFunction(*TheFunction);
1119
1120 return TheFunction;
1121 }
Lang Hames172d7122015-09-18 06:16:49 +00001122
Lang Hamesd855e452015-02-06 22:52:04 +00001123 // Error reading body, remove function.
1124 TheFunction->eraseFromParent();
1125
1126 if (Proto->isBinaryOp())
1127 BinopPrecedence.erase(Proto->getOperatorName());
1128 return nullptr;
1129}
1130
1131//===----------------------------------------------------------------------===//
1132// Top-Level parsing and JIT Driver
1133//===----------------------------------------------------------------------===//
1134
David Blaikie9c4c23b2015-02-08 21:03:30 +00001135static std::unique_ptr<llvm::Module> IRGen(SessionContext &S,
1136 const FunctionAST &F) {
David Blaikie1803dc22015-02-08 20:29:28 +00001137 IRGenContext C(S);
1138 auto LF = F.IRGen(C);
1139 if (!LF)
1140 return nullptr;
1141#ifndef MINIMAL_STDERR_OUTPUT
1142 fprintf(stderr, "Read function definition:");
1143 LF->dump();
1144#endif
1145 return C.takeM();
1146}
1147
Lang Hames0db567f2015-02-25 20:58:28 +00001148template <typename T>
1149static std::vector<T> singletonSet(T t) {
1150 std::vector<T> Vec;
1151 Vec.push_back(std::move(t));
1152 return Vec;
1153}
1154
1155class KaleidoscopeJIT {
1156public:
1157 typedef ObjectLinkingLayer<> ObjLayerT;
1158 typedef IRCompileLayer<ObjLayerT> CompileLayerT;
1159 typedef CompileLayerT::ModuleSetHandleT ModuleHandleT;
1160
1161 KaleidoscopeJIT(SessionContext &Session)
Mehdi Amini26d48132015-07-24 16:04:22 +00001162 : DL(Session.getTarget().createDataLayout()),
Rafael Espindolac233f742015-06-23 13:59:29 +00001163 CompileLayer(ObjectLayer, SimpleCompiler(Session.getTarget())) {}
Lang Hames0db567f2015-02-25 20:58:28 +00001164
1165 std::string mangle(const std::string &Name) {
1166 std::string MangledName;
1167 {
1168 raw_string_ostream MangledNameStream(MangledName);
Rafael Espindolac233f742015-06-23 13:59:29 +00001169 Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
Lang Hames0db567f2015-02-25 20:58:28 +00001170 }
1171 return MangledName;
1172 }
1173
1174 ModuleHandleT addModule(std::unique_ptr<Module> M) {
1175 // We need a memory manager to allocate memory and resolve symbols for this
1176 // new module. Create one that resolves symbols by looking back into the
1177 // JIT.
Lang Hames633fe142015-03-30 03:37:06 +00001178 auto Resolver = createLambdaResolver(
1179 [&](const std::string &Name) {
1180 if (auto Sym = findSymbol(Name))
1181 return RuntimeDyld::SymbolInfo(Sym.getAddress(),
1182 Sym.getFlags());
1183 return RuntimeDyld::SymbolInfo(nullptr);
1184 },
1185 [](const std::string &S) { return nullptr; }
1186 );
1187 return CompileLayer.addModuleSet(singletonSet(std::move(M)),
1188 make_unique<SectionMemoryManager>(),
1189 std::move(Resolver));
Lang Hames0db567f2015-02-25 20:58:28 +00001190 }
1191
1192 void removeModule(ModuleHandleT H) { CompileLayer.removeModuleSet(H); }
1193
1194 JITSymbol findSymbol(const std::string &Name) {
1195 return CompileLayer.findSymbol(Name, true);
1196 }
1197
1198 JITSymbol findUnmangledSymbol(const std::string Name) {
1199 return findSymbol(mangle(Name));
1200 }
1201
1202private:
Mehdi Amini26d48132015-07-24 16:04:22 +00001203 const DataLayout DL;
Lang Hames0db567f2015-02-25 20:58:28 +00001204 ObjLayerT ObjectLayer;
1205 CompileLayerT CompileLayer;
1206};
1207
Lang Hamesd855e452015-02-06 22:52:04 +00001208static void HandleDefinition(SessionContext &S, KaleidoscopeJIT &J) {
1209 if (auto F = ParseDefinition()) {
David Blaikie9c4c23b2015-02-08 21:03:30 +00001210 if (auto M = IRGen(S, *F)) {
Lang Hamesd855e452015-02-06 22:52:04 +00001211 S.addPrototypeAST(llvm::make_unique<PrototypeAST>(*F->Proto));
David Blaikie1803dc22015-02-08 20:29:28 +00001212 J.addModule(std::move(M));
Lang Hamesd855e452015-02-06 22:52:04 +00001213 }
1214 } else {
1215 // Skip token for error recovery.
1216 getNextToken();
1217 }
1218}
1219
1220static void HandleExtern(SessionContext &S) {
1221 if (auto P = ParseExtern())
1222 S.addPrototypeAST(std::move(P));
1223 else {
1224 // Skip token for error recovery.
1225 getNextToken();
1226 }
1227}
1228
1229static void HandleTopLevelExpression(SessionContext &S, KaleidoscopeJIT &J) {
1230 // Evaluate a top-level expression into an anonymous function.
1231 if (auto F = ParseTopLevelExpr()) {
1232 IRGenContext C(S);
1233 if (auto ExprFunc = F->IRGen(C)) {
1234#ifndef MINIMAL_STDERR_OUTPUT
Lang Hamesbe9df342015-02-08 19:14:56 +00001235 std::cerr << "Expression function:\n";
Lang Hamesd855e452015-02-06 22:52:04 +00001236 ExprFunc->dump();
1237#endif
1238 // Add the CodeGen'd module to the JIT. Keep a handle to it: We can remove
1239 // this module as soon as we've executed Function ExprFunc.
1240 auto H = J.addModule(C.takeM());
1241
1242 // Get the address of the JIT'd function in memory.
Lang Hames0db567f2015-02-25 20:58:28 +00001243 auto ExprSymbol = J.findUnmangledSymbol("__anon_expr");
Lang Hames172d7122015-09-18 06:16:49 +00001244
Lang Hamesd855e452015-02-06 22:52:04 +00001245 // Cast it to the right type (takes no arguments, returns a double) so we
1246 // can call it as a native function.
Lang Hames114b4f32015-02-09 01:20:51 +00001247 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Lang Hamesd855e452015-02-06 22:52:04 +00001248#ifdef MINIMAL_STDERR_OUTPUT
1249 FP();
1250#else
Lang Hamesbe9df342015-02-08 19:14:56 +00001251 std::cerr << "Evaluated to " << FP() << "\n";
Lang Hamesd855e452015-02-06 22:52:04 +00001252#endif
1253
1254 // Remove the function.
1255 J.removeModule(H);
1256 }
1257 } else {
1258 // Skip token for error recovery.
1259 getNextToken();
1260 }
1261}
1262
1263/// top ::= definition | external | expression | ';'
1264static void MainLoop() {
Mehdi Amini03b42e42016-04-14 21:59:01 +00001265 LLVMContext TheContext;
1266 SessionContext S(TheContext);
Lang Hames0db567f2015-02-25 20:58:28 +00001267 KaleidoscopeJIT J(S);
Lang Hamesd855e452015-02-06 22:52:04 +00001268
1269 while (1) {
Lang Hamesd855e452015-02-06 22:52:04 +00001270 switch (CurTok) {
1271 case tok_eof: return;
Lang Hames31ab4952015-02-17 05:36:59 +00001272 case ';': getNextToken(); continue; // ignore top-level semicolons.
Lang Hamesd855e452015-02-06 22:52:04 +00001273 case tok_def: HandleDefinition(S, J); break;
1274 case tok_extern: HandleExtern(S); break;
1275 default: HandleTopLevelExpression(S, J); break;
1276 }
Lang Hames31ab4952015-02-17 05:36:59 +00001277#ifndef MINIMAL_STDERR_OUTPUT
1278 std::cerr << "ready> ";
1279#endif
Lang Hamesd855e452015-02-06 22:52:04 +00001280 }
1281}
1282
1283//===----------------------------------------------------------------------===//
1284// "Library" functions that can be "extern'd" from user code.
1285//===----------------------------------------------------------------------===//
1286
1287/// putchard - putchar that takes a double and returns 0.
Lang Hames172d7122015-09-18 06:16:49 +00001288extern "C"
Lang Hamesd855e452015-02-06 22:52:04 +00001289double putchard(double X) {
1290 putchar((char)X);
1291 return 0;
1292}
1293
1294/// printd - printf that takes a double prints it as "%f\n", returning 0.
Lang Hames172d7122015-09-18 06:16:49 +00001295extern "C"
Lang Hamesd855e452015-02-06 22:52:04 +00001296double printd(double X) {
1297 printf("%f", X);
1298 return 0;
1299}
1300
Lang Hames172d7122015-09-18 06:16:49 +00001301extern "C"
Lang Hamesd855e452015-02-06 22:52:04 +00001302double printlf() {
1303 printf("\n");
1304 return 0;
1305}
1306
1307//===----------------------------------------------------------------------===//
1308// Main driver code.
1309//===----------------------------------------------------------------------===//
1310
1311int main() {
1312 InitializeNativeTarget();
1313 InitializeNativeTargetAsmPrinter();
1314 InitializeNativeTargetAsmParser();
Lang Hamesd855e452015-02-06 22:52:04 +00001315
1316 // Install standard binary operators.
1317 // 1 is lowest precedence.
1318 BinopPrecedence['='] = 2;
1319 BinopPrecedence['<'] = 10;
1320 BinopPrecedence['+'] = 20;
1321 BinopPrecedence['-'] = 20;
1322 BinopPrecedence['/'] = 40;
1323 BinopPrecedence['*'] = 40; // highest.
1324
1325 // Prime the first token.
1326#ifndef MINIMAL_STDERR_OUTPUT
Lang Hamesbe9df342015-02-08 19:14:56 +00001327 std::cerr << "ready> ";
Lang Hamesd855e452015-02-06 22:52:04 +00001328#endif
1329 getNextToken();
1330
Lang Hamesbe9df342015-02-08 19:14:56 +00001331 std::cerr << std::fixed;
1332
Lang Hamesd855e452015-02-06 22:52:04 +00001333 // Run the main "interpreter loop" now.
1334 MainLoop();
1335
1336 return 0;
1337}