blob: 8c96444ad4049532ecd786736f204ed9d7194707 [file] [log] [blame]
Lang Hames09bf4c12015-08-18 18:11:06 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00002#include "llvm/Analysis/Passes.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00003#include "llvm/IR/IRBuilder.h"
4#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +00005#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00006#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +00007#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +00008#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00009#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000010#include <cctype>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000011#include <cstdio>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000012#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000013#include <string>
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000014#include <vector>
Lang Hames2d789c32015-08-26 03:07:41 +000015#include "../include/KaleidoscopeJIT.h"
16
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000017using namespace llvm;
Lang Hames2d789c32015-08-26 03:07:41 +000018using namespace llvm::orc;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000019
20//===----------------------------------------------------------------------===//
21// Lexer
22//===----------------------------------------------------------------------===//
23
24// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25// of these for known things.
26enum Token {
27 tok_eof = -1,
28
29 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000030 tok_def = -2,
31 tok_extern = -3,
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000032
33 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000034 tok_identifier = -4,
35 tok_number = -5
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000036};
37
Eric Christopherc0239362014-12-08 18:12:28 +000038static std::string IdentifierStr; // Filled in if tok_identifier
39static double NumVal; // Filled in if tok_number
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000040
41/// gettok - Return the next token from standard input.
42static int gettok() {
43 static int LastChar = ' ';
44
45 // Skip any whitespace.
46 while (isspace(LastChar))
47 LastChar = getchar();
48
49 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
50 IdentifierStr = LastChar;
51 while (isalnum((LastChar = getchar())))
52 IdentifierStr += LastChar;
53
Eric Christopherc0239362014-12-08 18:12:28 +000054 if (IdentifierStr == "def")
55 return tok_def;
56 if (IdentifierStr == "extern")
57 return tok_extern;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000058 return tok_identifier;
59 }
60
Eric Christopherc0239362014-12-08 18:12:28 +000061 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000062 std::string NumStr;
63 do {
64 NumStr += LastChar;
65 LastChar = getchar();
66 } while (isdigit(LastChar) || LastChar == '.');
67
68 NumVal = strtod(NumStr.c_str(), 0);
69 return tok_number;
70 }
71
72 if (LastChar == '#') {
73 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +000074 do
75 LastChar = getchar();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000076 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +000077
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000078 if (LastChar != EOF)
79 return gettok();
80 }
Eric Christopherc0239362014-12-08 18:12:28 +000081
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000082 // Check for end of file. Don't eat the EOF.
83 if (LastChar == EOF)
84 return tok_eof;
85
86 // Otherwise, just return the character as its ascii value.
87 int ThisChar = LastChar;
88 LastChar = getchar();
89 return ThisChar;
90}
91
92//===----------------------------------------------------------------------===//
93// Abstract Syntax Tree (aka Parse Tree)
94//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +000095namespace {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +000096/// ExprAST - Base class for all expression nodes.
97class ExprAST {
98public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +000099 virtual ~ExprAST() {}
Lang Hames2d789c32015-08-26 03:07:41 +0000100 virtual Value *codegen() = 0;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000101};
102
103/// NumberExprAST - Expression class for numeric literals like "1.0".
104class NumberExprAST : public ExprAST {
105 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000106
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000107public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000108 NumberExprAST(double Val) : Val(Val) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000109 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000110};
111
112/// VariableExprAST - Expression class for referencing a variable, like "a".
113class VariableExprAST : public ExprAST {
114 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000115
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000116public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000117 VariableExprAST(const std::string &Name) : Name(Name) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000118 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000119};
120
121/// BinaryExprAST - Expression class for a binary operator.
122class BinaryExprAST : public ExprAST {
123 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000124 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000125
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000126public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000127 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
128 std::unique_ptr<ExprAST> RHS)
129 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000130 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000131};
132
133/// CallExprAST - Expression class for function calls.
134class CallExprAST : public ExprAST {
135 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000136 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000137
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000138public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000139 CallExprAST(const std::string &Callee,
140 std::vector<std::unique_ptr<ExprAST>> Args)
141 : Callee(Callee), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000142 Value *codegen() override;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000143};
144
145/// PrototypeAST - This class represents the "prototype" for a function,
146/// which captures its name, and its argument names (thus implicitly the number
147/// of arguments the function takes).
148class PrototypeAST {
149 std::string Name;
150 std::vector<std::string> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000151
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000152public:
Lang Hames59b0da82015-08-19 18:15:58 +0000153 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
154 : Name(Name), Args(std::move(Args)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000155 Function *codegen();
156 const std::string &getName() const { return Name; }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000157};
158
159/// FunctionAST - This class represents a function definition itself.
160class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000161 std::unique_ptr<PrototypeAST> Proto;
162 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000163
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000164public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000165 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
166 std::unique_ptr<ExprAST> Body)
Lang Hames59b0da82015-08-19 18:15:58 +0000167 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Lang Hames2d789c32015-08-26 03:07:41 +0000168 Function *codegen();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000169};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000170} // end anonymous namespace
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000171
172//===----------------------------------------------------------------------===//
173// Parser
174//===----------------------------------------------------------------------===//
175
176/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
177/// token the parser is looking at. getNextToken reads another token from the
178/// lexer and updates CurTok with its results.
179static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000180static int getNextToken() { return CurTok = gettok(); }
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000181
182/// BinopPrecedence - This holds the precedence for each binary operator that is
183/// defined.
184static std::map<char, int> BinopPrecedence;
185
186/// GetTokPrecedence - Get the precedence of the pending binary operator token.
187static int GetTokPrecedence() {
188 if (!isascii(CurTok))
189 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000190
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000191 // Make sure it's a declared binop.
192 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000193 if (TokPrec <= 0)
194 return -1;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000195 return TokPrec;
196}
197
198/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000199std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000200 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000201 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000202}
Lang Hames09bf4c12015-08-18 18:11:06 +0000203std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000204 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000205 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000206}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000207
Lang Hames09bf4c12015-08-18 18:11:06 +0000208static std::unique_ptr<ExprAST> ParseExpression();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000209
Lang Hames59b0da82015-08-19 18:15:58 +0000210/// numberexpr ::= number
211static std::unique_ptr<ExprAST> ParseNumberExpr() {
212 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
213 getNextToken(); // consume the number
214 return std::move(Result);
215}
216
217/// parenexpr ::= '(' expression ')'
218static std::unique_ptr<ExprAST> ParseParenExpr() {
219 getNextToken(); // eat (.
220 auto V = ParseExpression();
221 if (!V)
222 return nullptr;
223
224 if (CurTok != ')')
225 return Error("expected ')'");
226 getNextToken(); // eat ).
227 return V;
228}
229
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000230/// identifierexpr
231/// ::= identifier
232/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000233static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000234 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000235
236 getNextToken(); // eat identifier.
237
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000238 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000239 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000240
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000241 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000242 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000243 std::vector<std::unique_ptr<ExprAST>> Args;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000244 if (CurTok != ')') {
245 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000246 if (auto Arg = ParseExpression())
247 Args.push_back(std::move(Arg));
248 else
249 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000250
Eric Christopherc0239362014-12-08 18:12:28 +0000251 if (CurTok == ')')
252 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000253
254 if (CurTok != ',')
255 return Error("Expected ')' or ',' in argument list");
256 getNextToken();
257 }
258 }
259
260 // Eat the ')'.
261 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000262
Lang Hames09bf4c12015-08-18 18:11:06 +0000263 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000264}
265
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000266/// primary
267/// ::= identifierexpr
268/// ::= numberexpr
269/// ::= parenexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000270static std::unique_ptr<ExprAST> ParsePrimary() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000271 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000272 default:
273 return Error("unknown token when expecting an expression");
274 case tok_identifier:
275 return ParseIdentifierExpr();
276 case tok_number:
277 return ParseNumberExpr();
278 case '(':
279 return ParseParenExpr();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000280 }
281}
282
283/// binoprhs
284/// ::= ('+' primary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000285static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
286 std::unique_ptr<ExprAST> LHS) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000287 // If this is a binop, find its precedence.
288 while (1) {
289 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000290
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000291 // If this is a binop that binds at least as tightly as the current binop,
292 // consume it, otherwise we are done.
293 if (TokPrec < ExprPrec)
294 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000295
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000296 // Okay, we know this is a binop.
297 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000298 getNextToken(); // eat binop
299
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000300 // Parse the primary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000301 auto RHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000302 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000303 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000304
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000305 // If BinOp binds less tightly with RHS than the operator after RHS, let
306 // the pending operator take RHS as its LHS.
307 int NextPrec = GetTokPrecedence();
308 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000309 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
310 if (!RHS)
311 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000312 }
Eric Christopherc0239362014-12-08 18:12:28 +0000313
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000314 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000315 LHS =
316 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000317 }
318}
319
320/// expression
321/// ::= primary binoprhs
322///
Lang Hames09bf4c12015-08-18 18:11:06 +0000323static std::unique_ptr<ExprAST> ParseExpression() {
324 auto LHS = ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000325 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000326 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000327
Lang Hames09bf4c12015-08-18 18:11:06 +0000328 return ParseBinOpRHS(0, std::move(LHS));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000329}
330
331/// prototype
332/// ::= id '(' id* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000333static std::unique_ptr<PrototypeAST> ParsePrototype() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000334 if (CurTok != tok_identifier)
335 return ErrorP("Expected function name in prototype");
336
337 std::string FnName = IdentifierStr;
338 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000339
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000340 if (CurTok != '(')
341 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000342
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000343 std::vector<std::string> ArgNames;
344 while (getNextToken() == tok_identifier)
345 ArgNames.push_back(IdentifierStr);
346 if (CurTok != ')')
347 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000348
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000349 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000350 getNextToken(); // eat ')'.
351
Lang Hames09bf4c12015-08-18 18:11:06 +0000352 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000353}
354
355/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000356static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000357 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000358 auto Proto = ParsePrototype();
359 if (!Proto)
360 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000361
Lang Hames09bf4c12015-08-18 18:11:06 +0000362 if (auto E = ParseExpression())
363 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
364 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000365}
366
367/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000368static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
369 if (auto E = ParseExpression()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000370 // Make an anonymous proto.
Lang Hames2d789c32015-08-26 03:07:41 +0000371 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
372 std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000373 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000374 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000375 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000376}
377
378/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000379static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000380 getNextToken(); // eat extern.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000381 return ParsePrototype();
382}
383
384//===----------------------------------------------------------------------===//
385// Code Generation
386//===----------------------------------------------------------------------===//
387
Lang Hames2d789c32015-08-26 03:07:41 +0000388static std::unique_ptr<Module> TheModule;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000389static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000390static std::map<std::string, Value *> NamedValues;
Lang Hames2d789c32015-08-26 03:07:41 +0000391static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
392static std::unique_ptr<KaleidoscopeJIT> TheJIT;
393static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000394
Eric Christopherc0239362014-12-08 18:12:28 +0000395Value *ErrorV(const char *Str) {
396 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000397 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000398}
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000399
Lang Hames2d789c32015-08-26 03:07:41 +0000400Function *getFunction(std::string Name) {
401 // First, see if the function has already been added to the current module.
402 if (auto *F = TheModule->getFunction(Name))
403 return F;
404
405 // If not, check whether we can codegen the declaration from some existing
406 // prototype.
407 auto FI = FunctionProtos.find(Name);
408 if (FI != FunctionProtos.end())
409 return FI->second->codegen();
410
411 // If no existing prototype exists, return null.
412 return nullptr;
413}
414
415Value *NumberExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000416 return ConstantFP::get(getGlobalContext(), APFloat(Val));
417}
418
Lang Hames2d789c32015-08-26 03:07:41 +0000419Value *VariableExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000420 // Look this variable up in the function.
421 Value *V = NamedValues[Name];
Lang Hames596aec92015-08-19 18:32:58 +0000422 if (!V)
423 return ErrorV("Unknown variable name");
424 return V;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000425}
426
Lang Hames2d789c32015-08-26 03:07:41 +0000427Value *BinaryExprAST::codegen() {
428 Value *L = LHS->codegen();
429 Value *R = RHS->codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000430 if (!L || !R)
431 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000432
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000433 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000434 case '+':
435 return Builder.CreateFAdd(L, R, "addtmp");
436 case '-':
437 return Builder.CreateFSub(L, R, "subtmp");
438 case '*':
439 return Builder.CreateFMul(L, R, "multmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000440 case '<':
441 L = Builder.CreateFCmpULT(L, R, "cmptmp");
442 // Convert bool 0/1 to double 0.0 or 1.0
443 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
444 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000445 default:
446 return ErrorV("invalid binary operator");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000447 }
448}
449
Lang Hames2d789c32015-08-26 03:07:41 +0000450Value *CallExprAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000451 // Look up the name in the global module table.
Lang Hames2d789c32015-08-26 03:07:41 +0000452 Function *CalleeF = getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000453 if (!CalleeF)
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000454 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000455
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000456 // If argument mismatch error.
457 if (CalleeF->arg_size() != Args.size())
458 return ErrorV("Incorrect # arguments passed");
459
Eric Christopherc0239362014-12-08 18:12:28 +0000460 std::vector<Value *> ArgsV;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000461 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Lang Hames2d789c32015-08-26 03:07:41 +0000462 ArgsV.push_back(Args[i]->codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000463 if (!ArgsV.back())
464 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000465 }
Eric Christopherc0239362014-12-08 18:12:28 +0000466
Francois Pichetc5d10502011-07-15 10:59:52 +0000467 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000468}
469
Lang Hames2d789c32015-08-26 03:07:41 +0000470Function *PrototypeAST::codegen() {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000471 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000472 std::vector<Type *> Doubles(Args.size(),
473 Type::getDoubleTy(getGlobalContext()));
474 FunctionType *FT =
475 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
476
Lang Hames2d789c32015-08-26 03:07:41 +0000477 Function *F =
478 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
Eric Christopherc0239362014-12-08 18:12:28 +0000479
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000480 // Set names for all arguments.
481 unsigned Idx = 0;
Lang Hames2d789c32015-08-26 03:07:41 +0000482 for (auto &Arg : F->args())
483 Arg.setName(Args[Idx++]);
Eric Christopherc0239362014-12-08 18:12:28 +0000484
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000485 return F;
486}
487
Lang Hames2d789c32015-08-26 03:07:41 +0000488Function *FunctionAST::codegen() {
489 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
490 // reference to it for use below.
491 auto &P = *Proto;
492 FunctionProtos[Proto->getName()] = std::move(Proto);
493 Function *TheFunction = getFunction(P.getName());
Lang Hames09bf4c12015-08-18 18:11:06 +0000494 if (!TheFunction)
495 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000496
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000497 // Create a new basic block to start insertion into.
498 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
499 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +0000500
Lang Hames2d789c32015-08-26 03:07:41 +0000501 // Record the function arguments in the NamedValues map.
502 NamedValues.clear();
503 for (auto &Arg : TheFunction->args())
504 NamedValues[Arg.getName()] = &Arg;
505
506 if (Value *RetVal = Body->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000507 // Finish off the function.
508 Builder.CreateRet(RetVal);
509
510 // Validate the generated code, checking for consistency.
511 verifyFunction(*TheFunction);
512
Lang Hames2d789c32015-08-26 03:07:41 +0000513 // Run the optimizer on the function.
514 TheFPM->run(*TheFunction);
515
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000516 return TheFunction;
517 }
Eric Christopherc0239362014-12-08 18:12:28 +0000518
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000519 // Error reading body, remove function.
520 TheFunction->eraseFromParent();
Lang Hames09bf4c12015-08-18 18:11:06 +0000521 return nullptr;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000522}
523
524//===----------------------------------------------------------------------===//
525// Top-Level parsing and JIT Driver
526//===----------------------------------------------------------------------===//
527
Lang Hames2d789c32015-08-26 03:07:41 +0000528static void InitializeModuleAndPassManager() {
529 // Open a new module.
530 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
531 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
532
533 // Create a new pass manager attached to it.
534 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
535
Lang Hames2d789c32015-08-26 03:07:41 +0000536 // Do simple "peephole" optimizations and bit-twiddling optzns.
537 TheFPM->add(createInstructionCombiningPass());
538 // Reassociate expressions.
539 TheFPM->add(createReassociatePass());
540 // Eliminate Common SubExpressions.
541 TheFPM->add(createGVNPass());
542 // Simplify the control flow graph (deleting unreachable blocks, etc).
543 TheFPM->add(createCFGSimplificationPass());
544
545 TheFPM->doInitialization();
546}
547
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000548static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000549 if (auto FnAST = ParseDefinition()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000550 if (auto *FnIR = FnAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000551 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +0000552 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000553 TheJIT->addModule(std::move(TheModule));
554 InitializeModuleAndPassManager();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000555 }
556 } else {
557 // Skip token for error recovery.
558 getNextToken();
559 }
560}
561
562static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +0000563 if (auto ProtoAST = ParseExtern()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000564 if (auto *FnIR = ProtoAST->codegen()) {
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000565 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +0000566 FnIR->dump();
Lang Hames2d789c32015-08-26 03:07:41 +0000567 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000568 }
569 } else {
570 // Skip token for error recovery.
571 getNextToken();
572 }
573}
574
575static void HandleTopLevelExpression() {
576 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +0000577 if (auto FnAST = ParseTopLevelExpr()) {
Lang Hames2d789c32015-08-26 03:07:41 +0000578 if (FnAST->codegen()) {
Eric Christopherc0239362014-12-08 18:12:28 +0000579
Lang Hames2d789c32015-08-26 03:07:41 +0000580 // JIT the module containing the anonymous expression, keeping a handle so
581 // we can free it later.
582 auto H = TheJIT->addModule(std::move(TheModule));
583 InitializeModuleAndPassManager();
584
585 // Search the JIT for the __anon_expr symbol.
586 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
587 assert(ExprSymbol && "Function not found");
588
589 // Get the symbol's address and cast it to the right type (takes no
590 // arguments, returns a double) so we can call it as a native function.
591 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000592 fprintf(stderr, "Evaluated to %f\n", FP());
Lang Hames2d789c32015-08-26 03:07:41 +0000593
594 // Delete the anonymous expression module from the JIT.
595 TheJIT->removeModule(H);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000596 }
597 } else {
598 // Skip token for error recovery.
599 getNextToken();
600 }
601}
602
603/// top ::= definition | external | expression | ';'
604static void MainLoop() {
605 while (1) {
606 fprintf(stderr, "ready> ");
607 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000608 case tok_eof:
609 return;
Lang Hames59b0da82015-08-19 18:15:58 +0000610 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +0000611 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +0000612 break;
Eric Christopherc0239362014-12-08 18:12:28 +0000613 case tok_def:
614 HandleDefinition();
615 break;
616 case tok_extern:
617 HandleExtern();
618 break;
619 default:
620 HandleTopLevelExpression();
621 break;
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000622 }
623 }
624}
625
626//===----------------------------------------------------------------------===//
627// "Library" functions that can be "extern'd" from user code.
628//===----------------------------------------------------------------------===//
629
630/// putchard - putchar that takes a double and returns 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +0000631extern "C" double putchard(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +0000632 fputc((char)X, stderr);
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000633 return 0;
634}
635
Lang Hames59b0da82015-08-19 18:15:58 +0000636/// printd - printf that takes a double prints it as "%f\n", returning 0.
NAKAMURA Takumiac9d3732015-08-28 03:34:33 +0000637extern "C" double printd(double X) {
Lang Hamesd76e0672015-08-27 20:31:44 +0000638 fprintf(stderr, "%f\n", X);
Lang Hames59b0da82015-08-19 18:15:58 +0000639 return 0;
640}
641
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000642//===----------------------------------------------------------------------===//
643// Main driver code.
644//===----------------------------------------------------------------------===//
645
646int main() {
647 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +0000648 InitializeNativeTargetAsmPrinter();
649 InitializeNativeTargetAsmParser();
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000650
651 // Install standard binary operators.
652 // 1 is lowest precedence.
653 BinopPrecedence['<'] = 10;
654 BinopPrecedence['+'] = 20;
655 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +0000656 BinopPrecedence['*'] = 40; // highest.
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000657
658 // Prime the first token.
659 fprintf(stderr, "ready> ");
660 getNextToken();
661
Lang Hames2d789c32015-08-26 03:07:41 +0000662 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
663
664 InitializeModuleAndPassManager();
665
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000666 // Run the main "interpreter loop" now.
667 MainLoop();
668
Erick Tryzelaar21e83ea2009-09-22 21:15:19 +0000669 return 0;
670}