blob: a900c5f7b16f3039e6b74b0e6da8867f5f6bdcca [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Chandler Carruth17e0bc32015-08-06 07:33:15 +00002#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +00003#include "llvm/Analysis/Passes.h"
Nick Lewycky109af622009-04-12 20:47:23 +00004#include "llvm/ExecutionEngine/ExecutionEngine.h"
Eric Christopher1b74b652014-12-08 18:00:38 +00005#include "llvm/ExecutionEngine/MCJIT.h"
6#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +00007#include "llvm/IR/DataLayout.h"
8#include "llvm/IR/DerivedTypes.h"
9#include "llvm/IR/IRBuilder.h"
10#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000011#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth005f27a2013-01-02 11:56:33 +000012#include "llvm/IR/Module.h"
Chandler Carruth20d4e6b2014-01-13 09:58:03 +000013#include "llvm/IR/Verifier.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000014#include "llvm/Support/TargetSelect.h"
Chandler Carruth605e30e2012-12-04 10:16:57 +000015#include "llvm/Transforms/Scalar.h"
Will Dietz981af002013-10-12 00:55:57 +000016#include <cctype>
Nick Lewycky109af622009-04-12 20:47:23 +000017#include <cstdio>
Nick Lewycky109af622009-04-12 20:47:23 +000018#include <map>
Chandler Carruth605e30e2012-12-04 10:16:57 +000019#include <string>
Nick Lewycky109af622009-04-12 20:47:23 +000020#include <vector>
21using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// Lexer
25//===----------------------------------------------------------------------===//
26
27// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28// of these for known things.
29enum Token {
30 tok_eof = -1,
31
32 // commands
Eric Christopherc0239362014-12-08 18:12:28 +000033 tok_def = -2,
34 tok_extern = -3,
Nick Lewycky109af622009-04-12 20:47:23 +000035
36 // primary
Eric Christopherc0239362014-12-08 18:12:28 +000037 tok_identifier = -4,
38 tok_number = -5,
39
Nick Lewycky109af622009-04-12 20:47:23 +000040 // control
Eric Christopherc0239362014-12-08 18:12:28 +000041 tok_if = -6,
42 tok_then = -7,
43 tok_else = -8,
44 tok_for = -9,
45 tok_in = -10,
46
Nick Lewycky109af622009-04-12 20:47:23 +000047 // operators
Eric Christopherc0239362014-12-08 18:12:28 +000048 tok_binary = -11,
49 tok_unary = -12,
50
Nick Lewycky109af622009-04-12 20:47:23 +000051 // var definition
52 tok_var = -13
53};
54
Eric Christopherc0239362014-12-08 18:12:28 +000055static std::string IdentifierStr; // Filled in if tok_identifier
56static double NumVal; // Filled in if tok_number
Nick Lewycky109af622009-04-12 20:47:23 +000057
58/// gettok - Return the next token from standard input.
59static int gettok() {
60 static int LastChar = ' ';
61
62 // Skip any whitespace.
63 while (isspace(LastChar))
64 LastChar = getchar();
65
66 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
67 IdentifierStr = LastChar;
68 while (isalnum((LastChar = getchar())))
69 IdentifierStr += LastChar;
70
Eric Christopherc0239362014-12-08 18:12:28 +000071 if (IdentifierStr == "def")
72 return tok_def;
73 if (IdentifierStr == "extern")
74 return tok_extern;
75 if (IdentifierStr == "if")
76 return tok_if;
77 if (IdentifierStr == "then")
78 return tok_then;
79 if (IdentifierStr == "else")
80 return tok_else;
81 if (IdentifierStr == "for")
82 return tok_for;
83 if (IdentifierStr == "in")
84 return tok_in;
85 if (IdentifierStr == "binary")
86 return tok_binary;
87 if (IdentifierStr == "unary")
88 return tok_unary;
89 if (IdentifierStr == "var")
90 return tok_var;
Nick Lewycky109af622009-04-12 20:47:23 +000091 return tok_identifier;
92 }
93
Eric Christopherc0239362014-12-08 18:12:28 +000094 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
Nick Lewycky109af622009-04-12 20:47:23 +000095 std::string NumStr;
96 do {
97 NumStr += LastChar;
98 LastChar = getchar();
99 } while (isdigit(LastChar) || LastChar == '.');
100
101 NumVal = strtod(NumStr.c_str(), 0);
102 return tok_number;
103 }
104
105 if (LastChar == '#') {
106 // Comment until end of line.
Eric Christopherc0239362014-12-08 18:12:28 +0000107 do
108 LastChar = getchar();
Nick Lewycky109af622009-04-12 20:47:23 +0000109 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
Eric Christopherc0239362014-12-08 18:12:28 +0000110
Nick Lewycky109af622009-04-12 20:47:23 +0000111 if (LastChar != EOF)
112 return gettok();
113 }
Eric Christopherc0239362014-12-08 18:12:28 +0000114
Nick Lewycky109af622009-04-12 20:47:23 +0000115 // Check for end of file. Don't eat the EOF.
116 if (LastChar == EOF)
117 return tok_eof;
118
119 // Otherwise, just return the character as its ascii value.
120 int ThisChar = LastChar;
121 LastChar = getchar();
122 return ThisChar;
123}
124
125//===----------------------------------------------------------------------===//
126// Abstract Syntax Tree (aka Parse Tree)
127//===----------------------------------------------------------------------===//
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000128namespace {
Nick Lewycky109af622009-04-12 20:47:23 +0000129/// ExprAST - Base class for all expression nodes.
130class ExprAST {
131public:
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000132 virtual ~ExprAST() {}
Nick Lewycky109af622009-04-12 20:47:23 +0000133 virtual Value *Codegen() = 0;
134};
135
136/// NumberExprAST - Expression class for numeric literals like "1.0".
137class NumberExprAST : public ExprAST {
138 double Val;
Lang Hames59b0da82015-08-19 18:15:58 +0000139
Nick Lewycky109af622009-04-12 20:47:23 +0000140public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000141 NumberExprAST(double Val) : Val(Val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000142 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000143};
144
145/// VariableExprAST - Expression class for referencing a variable, like "a".
146class VariableExprAST : public ExprAST {
147 std::string Name;
Lang Hames59b0da82015-08-19 18:15:58 +0000148
Nick Lewycky109af622009-04-12 20:47:23 +0000149public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000150 VariableExprAST(const std::string &Name) : Name(Name) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000151 const std::string &getName() const { return Name; }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000152 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000153};
154
155/// UnaryExprAST - Expression class for a unary operator.
156class UnaryExprAST : public ExprAST {
157 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000158 std::unique_ptr<ExprAST> Operand;
Lang Hames59b0da82015-08-19 18:15:58 +0000159
Nick Lewycky109af622009-04-12 20:47:23 +0000160public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000161 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
162 : Opcode(Opcode), Operand(std::move(Operand)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000163 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000164};
165
166/// BinaryExprAST - Expression class for a binary operator.
167class BinaryExprAST : public ExprAST {
168 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000169 std::unique_ptr<ExprAST> LHS, RHS;
Lang Hames59b0da82015-08-19 18:15:58 +0000170
Nick Lewycky109af622009-04-12 20:47:23 +0000171public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000172 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
173 std::unique_ptr<ExprAST> RHS)
174 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000175 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000176};
177
178/// CallExprAST - Expression class for function calls.
179class CallExprAST : public ExprAST {
180 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000181 std::vector<std::unique_ptr<ExprAST>> Args;
Lang Hames59b0da82015-08-19 18:15:58 +0000182
Nick Lewycky109af622009-04-12 20:47:23 +0000183public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000184 CallExprAST(const std::string &Callee,
185 std::vector<std::unique_ptr<ExprAST>> Args)
186 : Callee(Callee), Args(std::move(Args)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000187 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000188};
189
190/// IfExprAST - Expression class for if/then/else.
191class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000192 std::unique_ptr<ExprAST> Cond, Then, Else;
Lang Hames59b0da82015-08-19 18:15:58 +0000193
Nick Lewycky109af622009-04-12 20:47:23 +0000194public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000195 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
196 std::unique_ptr<ExprAST> Else)
197 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000198 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000199};
200
201/// ForExprAST - Expression class for for/in.
202class ForExprAST : public ExprAST {
203 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000204 std::unique_ptr<ExprAST> Start, End, Step, Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000205
Nick Lewycky109af622009-04-12 20:47:23 +0000206public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000207 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
208 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
209 std::unique_ptr<ExprAST> Body)
210 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
211 Step(std::move(Step)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000212 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000213};
214
215/// VarExprAST - Expression class for var/in
216class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000217 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
218 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000219
Nick Lewycky109af622009-04-12 20:47:23 +0000220public:
Lang Hames59b0da82015-08-19 18:15:58 +0000221 VarExprAST(
222 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
223 std::unique_ptr<ExprAST> Body)
224 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000225 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000226};
227
228/// PrototypeAST - This class represents the "prototype" for a function,
Lang Hames59b0da82015-08-19 18:15:58 +0000229/// which captures its name, and its argument names (thus implicitly the number
230/// of arguments the function takes), as well as if it is an operator.
Nick Lewycky109af622009-04-12 20:47:23 +0000231class PrototypeAST {
232 std::string Name;
233 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000234 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000235 unsigned Precedence; // Precedence if a binary op.
Lang Hames59b0da82015-08-19 18:15:58 +0000236
Nick Lewycky109af622009-04-12 20:47:23 +0000237public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000238 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
239 bool IsOperator = false, unsigned Prec = 0)
Lang Hames59b0da82015-08-19 18:15:58 +0000240 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
241 Precedence(Prec) {}
Eric Christopherc0239362014-12-08 18:12:28 +0000242
Lang Hames09bf4c12015-08-18 18:11:06 +0000243 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
244 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000245
Nick Lewycky109af622009-04-12 20:47:23 +0000246 char getOperatorName() const {
247 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000248 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000249 }
Eric Christopherc0239362014-12-08 18:12:28 +0000250
Nick Lewycky109af622009-04-12 20:47:23 +0000251 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopherc0239362014-12-08 18:12:28 +0000252
Nick Lewycky109af622009-04-12 20:47:23 +0000253 Function *Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000254
Nick Lewycky109af622009-04-12 20:47:23 +0000255 void CreateArgumentAllocas(Function *F);
256};
257
258/// FunctionAST - This class represents a function definition itself.
259class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000260 std::unique_ptr<PrototypeAST> Proto;
261 std::unique_ptr<ExprAST> Body;
Lang Hames59b0da82015-08-19 18:15:58 +0000262
Nick Lewycky109af622009-04-12 20:47:23 +0000263public:
Lang Hames59b0da82015-08-19 18:15:58 +0000264 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
265 std::unique_ptr<ExprAST> Body)
Lang Hames09bf4c12015-08-18 18:11:06 +0000266 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000267 Function *Codegen();
268};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000269} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000270
271//===----------------------------------------------------------------------===//
272// Parser
273//===----------------------------------------------------------------------===//
274
275/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000276/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000277/// lexer and updates CurTok with its results.
278static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000279static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000280
281/// BinopPrecedence - This holds the precedence for each binary operator that is
282/// defined.
283static std::map<char, int> BinopPrecedence;
284
285/// GetTokPrecedence - Get the precedence of the pending binary operator token.
286static int GetTokPrecedence() {
287 if (!isascii(CurTok))
288 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000289
Nick Lewycky109af622009-04-12 20:47:23 +0000290 // Make sure it's a declared binop.
291 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000292 if (TokPrec <= 0)
293 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000294 return TokPrec;
295}
296
297/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000298std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000299 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000300 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000301}
Lang Hames09bf4c12015-08-18 18:11:06 +0000302std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000303 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000304 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000305}
Lang Hames09bf4c12015-08-18 18:11:06 +0000306std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000307 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000308 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000309}
Nick Lewycky109af622009-04-12 20:47:23 +0000310
Lang Hames09bf4c12015-08-18 18:11:06 +0000311static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000312
Lang Hames59b0da82015-08-19 18:15:58 +0000313/// numberexpr ::= number
314static std::unique_ptr<ExprAST> ParseNumberExpr() {
315 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
316 getNextToken(); // consume the number
317 return std::move(Result);
318}
319
320/// parenexpr ::= '(' expression ')'
321static std::unique_ptr<ExprAST> ParseParenExpr() {
322 getNextToken(); // eat (.
323 auto V = ParseExpression();
324 if (!V)
325 return nullptr;
326
327 if (CurTok != ')')
328 return Error("expected ')'");
329 getNextToken(); // eat ).
330 return V;
331}
332
Nick Lewycky109af622009-04-12 20:47:23 +0000333/// identifierexpr
334/// ::= identifier
335/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000336static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000337 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000338
339 getNextToken(); // eat identifier.
340
Nick Lewycky109af622009-04-12 20:47:23 +0000341 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000342 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000343
Nick Lewycky109af622009-04-12 20:47:23 +0000344 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000345 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000346 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000347 if (CurTok != ')') {
348 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000349 if (auto Arg = ParseExpression())
350 Args.push_back(std::move(Arg));
351 else
352 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000353
Eric Christopherc0239362014-12-08 18:12:28 +0000354 if (CurTok == ')')
355 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000356
Nick Lewycky109af622009-04-12 20:47:23 +0000357 if (CurTok != ',')
358 return Error("Expected ')' or ',' in argument list");
359 getNextToken();
360 }
361 }
362
363 // Eat the ')'.
364 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000365
Lang Hames09bf4c12015-08-18 18:11:06 +0000366 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000367}
368
Nick Lewycky109af622009-04-12 20:47:23 +0000369/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000370static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000371 getNextToken(); // eat the if.
372
Nick Lewycky109af622009-04-12 20:47:23 +0000373 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000374 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000375 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000376 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000377
Nick Lewycky109af622009-04-12 20:47:23 +0000378 if (CurTok != tok_then)
379 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000380 getNextToken(); // eat the then
381
Lang Hames09bf4c12015-08-18 18:11:06 +0000382 auto Then = ParseExpression();
383 if (!Then)
384 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000385
Nick Lewycky109af622009-04-12 20:47:23 +0000386 if (CurTok != tok_else)
387 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000388
Nick Lewycky109af622009-04-12 20:47:23 +0000389 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000390
Lang Hames09bf4c12015-08-18 18:11:06 +0000391 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000392 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000393 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000394
Lang Hames09bf4c12015-08-18 18:11:06 +0000395 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
396 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000397}
398
399/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000400static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000401 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000402
403 if (CurTok != tok_identifier)
404 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000405
Nick Lewycky109af622009-04-12 20:47:23 +0000406 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000407 getNextToken(); // eat identifier.
408
Nick Lewycky109af622009-04-12 20:47:23 +0000409 if (CurTok != '=')
410 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000411 getNextToken(); // eat '='.
412
Lang Hames09bf4c12015-08-18 18:11:06 +0000413 auto Start = ParseExpression();
414 if (!Start)
415 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000416 if (CurTok != ',')
417 return Error("expected ',' after for start value");
418 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000419
Lang Hames09bf4c12015-08-18 18:11:06 +0000420 auto End = ParseExpression();
421 if (!End)
422 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000423
Nick Lewycky109af622009-04-12 20:47:23 +0000424 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000425 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000426 if (CurTok == ',') {
427 getNextToken();
428 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000429 if (!Step)
430 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000431 }
Eric Christopherc0239362014-12-08 18:12:28 +0000432
Nick Lewycky109af622009-04-12 20:47:23 +0000433 if (CurTok != tok_in)
434 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000435 getNextToken(); // eat 'in'.
436
Lang Hames09bf4c12015-08-18 18:11:06 +0000437 auto Body = ParseExpression();
438 if (!Body)
439 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000440
Lang Hames09bf4c12015-08-18 18:11:06 +0000441 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
442 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000443}
444
Eric Christopherc0239362014-12-08 18:12:28 +0000445/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000446// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000447static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000448 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000449
Lang Hames09bf4c12015-08-18 18:11:06 +0000450 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000451
452 // At least one variable name is required.
453 if (CurTok != tok_identifier)
454 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000455
Nick Lewycky109af622009-04-12 20:47:23 +0000456 while (1) {
457 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000458 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000459
460 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000461 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000462 if (CurTok == '=') {
463 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000464
Nick Lewycky109af622009-04-12 20:47:23 +0000465 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000466 if (!Init)
467 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000468 }
Eric Christopherc0239362014-12-08 18:12:28 +0000469
Lang Hames09bf4c12015-08-18 18:11:06 +0000470 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000471
Nick Lewycky109af622009-04-12 20:47:23 +0000472 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000473 if (CurTok != ',')
474 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000475 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000476
Nick Lewycky109af622009-04-12 20:47:23 +0000477 if (CurTok != tok_identifier)
478 return Error("expected identifier list after var");
479 }
Eric Christopherc0239362014-12-08 18:12:28 +0000480
Nick Lewycky109af622009-04-12 20:47:23 +0000481 // At this point, we have to have 'in'.
482 if (CurTok != tok_in)
483 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000484 getNextToken(); // eat 'in'.
485
Lang Hames09bf4c12015-08-18 18:11:06 +0000486 auto Body = ParseExpression();
487 if (!Body)
488 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000489
Lang Hames09bf4c12015-08-18 18:11:06 +0000490 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000491}
492
Nick Lewycky109af622009-04-12 20:47:23 +0000493/// primary
494/// ::= identifierexpr
495/// ::= numberexpr
496/// ::= parenexpr
497/// ::= ifexpr
498/// ::= forexpr
499/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000500static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000501 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000502 default:
503 return Error("unknown token when expecting an expression");
504 case tok_identifier:
505 return ParseIdentifierExpr();
506 case tok_number:
507 return ParseNumberExpr();
508 case '(':
509 return ParseParenExpr();
510 case tok_if:
511 return ParseIfExpr();
512 case tok_for:
513 return ParseForExpr();
514 case tok_var:
515 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000516 }
517}
518
519/// unary
520/// ::= primary
521/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000522static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000523 // If the current token is not an operator, it must be a primary expr.
524 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
525 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000526
Nick Lewycky109af622009-04-12 20:47:23 +0000527 // If this is a unary operator, read it.
528 int Opc = CurTok;
529 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000530 if (auto Operand = ParseUnary())
531 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
532 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000533}
534
535/// binoprhs
536/// ::= ('+' unary)*
Lang Hames59b0da82015-08-19 18:15:58 +0000537static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
538 std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000539 // If this is a binop, find its precedence.
540 while (1) {
541 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000542
Nick Lewycky109af622009-04-12 20:47:23 +0000543 // If this is a binop that binds at least as tightly as the current binop,
544 // consume it, otherwise we are done.
545 if (TokPrec < ExprPrec)
546 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000547
Nick Lewycky109af622009-04-12 20:47:23 +0000548 // Okay, we know this is a binop.
549 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000550 getNextToken(); // eat binop
551
Nick Lewycky109af622009-04-12 20:47:23 +0000552 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000553 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000554 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000555 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000556
Nick Lewycky109af622009-04-12 20:47:23 +0000557 // If BinOp binds less tightly with RHS than the operator after RHS, let
558 // the pending operator take RHS as its LHS.
559 int NextPrec = GetTokPrecedence();
560 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000561 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
562 if (!RHS)
563 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000564 }
Eric Christopherc0239362014-12-08 18:12:28 +0000565
Nick Lewycky109af622009-04-12 20:47:23 +0000566 // Merge LHS/RHS.
Lang Hames59b0da82015-08-19 18:15:58 +0000567 LHS =
568 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000569 }
570}
571
572/// expression
573/// ::= unary binoprhs
574///
Lang Hames09bf4c12015-08-18 18:11:06 +0000575static std::unique_ptr<ExprAST> ParseExpression() {
576 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000577 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000578 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000579
Lang Hames09bf4c12015-08-18 18:11:06 +0000580 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000581}
582
583/// prototype
584/// ::= id '(' id* ')'
585/// ::= binary LETTER number? (id, id)
586/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000587static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000588 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000589
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000590 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000591 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000592
Nick Lewycky109af622009-04-12 20:47:23 +0000593 switch (CurTok) {
594 default:
595 return ErrorP("Expected function name in prototype");
596 case tok_identifier:
597 FnName = IdentifierStr;
598 Kind = 0;
599 getNextToken();
600 break;
601 case tok_unary:
602 getNextToken();
603 if (!isascii(CurTok))
604 return ErrorP("Expected unary operator");
605 FnName = "unary";
606 FnName += (char)CurTok;
607 Kind = 1;
608 getNextToken();
609 break;
610 case tok_binary:
611 getNextToken();
612 if (!isascii(CurTok))
613 return ErrorP("Expected binary operator");
614 FnName = "binary";
615 FnName += (char)CurTok;
616 Kind = 2;
617 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000618
Nick Lewycky109af622009-04-12 20:47:23 +0000619 // Read the precedence if present.
620 if (CurTok == tok_number) {
621 if (NumVal < 1 || NumVal > 100)
622 return ErrorP("Invalid precedecnce: must be 1..100");
623 BinaryPrecedence = (unsigned)NumVal;
624 getNextToken();
625 }
626 break;
627 }
Eric Christopherc0239362014-12-08 18:12:28 +0000628
Nick Lewycky109af622009-04-12 20:47:23 +0000629 if (CurTok != '(')
630 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000631
Nick Lewycky109af622009-04-12 20:47:23 +0000632 std::vector<std::string> ArgNames;
633 while (getNextToken() == tok_identifier)
634 ArgNames.push_back(IdentifierStr);
635 if (CurTok != ')')
636 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000637
Nick Lewycky109af622009-04-12 20:47:23 +0000638 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000639 getNextToken(); // eat ')'.
640
Nick Lewycky109af622009-04-12 20:47:23 +0000641 // Verify right number of names for operator.
642 if (Kind && ArgNames.size() != Kind)
643 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000644
Lang Hames09bf4c12015-08-18 18:11:06 +0000645 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
646 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000647}
648
649/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000650static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000651 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000652 auto Proto = ParsePrototype();
653 if (!Proto)
654 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000655
Lang Hames09bf4c12015-08-18 18:11:06 +0000656 if (auto E = ParseExpression())
657 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
658 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000659}
660
661/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000662static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
663 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000664 // Make an anonymous proto.
Lang Hames59b0da82015-08-19 18:15:58 +0000665 auto Proto =
666 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
Lang Hames09bf4c12015-08-18 18:11:06 +0000667 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000668 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000669 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000670}
671
672/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000673static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000674 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000675 return ParsePrototype();
676}
677
678//===----------------------------------------------------------------------===//
679// Code Generation
680//===----------------------------------------------------------------------===//
681
682static Module *TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000683static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000684static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000685static legacy::FunctionPassManager *TheFPM;
Nick Lewycky109af622009-04-12 20:47:23 +0000686
Eric Christopherc0239362014-12-08 18:12:28 +0000687Value *ErrorV(const char *Str) {
688 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000689 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000690}
Nick Lewycky109af622009-04-12 20:47:23 +0000691
692/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
693/// the function. This is used for mutable variables etc.
694static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
695 const std::string &VarName) {
696 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000697 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000698 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
699 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000700}
701
Nick Lewycky109af622009-04-12 20:47:23 +0000702Value *NumberExprAST::Codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000703 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000704}
705
706Value *VariableExprAST::Codegen() {
707 // Look this variable up in the function.
708 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000709 if (!V)
Eric Christopherc0239362014-12-08 18:12:28 +0000710 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000711
712 // Load the value.
713 return Builder.CreateLoad(V, Name.c_str());
714}
715
716Value *UnaryExprAST::Codegen() {
717 Value *OperandV = Operand->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000718 if (!OperandV)
719 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000720
721 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000722 if (!F)
Nick Lewycky109af622009-04-12 20:47:23 +0000723 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000724
Nick Lewycky109af622009-04-12 20:47:23 +0000725 return Builder.CreateCall(F, OperandV, "unop");
726}
727
Nick Lewycky109af622009-04-12 20:47:23 +0000728Value *BinaryExprAST::Codegen() {
729 // Special case '=' because we don't want to emit the LHS as an expression.
730 if (Op == '=') {
731 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000732 // This assume we're building without RTTI because LLVM builds that way by
733 // default. If you build LLVM with RTTI this can be changed to a
734 // dynamic_cast for automatic error checking.
Lang Hames59b0da82015-08-19 18:15:58 +0000735 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000736 if (!LHSE)
737 return ErrorV("destination of '=' must be a variable");
738 // Codegen the RHS.
739 Value *Val = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000740 if (!Val)
741 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000742
743 // Look up the name.
744 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000745 if (!Variable)
Eric Christopherc0239362014-12-08 18:12:28 +0000746 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000747
748 Builder.CreateStore(Val, Variable);
749 return Val;
750 }
Eric Christopherc0239362014-12-08 18:12:28 +0000751
Nick Lewycky109af622009-04-12 20:47:23 +0000752 Value *L = LHS->Codegen();
753 Value *R = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000754 if (!L || !R)
755 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000756
Nick Lewycky109af622009-04-12 20:47:23 +0000757 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000758 case '+':
759 return Builder.CreateFAdd(L, R, "addtmp");
760 case '-':
761 return Builder.CreateFSub(L, R, "subtmp");
762 case '*':
763 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000764 case '<':
765 L = Builder.CreateFCmpULT(L, R, "cmptmp");
766 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000767 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
768 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000769 default:
770 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000771 }
Eric Christopherc0239362014-12-08 18:12:28 +0000772
Nick Lewycky109af622009-04-12 20:47:23 +0000773 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
774 // a call to it.
Eric Christopherc0239362014-12-08 18:12:28 +0000775 Function *F = TheModule->getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000776 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000777
Lang Hames59b0da82015-08-19 18:15:58 +0000778 Value *Ops[] = {L, R};
Francois Pichetc5d10502011-07-15 10:59:52 +0000779 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000780}
781
782Value *CallExprAST::Codegen() {
783 // Look up the name in the global module table.
784 Function *CalleeF = TheModule->getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000785 if (!CalleeF)
Nick Lewycky109af622009-04-12 20:47:23 +0000786 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000787
Nick Lewycky109af622009-04-12 20:47:23 +0000788 // If argument mismatch error.
789 if (CalleeF->arg_size() != Args.size())
790 return ErrorV("Incorrect # arguments passed");
791
Eric Christopherc0239362014-12-08 18:12:28 +0000792 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000793 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
794 ArgsV.push_back(Args[i]->Codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000795 if (!ArgsV.back())
796 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000797 }
Eric Christopherc0239362014-12-08 18:12:28 +0000798
Francois Pichetc5d10502011-07-15 10:59:52 +0000799 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000800}
801
802Value *IfExprAST::Codegen() {
803 Value *CondV = Cond->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000804 if (!CondV)
805 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000806
Nick Lewycky109af622009-04-12 20:47:23 +0000807 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000808 CondV = Builder.CreateFCmpONE(
809 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
810
Nick Lewycky109af622009-04-12 20:47:23 +0000811 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000812
Nick Lewycky109af622009-04-12 20:47:23 +0000813 // Create blocks for the then and else cases. Insert the 'then' block at the
814 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000815 BasicBlock *ThenBB =
816 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000817 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
818 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000819
Nick Lewycky109af622009-04-12 20:47:23 +0000820 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000821
Nick Lewycky109af622009-04-12 20:47:23 +0000822 // Emit then value.
823 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000824
Nick Lewycky109af622009-04-12 20:47:23 +0000825 Value *ThenV = Then->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000826 if (!ThenV)
827 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000828
Nick Lewycky109af622009-04-12 20:47:23 +0000829 Builder.CreateBr(MergeBB);
830 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
831 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000832
Nick Lewycky109af622009-04-12 20:47:23 +0000833 // Emit else block.
834 TheFunction->getBasicBlockList().push_back(ElseBB);
835 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000836
Nick Lewycky109af622009-04-12 20:47:23 +0000837 Value *ElseV = Else->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000838 if (!ElseV)
839 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000840
Nick Lewycky109af622009-04-12 20:47:23 +0000841 Builder.CreateBr(MergeBB);
842 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
843 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000844
Nick Lewycky109af622009-04-12 20:47:23 +0000845 // Emit merge block.
846 TheFunction->getBasicBlockList().push_back(MergeBB);
847 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000848 PHINode *PN =
849 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
850
Nick Lewycky109af622009-04-12 20:47:23 +0000851 PN->addIncoming(ThenV, ThenBB);
852 PN->addIncoming(ElseV, ElseBB);
853 return PN;
854}
855
Lang Hames59b0da82015-08-19 18:15:58 +0000856// Output for-loop as:
857// var = alloca double
858// ...
859// start = startexpr
860// store start -> var
861// goto loop
862// loop:
863// ...
864// bodyexpr
865// ...
866// loopend:
867// step = stepexpr
868// endcond = endexpr
869//
870// curvar = load var
871// nextvar = curvar + step
872// store nextvar -> var
873// br endcond, loop, endloop
874// outloop:
Nick Lewycky109af622009-04-12 20:47:23 +0000875Value *ForExprAST::Codegen() {
Nick Lewycky109af622009-04-12 20:47:23 +0000876 Function *TheFunction = Builder.GetInsertBlock()->getParent();
877
878 // Create an alloca for the variable in the entry block.
879 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000880
Nick Lewycky109af622009-04-12 20:47:23 +0000881 // Emit the start code first, without 'variable' in scope.
882 Value *StartVal = Start->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000883 if (!StartVal)
884 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000885
Nick Lewycky109af622009-04-12 20:47:23 +0000886 // Store the value into the alloca.
887 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000888
Nick Lewycky109af622009-04-12 20:47:23 +0000889 // Make the new basic block for the loop header, inserting after current
890 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000891 BasicBlock *LoopBB =
892 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
893
Nick Lewycky109af622009-04-12 20:47:23 +0000894 // Insert an explicit fall through from the current block to the LoopBB.
895 Builder.CreateBr(LoopBB);
896
897 // Start insertion in LoopBB.
898 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000899
Nick Lewycky109af622009-04-12 20:47:23 +0000900 // Within the loop, the variable is defined equal to the PHI node. If it
901 // shadows an existing variable, we have to restore it, so save it now.
902 AllocaInst *OldVal = NamedValues[VarName];
903 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000904
Nick Lewycky109af622009-04-12 20:47:23 +0000905 // Emit the body of the loop. This, like any other expr, can change the
906 // current BB. Note that we ignore the value computed by the body, but don't
907 // allow an error.
Lang Hames09bf4c12015-08-18 18:11:06 +0000908 if (!Body->Codegen())
909 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000910
Nick Lewycky109af622009-04-12 20:47:23 +0000911 // Emit the step value.
Lang Hames59b0da82015-08-19 18:15:58 +0000912 Value *StepVal = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000913 if (Step) {
914 StepVal = Step->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000915 if (!StepVal)
916 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000917 } else {
918 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000919 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000920 }
Eric Christopherc0239362014-12-08 18:12:28 +0000921
Nick Lewycky109af622009-04-12 20:47:23 +0000922 // Compute the end condition.
923 Value *EndCond = End->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000924 if (!EndCond)
Lang Hames59b0da82015-08-19 18:15:58 +0000925 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000926
Nick Lewycky109af622009-04-12 20:47:23 +0000927 // Reload, increment, and restore the alloca. This handles the case where
928 // the body of the loop mutates the variable.
929 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000930 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000931 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000932
Nick Lewycky109af622009-04-12 20:47:23 +0000933 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000934 EndCond = Builder.CreateFCmpONE(
935 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
936
Nick Lewycky109af622009-04-12 20:47:23 +0000937 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000938 BasicBlock *AfterBB =
939 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
940
Nick Lewycky109af622009-04-12 20:47:23 +0000941 // Insert the conditional branch into the end of LoopEndBB.
942 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000943
Nick Lewycky109af622009-04-12 20:47:23 +0000944 // Any new code will be inserted in AfterBB.
945 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000946
Nick Lewycky109af622009-04-12 20:47:23 +0000947 // Restore the unshadowed variable.
948 if (OldVal)
949 NamedValues[VarName] = OldVal;
950 else
951 NamedValues.erase(VarName);
952
Nick Lewycky109af622009-04-12 20:47:23 +0000953 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000954 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000955}
956
957Value *VarExprAST::Codegen() {
958 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000959
Nick Lewycky109af622009-04-12 20:47:23 +0000960 Function *TheFunction = Builder.GetInsertBlock()->getParent();
961
962 // Register all variables and emit their initializer.
963 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
964 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000965 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000966
Nick Lewycky109af622009-04-12 20:47:23 +0000967 // Emit the initializer before adding the variable to scope, this prevents
968 // the initializer from referencing the variable itself, and permits stuff
969 // like this:
970 // var a = 1 in
971 // var a = a in ... # refers to outer 'a'.
972 Value *InitVal;
973 if (Init) {
974 InitVal = Init->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000975 if (!InitVal)
976 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000977 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000978 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000979 }
Eric Christopherc0239362014-12-08 18:12:28 +0000980
Nick Lewycky109af622009-04-12 20:47:23 +0000981 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
982 Builder.CreateStore(InitVal, Alloca);
983
984 // Remember the old variable binding so that we can restore the binding when
985 // we unrecurse.
986 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000987
Nick Lewycky109af622009-04-12 20:47:23 +0000988 // Remember this binding.
989 NamedValues[VarName] = Alloca;
990 }
Eric Christopherc0239362014-12-08 18:12:28 +0000991
Nick Lewycky109af622009-04-12 20:47:23 +0000992 // Codegen the body, now that all vars are in scope.
993 Value *BodyVal = Body->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000994 if (!BodyVal)
995 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000996
Nick Lewycky109af622009-04-12 20:47:23 +0000997 // Pop all our variables from scope.
998 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
999 NamedValues[VarNames[i].first] = OldBindings[i];
1000
1001 // Return the body computation.
1002 return BodyVal;
1003}
1004
Nick Lewycky109af622009-04-12 20:47:23 +00001005Function *PrototypeAST::Codegen() {
1006 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +00001007 std::vector<Type *> Doubles(Args.size(),
1008 Type::getDoubleTy(getGlobalContext()));
1009 FunctionType *FT =
1010 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1011
1012 Function *F =
1013 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1014
Nick Lewycky109af622009-04-12 20:47:23 +00001015 // If F conflicted, there was already something named 'Name'. If it has a
1016 // body, don't allow redefinition or reextern.
1017 if (F->getName() != Name) {
1018 // Delete the one we just made and get the existing one.
1019 F->eraseFromParent();
1020 F = TheModule->getFunction(Name);
Eric Christopherc0239362014-12-08 18:12:28 +00001021
Nick Lewycky109af622009-04-12 20:47:23 +00001022 // If F already has a body, reject this.
1023 if (!F->empty()) {
1024 ErrorF("redefinition of function");
Lang Hames09bf4c12015-08-18 18:11:06 +00001025 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001026 }
Eric Christopherc0239362014-12-08 18:12:28 +00001027
Nick Lewycky109af622009-04-12 20:47:23 +00001028 // If F took a different number of args, reject.
1029 if (F->arg_size() != Args.size()) {
1030 ErrorF("redefinition of function with different # args");
Lang Hames09bf4c12015-08-18 18:11:06 +00001031 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001032 }
1033 }
Eric Christopherc0239362014-12-08 18:12:28 +00001034
Nick Lewycky109af622009-04-12 20:47:23 +00001035 // Set names for all arguments.
1036 unsigned Idx = 0;
1037 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1038 ++AI, ++Idx)
1039 AI->setName(Args[Idx]);
Eric Christopherc0239362014-12-08 18:12:28 +00001040
Nick Lewycky109af622009-04-12 20:47:23 +00001041 return F;
1042}
1043
1044/// CreateArgumentAllocas - Create an alloca for each argument and register the
1045/// argument in the symbol table so that references to it will succeed.
1046void PrototypeAST::CreateArgumentAllocas(Function *F) {
1047 Function::arg_iterator AI = F->arg_begin();
1048 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1049 // Create an alloca for this variable.
1050 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1051
1052 // Store the initial value into the alloca.
1053 Builder.CreateStore(AI, Alloca);
1054
1055 // Add arguments to variable symbol table.
1056 NamedValues[Args[Idx]] = Alloca;
1057 }
1058}
1059
Nick Lewycky109af622009-04-12 20:47:23 +00001060Function *FunctionAST::Codegen() {
1061 NamedValues.clear();
Eric Christopherc0239362014-12-08 18:12:28 +00001062
Nick Lewycky109af622009-04-12 20:47:23 +00001063 Function *TheFunction = Proto->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001064 if (!TheFunction)
1065 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001066
Nick Lewycky109af622009-04-12 20:47:23 +00001067 // If this is an operator, install it.
1068 if (Proto->isBinaryOp())
1069 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001070
Nick Lewycky109af622009-04-12 20:47:23 +00001071 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001072 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001073 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001074
Nick Lewycky109af622009-04-12 20:47:23 +00001075 // Add all arguments to the symbol table and create their allocas.
1076 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001077
Nick Lewycky109af622009-04-12 20:47:23 +00001078 if (Value *RetVal = Body->Codegen()) {
1079 // Finish off the function.
1080 Builder.CreateRet(RetVal);
1081
1082 // Validate the generated code, checking for consistency.
1083 verifyFunction(*TheFunction);
1084
1085 // Optimize the function.
1086 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001087
Nick Lewycky109af622009-04-12 20:47:23 +00001088 return TheFunction;
1089 }
Eric Christopherc0239362014-12-08 18:12:28 +00001090
Nick Lewycky109af622009-04-12 20:47:23 +00001091 // Error reading body, remove function.
1092 TheFunction->eraseFromParent();
1093
1094 if (Proto->isBinaryOp())
1095 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001096 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001097}
1098
1099//===----------------------------------------------------------------------===//
1100// Top-Level parsing and JIT Driver
1101//===----------------------------------------------------------------------===//
1102
1103static ExecutionEngine *TheExecutionEngine;
1104
1105static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001106 if (auto FnAST = ParseDefinition()) {
1107 if (auto *FnIR = FnAST->Codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001108 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001109 FnIR->dump();
Nick Lewycky109af622009-04-12 20:47:23 +00001110 }
1111 } else {
1112 // Skip token for error recovery.
1113 getNextToken();
1114 }
1115}
1116
1117static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001118 if (auto ProtoAST = ParseExtern()) {
1119 if (auto *FnIR = ProtoAST->Codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001120 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001121 FnIR->dump();
Nick Lewycky109af622009-04-12 20:47:23 +00001122 }
1123 } else {
1124 // Skip token for error recovery.
1125 getNextToken();
1126 }
1127}
1128
1129static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001130 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001131 if (auto FnAST = ParseTopLevelExpr()) {
1132 if (auto *FnIR = FnAST->Codegen()) {
Eric Christopher1b74b652014-12-08 18:00:38 +00001133 TheExecutionEngine->finalizeObject();
Nick Lewycky109af622009-04-12 20:47:23 +00001134 // JIT the function, returning a function pointer.
Lang Hames09bf4c12015-08-18 18:11:06 +00001135 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
Eric Christopherc0239362014-12-08 18:12:28 +00001136
Nick Lewycky109af622009-04-12 20:47:23 +00001137 // Cast it to the right type (takes no arguments, returns a double) so we
1138 // can call it as a native function.
Chris Lattner0813c0c2009-04-15 00:16:05 +00001139 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky109af622009-04-12 20:47:23 +00001140 fprintf(stderr, "Evaluated to %f\n", FP());
1141 }
1142 } else {
1143 // Skip token for error recovery.
1144 getNextToken();
1145 }
1146}
1147
1148/// top ::= definition | external | expression | ';'
1149static void MainLoop() {
1150 while (1) {
1151 fprintf(stderr, "ready> ");
1152 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001153 case tok_eof:
1154 return;
Lang Hames59b0da82015-08-19 18:15:58 +00001155 case ';': // ignore top-level semicolons.
Eric Christopherc0239362014-12-08 18:12:28 +00001156 getNextToken();
Lang Hames59b0da82015-08-19 18:15:58 +00001157 break;
Eric Christopherc0239362014-12-08 18:12:28 +00001158 case tok_def:
1159 HandleDefinition();
1160 break;
1161 case tok_extern:
1162 HandleExtern();
1163 break;
1164 default:
1165 HandleTopLevelExpression();
1166 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001167 }
1168 }
1169}
1170
Nick Lewycky109af622009-04-12 20:47:23 +00001171//===----------------------------------------------------------------------===//
1172// "Library" functions that can be "extern'd" from user code.
1173//===----------------------------------------------------------------------===//
1174
1175/// putchard - putchar that takes a double and returns 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001176extern "C" double putchard(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001177 putchar((char)X);
1178 return 0;
1179}
1180
1181/// printd - printf that takes a double prints it as "%f\n", returning 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001182extern "C" double printd(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001183 printf("%f\n", X);
1184 return 0;
1185}
1186
1187//===----------------------------------------------------------------------===//
1188// Main driver code.
1189//===----------------------------------------------------------------------===//
1190
1191int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001192 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001193 InitializeNativeTargetAsmPrinter();
1194 InitializeNativeTargetAsmParser();
Owen Andersonc277dc42009-07-16 19:05:41 +00001195 LLVMContext &Context = getGlobalContext();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001196
Nick Lewycky109af622009-04-12 20:47:23 +00001197 // Install standard binary operators.
1198 // 1 is lowest precedence.
1199 BinopPrecedence['='] = 2;
1200 BinopPrecedence['<'] = 10;
1201 BinopPrecedence['+'] = 20;
1202 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001203 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001204
1205 // Prime the first token.
1206 fprintf(stderr, "ready> ");
1207 getNextToken();
1208
1209 // Make the module, which holds all the code.
Rafael Espindola2a8a2792014-08-19 04:04:25 +00001210 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1211 TheModule = Owner.get();
Nick Lewycky109af622009-04-12 20:47:23 +00001212
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001213 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001214 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001215 TheExecutionEngine =
1216 EngineBuilder(std::move(Owner))
1217 .setErrorStr(&ErrStr)
1218 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1219 .create();
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001220 if (!TheExecutionEngine) {
1221 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1222 exit(1);
1223 }
Reid Klecknere56676a2009-08-24 05:42:21 +00001224
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001225 legacy::FunctionPassManager OurFPM(TheModule);
Nick Lewycky109af622009-04-12 20:47:23 +00001226
Reid Klecknerab770042009-08-26 20:58:25 +00001227 // Set up the optimizer pipeline. Start with registering info about how the
1228 // target lays out data structures.
Mehdi Aminicd253da2015-07-16 16:47:18 +00001229 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
Dan Gohman56f3a4c2010-11-15 18:41:10 +00001230 // Provide basic AliasAnalysis support for GVN.
1231 OurFPM.add(createBasicAliasAnalysisPass());
Reid Klecknerab770042009-08-26 20:58:25 +00001232 // Promote allocas to registers.
1233 OurFPM.add(createPromoteMemoryToRegisterPass());
1234 // Do simple "peephole" optimizations and bit-twiddling optzns.
1235 OurFPM.add(createInstructionCombiningPass());
1236 // Reassociate expressions.
1237 OurFPM.add(createReassociatePass());
1238 // Eliminate Common SubExpressions.
1239 OurFPM.add(createGVNPass());
1240 // Simplify the control flow graph (deleting unreachable blocks, etc).
1241 OurFPM.add(createCFGSimplificationPass());
Eli Friedmane04169c2009-07-20 14:50:07 +00001242
Reid Klecknerab770042009-08-26 20:58:25 +00001243 OurFPM.doInitialization();
Nick Lewycky109af622009-04-12 20:47:23 +00001244
Reid Klecknerab770042009-08-26 20:58:25 +00001245 // Set the global so the code gen can use this.
1246 TheFPM = &OurFPM;
1247
1248 // Run the main "interpreter loop" now.
1249 MainLoop();
1250
1251 TheFPM = 0;
1252
1253 // Print out all of the generated code.
1254 TheModule->dump();
1255
Nick Lewycky109af622009-04-12 20:47:23 +00001256 return 0;
1257}