blob: 3c988ac9aa2f78f0c649c1dab4cd3fbe5252a3af [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;
139public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000140 NumberExprAST(double Val) : Val(Val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000141 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000142};
143
144/// VariableExprAST - Expression class for referencing a variable, like "a".
145class VariableExprAST : public ExprAST {
146 std::string Name;
147public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000148 VariableExprAST(const std::string &Name) : Name(Name) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000149 const std::string &getName() const { return Name; }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000150 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000151};
152
153/// UnaryExprAST - Expression class for a unary operator.
154class UnaryExprAST : public ExprAST {
155 char Opcode;
Lang Hames09bf4c12015-08-18 18:11:06 +0000156 std::unique_ptr<ExprAST> Operand;
Nick Lewycky109af622009-04-12 20:47:23 +0000157public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000158 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
159 : Opcode(Opcode), Operand(std::move(Operand)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000160 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000161};
162
163/// BinaryExprAST - Expression class for a binary operator.
164class BinaryExprAST : public ExprAST {
165 char Op;
Lang Hames09bf4c12015-08-18 18:11:06 +0000166 std::unique_ptr<ExprAST> LHS, RHS;
Nick Lewycky109af622009-04-12 20:47:23 +0000167public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000168 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
169 std::unique_ptr<ExprAST> RHS)
170 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000171 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000172};
173
174/// CallExprAST - Expression class for function calls.
175class CallExprAST : public ExprAST {
176 std::string Callee;
Lang Hames09bf4c12015-08-18 18:11:06 +0000177 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000178public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000179 CallExprAST(const std::string &Callee,
180 std::vector<std::unique_ptr<ExprAST>> Args)
181 : Callee(Callee), Args(std::move(Args)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000182 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000183};
184
185/// IfExprAST - Expression class for if/then/else.
186class IfExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000187 std::unique_ptr<ExprAST> Cond, Then, Else;
Nick Lewycky109af622009-04-12 20:47:23 +0000188public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000189 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
190 std::unique_ptr<ExprAST> Else)
191 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000192 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000193};
194
195/// ForExprAST - Expression class for for/in.
196class ForExprAST : public ExprAST {
197 std::string VarName;
Lang Hames09bf4c12015-08-18 18:11:06 +0000198 std::unique_ptr<ExprAST> Start, End, Step, Body;
Nick Lewycky109af622009-04-12 20:47:23 +0000199public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000200 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
201 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
202 std::unique_ptr<ExprAST> Body)
203 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
204 Step(std::move(Step)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000205 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000206};
207
208/// VarExprAST - Expression class for var/in
209class VarExprAST : public ExprAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000210 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
211 std::unique_ptr<ExprAST> Body;
Nick Lewycky109af622009-04-12 20:47:23 +0000212public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000213 VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
214 std::unique_ptr<ExprAST> Body)
215 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000216 Value *Codegen() override;
Nick Lewycky109af622009-04-12 20:47:23 +0000217};
218
219/// PrototypeAST - This class represents the "prototype" for a function,
220/// which captures its argument names as well as if it is an operator.
221class PrototypeAST {
222 std::string Name;
223 std::vector<std::string> Args;
Lang Hames09bf4c12015-08-18 18:11:06 +0000224 bool IsOperator;
Eric Christopherc0239362014-12-08 18:12:28 +0000225 unsigned Precedence; // Precedence if a binary op.
Nick Lewycky109af622009-04-12 20:47:23 +0000226public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000227 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
228 bool IsOperator = false, unsigned Prec = 0)
229 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
230 Precedence(Prec) {}
Eric Christopherc0239362014-12-08 18:12:28 +0000231
Lang Hames09bf4c12015-08-18 18:11:06 +0000232 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
233 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
Eric Christopherc0239362014-12-08 18:12:28 +0000234
Nick Lewycky109af622009-04-12 20:47:23 +0000235 char getOperatorName() const {
236 assert(isUnaryOp() || isBinaryOp());
Eric Christopherc0239362014-12-08 18:12:28 +0000237 return Name[Name.size() - 1];
Nick Lewycky109af622009-04-12 20:47:23 +0000238 }
Eric Christopherc0239362014-12-08 18:12:28 +0000239
Nick Lewycky109af622009-04-12 20:47:23 +0000240 unsigned getBinaryPrecedence() const { return Precedence; }
Eric Christopherc0239362014-12-08 18:12:28 +0000241
Nick Lewycky109af622009-04-12 20:47:23 +0000242 Function *Codegen();
Eric Christopherc0239362014-12-08 18:12:28 +0000243
Nick Lewycky109af622009-04-12 20:47:23 +0000244 void CreateArgumentAllocas(Function *F);
245};
246
247/// FunctionAST - This class represents a function definition itself.
248class FunctionAST {
Lang Hames09bf4c12015-08-18 18:11:06 +0000249 std::unique_ptr<PrototypeAST> Proto;
250 std::unique_ptr<ExprAST> Body;
Nick Lewycky109af622009-04-12 20:47:23 +0000251public:
Lang Hames09bf4c12015-08-18 18:11:06 +0000252 FunctionAST(std::unique_ptr<PrototypeAST> Proto, std::unique_ptr<ExprAST> Body)
253 : Proto(std::move(Proto)), Body(std::move(Body)) {}
Nick Lewycky109af622009-04-12 20:47:23 +0000254 Function *Codegen();
255};
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000256} // end anonymous namespace
Nick Lewycky109af622009-04-12 20:47:23 +0000257
258//===----------------------------------------------------------------------===//
259// Parser
260//===----------------------------------------------------------------------===//
261
262/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000263/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky109af622009-04-12 20:47:23 +0000264/// lexer and updates CurTok with its results.
265static int CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000266static int getNextToken() { return CurTok = gettok(); }
Nick Lewycky109af622009-04-12 20:47:23 +0000267
268/// BinopPrecedence - This holds the precedence for each binary operator that is
269/// defined.
270static std::map<char, int> BinopPrecedence;
271
272/// GetTokPrecedence - Get the precedence of the pending binary operator token.
273static int GetTokPrecedence() {
274 if (!isascii(CurTok))
275 return -1;
Eric Christopherc0239362014-12-08 18:12:28 +0000276
Nick Lewycky109af622009-04-12 20:47:23 +0000277 // Make sure it's a declared binop.
278 int TokPrec = BinopPrecedence[CurTok];
Eric Christopherc0239362014-12-08 18:12:28 +0000279 if (TokPrec <= 0)
280 return -1;
Nick Lewycky109af622009-04-12 20:47:23 +0000281 return TokPrec;
282}
283
284/// Error* - These are little helper functions for error handling.
Lang Hames09bf4c12015-08-18 18:11:06 +0000285std::unique_ptr<ExprAST> Error(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000286 fprintf(stderr, "Error: %s\n", Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000287 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000288}
Lang Hames09bf4c12015-08-18 18:11:06 +0000289std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000290 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000291 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000292}
Lang Hames09bf4c12015-08-18 18:11:06 +0000293std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
Eric Christopherc0239362014-12-08 18:12:28 +0000294 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000295 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000296}
Nick Lewycky109af622009-04-12 20:47:23 +0000297
Lang Hames09bf4c12015-08-18 18:11:06 +0000298static std::unique_ptr<ExprAST> ParseExpression();
Nick Lewycky109af622009-04-12 20:47:23 +0000299
300/// identifierexpr
301/// ::= identifier
302/// ::= identifier '(' expression* ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000303static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
Nick Lewycky109af622009-04-12 20:47:23 +0000304 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000305
306 getNextToken(); // eat identifier.
307
Nick Lewycky109af622009-04-12 20:47:23 +0000308 if (CurTok != '(') // Simple variable ref.
Lang Hames09bf4c12015-08-18 18:11:06 +0000309 return llvm::make_unique<VariableExprAST>(IdName);
Eric Christopherc0239362014-12-08 18:12:28 +0000310
Nick Lewycky109af622009-04-12 20:47:23 +0000311 // Call.
Eric Christopherc0239362014-12-08 18:12:28 +0000312 getNextToken(); // eat (
Lang Hames09bf4c12015-08-18 18:11:06 +0000313 std::vector<std::unique_ptr<ExprAST>> Args;
Nick Lewycky109af622009-04-12 20:47:23 +0000314 if (CurTok != ')') {
315 while (1) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000316 if (auto Arg = ParseExpression())
317 Args.push_back(std::move(Arg));
318 else
319 return nullptr;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000320
Eric Christopherc0239362014-12-08 18:12:28 +0000321 if (CurTok == ')')
322 break;
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000323
Nick Lewycky109af622009-04-12 20:47:23 +0000324 if (CurTok != ',')
325 return Error("Expected ')' or ',' in argument list");
326 getNextToken();
327 }
328 }
329
330 // Eat the ')'.
331 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000332
Lang Hames09bf4c12015-08-18 18:11:06 +0000333 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
Nick Lewycky109af622009-04-12 20:47:23 +0000334}
335
336/// numberexpr ::= number
Lang Hames09bf4c12015-08-18 18:11:06 +0000337static std::unique_ptr<ExprAST> ParseNumberExpr() {
338 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
Nick Lewycky109af622009-04-12 20:47:23 +0000339 getNextToken(); // consume the number
Lang Hames09bf4c12015-08-18 18:11:06 +0000340 return std::move(Result);
Nick Lewycky109af622009-04-12 20:47:23 +0000341}
342
343/// parenexpr ::= '(' expression ')'
Lang Hames09bf4c12015-08-18 18:11:06 +0000344static std::unique_ptr<ExprAST> ParseParenExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000345 getNextToken(); // eat (.
Lang Hames09bf4c12015-08-18 18:11:06 +0000346 auto V = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000347 if (!V)
Lang Hames09bf4c12015-08-18 18:11:06 +0000348 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000349
Nick Lewycky109af622009-04-12 20:47:23 +0000350 if (CurTok != ')')
351 return Error("expected ')'");
Eric Christopherc0239362014-12-08 18:12:28 +0000352 getNextToken(); // eat ).
Nick Lewycky109af622009-04-12 20:47:23 +0000353 return V;
354}
355
356/// ifexpr ::= 'if' expression 'then' expression 'else' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000357static std::unique_ptr<ExprAST> ParseIfExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000358 getNextToken(); // eat the if.
359
Nick Lewycky109af622009-04-12 20:47:23 +0000360 // condition.
Lang Hames09bf4c12015-08-18 18:11:06 +0000361 auto Cond = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000362 if (!Cond)
Lang Hames09bf4c12015-08-18 18:11:06 +0000363 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000364
Nick Lewycky109af622009-04-12 20:47:23 +0000365 if (CurTok != tok_then)
366 return Error("expected then");
Eric Christopherc0239362014-12-08 18:12:28 +0000367 getNextToken(); // eat the then
368
Lang Hames09bf4c12015-08-18 18:11:06 +0000369 auto Then = ParseExpression();
370 if (!Then)
371 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000372
Nick Lewycky109af622009-04-12 20:47:23 +0000373 if (CurTok != tok_else)
374 return Error("expected else");
Eric Christopherc0239362014-12-08 18:12:28 +0000375
Nick Lewycky109af622009-04-12 20:47:23 +0000376 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000377
Lang Hames09bf4c12015-08-18 18:11:06 +0000378 auto Else = ParseExpression();
Eric Christopherc0239362014-12-08 18:12:28 +0000379 if (!Else)
Lang Hames09bf4c12015-08-18 18:11:06 +0000380 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000381
Lang Hames09bf4c12015-08-18 18:11:06 +0000382 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
383 std::move(Else));
Nick Lewycky109af622009-04-12 20:47:23 +0000384}
385
386/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000387static std::unique_ptr<ExprAST> ParseForExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000388 getNextToken(); // eat the for.
Nick Lewycky109af622009-04-12 20:47:23 +0000389
390 if (CurTok != tok_identifier)
391 return Error("expected identifier after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000392
Nick Lewycky109af622009-04-12 20:47:23 +0000393 std::string IdName = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000394 getNextToken(); // eat identifier.
395
Nick Lewycky109af622009-04-12 20:47:23 +0000396 if (CurTok != '=')
397 return Error("expected '=' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000398 getNextToken(); // eat '='.
399
Lang Hames09bf4c12015-08-18 18:11:06 +0000400 auto Start = ParseExpression();
401 if (!Start)
402 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000403 if (CurTok != ',')
404 return Error("expected ',' after for start value");
405 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000406
Lang Hames09bf4c12015-08-18 18:11:06 +0000407 auto End = ParseExpression();
408 if (!End)
409 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000410
Nick Lewycky109af622009-04-12 20:47:23 +0000411 // The step value is optional.
Lang Hames09bf4c12015-08-18 18:11:06 +0000412 std::unique_ptr<ExprAST> Step;
Nick Lewycky109af622009-04-12 20:47:23 +0000413 if (CurTok == ',') {
414 getNextToken();
415 Step = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000416 if (!Step)
417 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000418 }
Eric Christopherc0239362014-12-08 18:12:28 +0000419
Nick Lewycky109af622009-04-12 20:47:23 +0000420 if (CurTok != tok_in)
421 return Error("expected 'in' after for");
Eric Christopherc0239362014-12-08 18:12:28 +0000422 getNextToken(); // eat 'in'.
423
Lang Hames09bf4c12015-08-18 18:11:06 +0000424 auto Body = ParseExpression();
425 if (!Body)
426 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000427
Lang Hames09bf4c12015-08-18 18:11:06 +0000428 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
429 std::move(Step), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000430}
431
Eric Christopherc0239362014-12-08 18:12:28 +0000432/// varexpr ::= 'var' identifier ('=' expression)?
Nick Lewycky109af622009-04-12 20:47:23 +0000433// (',' identifier ('=' expression)?)* 'in' expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000434static std::unique_ptr<ExprAST> ParseVarExpr() {
Eric Christopherc0239362014-12-08 18:12:28 +0000435 getNextToken(); // eat the var.
Nick Lewycky109af622009-04-12 20:47:23 +0000436
Lang Hames09bf4c12015-08-18 18:11:06 +0000437 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
Nick Lewycky109af622009-04-12 20:47:23 +0000438
439 // At least one variable name is required.
440 if (CurTok != tok_identifier)
441 return Error("expected identifier after var");
Eric Christopherc0239362014-12-08 18:12:28 +0000442
Nick Lewycky109af622009-04-12 20:47:23 +0000443 while (1) {
444 std::string Name = IdentifierStr;
Eric Christopherc0239362014-12-08 18:12:28 +0000445 getNextToken(); // eat identifier.
Nick Lewycky109af622009-04-12 20:47:23 +0000446
447 // Read the optional initializer.
Lang Hames09bf4c12015-08-18 18:11:06 +0000448 std::unique_ptr<ExprAST> Init = nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000449 if (CurTok == '=') {
450 getNextToken(); // eat the '='.
Eric Christopherc0239362014-12-08 18:12:28 +0000451
Nick Lewycky109af622009-04-12 20:47:23 +0000452 Init = ParseExpression();
Lang Hames09bf4c12015-08-18 18:11:06 +0000453 if (!Init)
454 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000455 }
Eric Christopherc0239362014-12-08 18:12:28 +0000456
Lang Hames09bf4c12015-08-18 18:11:06 +0000457 VarNames.push_back(std::make_pair(Name, std::move(Init)));
Eric Christopherc0239362014-12-08 18:12:28 +0000458
Nick Lewycky109af622009-04-12 20:47:23 +0000459 // End of var list, exit loop.
Eric Christopherc0239362014-12-08 18:12:28 +0000460 if (CurTok != ',')
461 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000462 getNextToken(); // eat the ','.
Eric Christopherc0239362014-12-08 18:12:28 +0000463
Nick Lewycky109af622009-04-12 20:47:23 +0000464 if (CurTok != tok_identifier)
465 return Error("expected identifier list after var");
466 }
Eric Christopherc0239362014-12-08 18:12:28 +0000467
Nick Lewycky109af622009-04-12 20:47:23 +0000468 // At this point, we have to have 'in'.
469 if (CurTok != tok_in)
470 return Error("expected 'in' keyword after 'var'");
Eric Christopherc0239362014-12-08 18:12:28 +0000471 getNextToken(); // eat 'in'.
472
Lang Hames09bf4c12015-08-18 18:11:06 +0000473 auto Body = ParseExpression();
474 if (!Body)
475 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000476
Lang Hames09bf4c12015-08-18 18:11:06 +0000477 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
Nick Lewycky109af622009-04-12 20:47:23 +0000478}
479
Nick Lewycky109af622009-04-12 20:47:23 +0000480/// primary
481/// ::= identifierexpr
482/// ::= numberexpr
483/// ::= parenexpr
484/// ::= ifexpr
485/// ::= forexpr
486/// ::= varexpr
Lang Hames09bf4c12015-08-18 18:11:06 +0000487static std::unique_ptr<ExprAST> ParsePrimary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000488 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +0000489 default:
490 return Error("unknown token when expecting an expression");
491 case tok_identifier:
492 return ParseIdentifierExpr();
493 case tok_number:
494 return ParseNumberExpr();
495 case '(':
496 return ParseParenExpr();
497 case tok_if:
498 return ParseIfExpr();
499 case tok_for:
500 return ParseForExpr();
501 case tok_var:
502 return ParseVarExpr();
Nick Lewycky109af622009-04-12 20:47:23 +0000503 }
504}
505
506/// unary
507/// ::= primary
508/// ::= '!' unary
Lang Hames09bf4c12015-08-18 18:11:06 +0000509static std::unique_ptr<ExprAST> ParseUnary() {
Nick Lewycky109af622009-04-12 20:47:23 +0000510 // If the current token is not an operator, it must be a primary expr.
511 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
512 return ParsePrimary();
Eric Christopherc0239362014-12-08 18:12:28 +0000513
Nick Lewycky109af622009-04-12 20:47:23 +0000514 // If this is a unary operator, read it.
515 int Opc = CurTok;
516 getNextToken();
Lang Hames09bf4c12015-08-18 18:11:06 +0000517 if (auto Operand = ParseUnary())
518 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
519 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000520}
521
522/// binoprhs
523/// ::= ('+' unary)*
Lang Hames09bf4c12015-08-18 18:11:06 +0000524 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
Nick Lewycky109af622009-04-12 20:47:23 +0000525 // If this is a binop, find its precedence.
526 while (1) {
527 int TokPrec = GetTokPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +0000528
Nick Lewycky109af622009-04-12 20:47:23 +0000529 // If this is a binop that binds at least as tightly as the current binop,
530 // consume it, otherwise we are done.
531 if (TokPrec < ExprPrec)
532 return LHS;
Eric Christopherc0239362014-12-08 18:12:28 +0000533
Nick Lewycky109af622009-04-12 20:47:23 +0000534 // Okay, we know this is a binop.
535 int BinOp = CurTok;
Eric Christopherc0239362014-12-08 18:12:28 +0000536 getNextToken(); // eat binop
537
Nick Lewycky109af622009-04-12 20:47:23 +0000538 // Parse the unary expression after the binary operator.
Lang Hames09bf4c12015-08-18 18:11:06 +0000539 auto RHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000540 if (!RHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000541 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000542
Nick Lewycky109af622009-04-12 20:47:23 +0000543 // If BinOp binds less tightly with RHS than the operator after RHS, let
544 // the pending operator take RHS as its LHS.
545 int NextPrec = GetTokPrecedence();
546 if (TokPrec < NextPrec) {
Lang Hames09bf4c12015-08-18 18:11:06 +0000547 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
548 if (!RHS)
549 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000550 }
Eric Christopherc0239362014-12-08 18:12:28 +0000551
Nick Lewycky109af622009-04-12 20:47:23 +0000552 // Merge LHS/RHS.
Lang Hames09bf4c12015-08-18 18:11:06 +0000553 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000554 }
555}
556
557/// expression
558/// ::= unary binoprhs
559///
Lang Hames09bf4c12015-08-18 18:11:06 +0000560static std::unique_ptr<ExprAST> ParseExpression() {
561 auto LHS = ParseUnary();
Eric Christopherc0239362014-12-08 18:12:28 +0000562 if (!LHS)
Lang Hames09bf4c12015-08-18 18:11:06 +0000563 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000564
Lang Hames09bf4c12015-08-18 18:11:06 +0000565 return ParseBinOpRHS(0, std::move(LHS));
Nick Lewycky109af622009-04-12 20:47:23 +0000566}
567
568/// prototype
569/// ::= id '(' id* ')'
570/// ::= binary LETTER number? (id, id)
571/// ::= unary LETTER (id)
Lang Hames09bf4c12015-08-18 18:11:06 +0000572static std::unique_ptr<PrototypeAST> ParsePrototype() {
Nick Lewycky109af622009-04-12 20:47:23 +0000573 std::string FnName;
Eric Christopherc0239362014-12-08 18:12:28 +0000574
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +0000575 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky109af622009-04-12 20:47:23 +0000576 unsigned BinaryPrecedence = 30;
Eric Christopherc0239362014-12-08 18:12:28 +0000577
Nick Lewycky109af622009-04-12 20:47:23 +0000578 switch (CurTok) {
579 default:
580 return ErrorP("Expected function name in prototype");
581 case tok_identifier:
582 FnName = IdentifierStr;
583 Kind = 0;
584 getNextToken();
585 break;
586 case tok_unary:
587 getNextToken();
588 if (!isascii(CurTok))
589 return ErrorP("Expected unary operator");
590 FnName = "unary";
591 FnName += (char)CurTok;
592 Kind = 1;
593 getNextToken();
594 break;
595 case tok_binary:
596 getNextToken();
597 if (!isascii(CurTok))
598 return ErrorP("Expected binary operator");
599 FnName = "binary";
600 FnName += (char)CurTok;
601 Kind = 2;
602 getNextToken();
Eric Christopherc0239362014-12-08 18:12:28 +0000603
Nick Lewycky109af622009-04-12 20:47:23 +0000604 // Read the precedence if present.
605 if (CurTok == tok_number) {
606 if (NumVal < 1 || NumVal > 100)
607 return ErrorP("Invalid precedecnce: must be 1..100");
608 BinaryPrecedence = (unsigned)NumVal;
609 getNextToken();
610 }
611 break;
612 }
Eric Christopherc0239362014-12-08 18:12:28 +0000613
Nick Lewycky109af622009-04-12 20:47:23 +0000614 if (CurTok != '(')
615 return ErrorP("Expected '(' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000616
Nick Lewycky109af622009-04-12 20:47:23 +0000617 std::vector<std::string> ArgNames;
618 while (getNextToken() == tok_identifier)
619 ArgNames.push_back(IdentifierStr);
620 if (CurTok != ')')
621 return ErrorP("Expected ')' in prototype");
Eric Christopherc0239362014-12-08 18:12:28 +0000622
Nick Lewycky109af622009-04-12 20:47:23 +0000623 // success.
Eric Christopherc0239362014-12-08 18:12:28 +0000624 getNextToken(); // eat ')'.
625
Nick Lewycky109af622009-04-12 20:47:23 +0000626 // Verify right number of names for operator.
627 if (Kind && ArgNames.size() != Kind)
628 return ErrorP("Invalid number of operands for operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000629
Lang Hames09bf4c12015-08-18 18:11:06 +0000630 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
631 BinaryPrecedence);
Nick Lewycky109af622009-04-12 20:47:23 +0000632}
633
634/// definition ::= 'def' prototype expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000635static std::unique_ptr<FunctionAST> ParseDefinition() {
Eric Christopherc0239362014-12-08 18:12:28 +0000636 getNextToken(); // eat def.
Lang Hames09bf4c12015-08-18 18:11:06 +0000637 auto Proto = ParsePrototype();
638 if (!Proto)
639 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000640
Lang Hames09bf4c12015-08-18 18:11:06 +0000641 if (auto E = ParseExpression())
642 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
643 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000644}
645
646/// toplevelexpr ::= expression
Lang Hames09bf4c12015-08-18 18:11:06 +0000647static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
648 if (auto E = ParseExpression()) {
Nick Lewycky109af622009-04-12 20:47:23 +0000649 // Make an anonymous proto.
Lang Hames09bf4c12015-08-18 18:11:06 +0000650 auto Proto = llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
651 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
Nick Lewycky109af622009-04-12 20:47:23 +0000652 }
Lang Hames09bf4c12015-08-18 18:11:06 +0000653 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000654}
655
656/// external ::= 'extern' prototype
Lang Hames09bf4c12015-08-18 18:11:06 +0000657static std::unique_ptr<PrototypeAST> ParseExtern() {
Eric Christopherc0239362014-12-08 18:12:28 +0000658 getNextToken(); // eat extern.
Nick Lewycky109af622009-04-12 20:47:23 +0000659 return ParsePrototype();
660}
661
662//===----------------------------------------------------------------------===//
663// Code Generation
664//===----------------------------------------------------------------------===//
665
666static Module *TheModule;
Owen Andersona7714592009-07-08 20:50:47 +0000667static IRBuilder<> Builder(getGlobalContext());
Eric Christopherc0239362014-12-08 18:12:28 +0000668static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000669static legacy::FunctionPassManager *TheFPM;
Nick Lewycky109af622009-04-12 20:47:23 +0000670
Eric Christopherc0239362014-12-08 18:12:28 +0000671Value *ErrorV(const char *Str) {
672 Error(Str);
Lang Hames09bf4c12015-08-18 18:11:06 +0000673 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000674}
Nick Lewycky109af622009-04-12 20:47:23 +0000675
676/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
677/// the function. This is used for mutable variables etc.
678static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
679 const std::string &VarName) {
680 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
Eric Christopherc0239362014-12-08 18:12:28 +0000681 TheFunction->getEntryBlock().begin());
Owen Anderson55f1c092009-08-13 21:58:54 +0000682 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
683 VarName.c_str());
Nick Lewycky109af622009-04-12 20:47:23 +0000684}
685
Nick Lewycky109af622009-04-12 20:47:23 +0000686Value *NumberExprAST::Codegen() {
Owen Anderson69c464d2009-07-27 20:59:43 +0000687 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky109af622009-04-12 20:47:23 +0000688}
689
690Value *VariableExprAST::Codegen() {
691 // Look this variable up in the function.
692 Value *V = NamedValues[Name];
Lang Hames09bf4c12015-08-18 18:11:06 +0000693 if (!V)
Eric Christopherc0239362014-12-08 18:12:28 +0000694 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000695
696 // Load the value.
697 return Builder.CreateLoad(V, Name.c_str());
698}
699
700Value *UnaryExprAST::Codegen() {
701 Value *OperandV = Operand->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000702 if (!OperandV)
703 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000704
705 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
Lang Hames09bf4c12015-08-18 18:11:06 +0000706 if (!F)
Nick Lewycky109af622009-04-12 20:47:23 +0000707 return ErrorV("Unknown unary operator");
Eric Christopherc0239362014-12-08 18:12:28 +0000708
Nick Lewycky109af622009-04-12 20:47:23 +0000709 return Builder.CreateCall(F, OperandV, "unop");
710}
711
Nick Lewycky109af622009-04-12 20:47:23 +0000712Value *BinaryExprAST::Codegen() {
713 // Special case '=' because we don't want to emit the LHS as an expression.
714 if (Op == '=') {
715 // Assignment requires the LHS to be an identifier.
Lang Hamese7c28bc2015-04-22 20:41:34 +0000716 // This assume we're building without RTTI because LLVM builds that way by
717 // default. If you build LLVM with RTTI this can be changed to a
718 // dynamic_cast for automatic error checking.
Lang Hames09bf4c12015-08-18 18:11:06 +0000719 VariableExprAST *LHSE = static_cast<VariableExprAST*>(LHS.get());
Nick Lewycky109af622009-04-12 20:47:23 +0000720 if (!LHSE)
721 return ErrorV("destination of '=' must be a variable");
722 // Codegen the RHS.
723 Value *Val = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000724 if (!Val)
725 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000726
727 // Look up the name.
728 Value *Variable = NamedValues[LHSE->getName()];
Lang Hames09bf4c12015-08-18 18:11:06 +0000729 if (!Variable)
Eric Christopherc0239362014-12-08 18:12:28 +0000730 return ErrorV("Unknown variable name");
Nick Lewycky109af622009-04-12 20:47:23 +0000731
732 Builder.CreateStore(Val, Variable);
733 return Val;
734 }
Eric Christopherc0239362014-12-08 18:12:28 +0000735
Nick Lewycky109af622009-04-12 20:47:23 +0000736 Value *L = LHS->Codegen();
737 Value *R = RHS->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000738 if (!L || !R)
739 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000740
Nick Lewycky109af622009-04-12 20:47:23 +0000741 switch (Op) {
Eric Christopherc0239362014-12-08 18:12:28 +0000742 case '+':
743 return Builder.CreateFAdd(L, R, "addtmp");
744 case '-':
745 return Builder.CreateFSub(L, R, "subtmp");
746 case '*':
747 return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000748 case '<':
749 L = Builder.CreateFCmpULT(L, R, "cmptmp");
750 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson55f1c092009-08-13 21:58:54 +0000751 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
752 "booltmp");
Eric Christopherc0239362014-12-08 18:12:28 +0000753 default:
754 break;
Nick Lewycky109af622009-04-12 20:47:23 +0000755 }
Eric Christopherc0239362014-12-08 18:12:28 +0000756
Nick Lewycky109af622009-04-12 20:47:23 +0000757 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
758 // a call to it.
Eric Christopherc0239362014-12-08 18:12:28 +0000759 Function *F = TheModule->getFunction(std::string("binary") + Op);
Nick Lewycky109af622009-04-12 20:47:23 +0000760 assert(F && "binary operator not found!");
Eric Christopherc0239362014-12-08 18:12:28 +0000761
Nick Lewycky109af622009-04-12 20:47:23 +0000762 Value *Ops[] = { L, R };
Francois Pichetc5d10502011-07-15 10:59:52 +0000763 return Builder.CreateCall(F, Ops, "binop");
Nick Lewycky109af622009-04-12 20:47:23 +0000764}
765
766Value *CallExprAST::Codegen() {
767 // Look up the name in the global module table.
768 Function *CalleeF = TheModule->getFunction(Callee);
Lang Hames09bf4c12015-08-18 18:11:06 +0000769 if (!CalleeF)
Nick Lewycky109af622009-04-12 20:47:23 +0000770 return ErrorV("Unknown function referenced");
Eric Christopherc0239362014-12-08 18:12:28 +0000771
Nick Lewycky109af622009-04-12 20:47:23 +0000772 // If argument mismatch error.
773 if (CalleeF->arg_size() != Args.size())
774 return ErrorV("Incorrect # arguments passed");
775
Eric Christopherc0239362014-12-08 18:12:28 +0000776 std::vector<Value *> ArgsV;
Nick Lewycky109af622009-04-12 20:47:23 +0000777 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
778 ArgsV.push_back(Args[i]->Codegen());
Lang Hames09bf4c12015-08-18 18:11:06 +0000779 if (!ArgsV.back())
780 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000781 }
Eric Christopherc0239362014-12-08 18:12:28 +0000782
Francois Pichetc5d10502011-07-15 10:59:52 +0000783 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
Nick Lewycky109af622009-04-12 20:47:23 +0000784}
785
786Value *IfExprAST::Codegen() {
787 Value *CondV = Cond->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000788 if (!CondV)
789 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000790
Nick Lewycky109af622009-04-12 20:47:23 +0000791 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000792 CondV = Builder.CreateFCmpONE(
793 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
794
Nick Lewycky109af622009-04-12 20:47:23 +0000795 Function *TheFunction = Builder.GetInsertBlock()->getParent();
Eric Christopherc0239362014-12-08 18:12:28 +0000796
Nick Lewycky109af622009-04-12 20:47:23 +0000797 // Create blocks for the then and else cases. Insert the 'then' block at the
798 // end of the function.
Eric Christopherc0239362014-12-08 18:12:28 +0000799 BasicBlock *ThenBB =
800 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
Owen Anderson55f1c092009-08-13 21:58:54 +0000801 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
802 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Eric Christopherc0239362014-12-08 18:12:28 +0000803
Nick Lewycky109af622009-04-12 20:47:23 +0000804 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000805
Nick Lewycky109af622009-04-12 20:47:23 +0000806 // Emit then value.
807 Builder.SetInsertPoint(ThenBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000808
Nick Lewycky109af622009-04-12 20:47:23 +0000809 Value *ThenV = Then->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000810 if (!ThenV)
811 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000812
Nick Lewycky109af622009-04-12 20:47:23 +0000813 Builder.CreateBr(MergeBB);
814 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
815 ThenBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000816
Nick Lewycky109af622009-04-12 20:47:23 +0000817 // Emit else block.
818 TheFunction->getBasicBlockList().push_back(ElseBB);
819 Builder.SetInsertPoint(ElseBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000820
Nick Lewycky109af622009-04-12 20:47:23 +0000821 Value *ElseV = Else->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000822 if (!ElseV)
823 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000824
Nick Lewycky109af622009-04-12 20:47:23 +0000825 Builder.CreateBr(MergeBB);
826 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
827 ElseBB = Builder.GetInsertBlock();
Eric Christopherc0239362014-12-08 18:12:28 +0000828
Nick Lewycky109af622009-04-12 20:47:23 +0000829 // Emit merge block.
830 TheFunction->getBasicBlockList().push_back(MergeBB);
831 Builder.SetInsertPoint(MergeBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000832 PHINode *PN =
833 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
834
Nick Lewycky109af622009-04-12 20:47:23 +0000835 PN->addIncoming(ThenV, ThenBB);
836 PN->addIncoming(ElseV, ElseBB);
837 return PN;
838}
839
840Value *ForExprAST::Codegen() {
841 // Output this as:
842 // var = alloca double
843 // ...
844 // start = startexpr
845 // store start -> var
846 // goto loop
Eric Christopherc0239362014-12-08 18:12:28 +0000847 // loop:
Nick Lewycky109af622009-04-12 20:47:23 +0000848 // ...
849 // bodyexpr
850 // ...
851 // loopend:
852 // step = stepexpr
853 // endcond = endexpr
854 //
855 // curvar = load var
856 // nextvar = curvar + step
857 // store nextvar -> var
858 // br endcond, loop, endloop
859 // outloop:
Eric Christopherc0239362014-12-08 18:12:28 +0000860
Nick Lewycky109af622009-04-12 20:47:23 +0000861 Function *TheFunction = Builder.GetInsertBlock()->getParent();
862
863 // Create an alloca for the variable in the entry block.
864 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
Eric Christopherc0239362014-12-08 18:12:28 +0000865
Nick Lewycky109af622009-04-12 20:47:23 +0000866 // Emit the start code first, without 'variable' in scope.
867 Value *StartVal = Start->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000868 if (!StartVal)
869 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000870
Nick Lewycky109af622009-04-12 20:47:23 +0000871 // Store the value into the alloca.
872 Builder.CreateStore(StartVal, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000873
Nick Lewycky109af622009-04-12 20:47:23 +0000874 // Make the new basic block for the loop header, inserting after current
875 // block.
Eric Christopherc0239362014-12-08 18:12:28 +0000876 BasicBlock *LoopBB =
877 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
878
Nick Lewycky109af622009-04-12 20:47:23 +0000879 // Insert an explicit fall through from the current block to the LoopBB.
880 Builder.CreateBr(LoopBB);
881
882 // Start insertion in LoopBB.
883 Builder.SetInsertPoint(LoopBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000884
Nick Lewycky109af622009-04-12 20:47:23 +0000885 // Within the loop, the variable is defined equal to the PHI node. If it
886 // shadows an existing variable, we have to restore it, so save it now.
887 AllocaInst *OldVal = NamedValues[VarName];
888 NamedValues[VarName] = Alloca;
Eric Christopherc0239362014-12-08 18:12:28 +0000889
Nick Lewycky109af622009-04-12 20:47:23 +0000890 // Emit the body of the loop. This, like any other expr, can change the
891 // current BB. Note that we ignore the value computed by the body, but don't
892 // allow an error.
Lang Hames09bf4c12015-08-18 18:11:06 +0000893 if (!Body->Codegen())
894 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000895
Nick Lewycky109af622009-04-12 20:47:23 +0000896 // Emit the step value.
897 Value *StepVal;
898 if (Step) {
899 StepVal = Step->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000900 if (!StepVal)
901 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000902 } else {
903 // If not specified, use 1.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000904 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000905 }
Eric Christopherc0239362014-12-08 18:12:28 +0000906
Nick Lewycky109af622009-04-12 20:47:23 +0000907 // Compute the end condition.
908 Value *EndCond = End->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000909 if (!EndCond)
Eric Christopherc0239362014-12-08 18:12:28 +0000910 return EndCond;
911
Nick Lewycky109af622009-04-12 20:47:23 +0000912 // Reload, increment, and restore the alloca. This handles the case where
913 // the body of the loop mutates the variable.
914 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattner26d79502010-06-21 22:51:14 +0000915 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky109af622009-04-12 20:47:23 +0000916 Builder.CreateStore(NextVar, Alloca);
Eric Christopherc0239362014-12-08 18:12:28 +0000917
Nick Lewycky109af622009-04-12 20:47:23 +0000918 // Convert condition to a bool by comparing equal to 0.0.
Eric Christopherc0239362014-12-08 18:12:28 +0000919 EndCond = Builder.CreateFCmpONE(
920 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
921
Nick Lewycky109af622009-04-12 20:47:23 +0000922 // Create the "after loop" block and insert it.
Eric Christopherc0239362014-12-08 18:12:28 +0000923 BasicBlock *AfterBB =
924 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
925
Nick Lewycky109af622009-04-12 20:47:23 +0000926 // Insert the conditional branch into the end of LoopEndBB.
927 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000928
Nick Lewycky109af622009-04-12 20:47:23 +0000929 // Any new code will be inserted in AfterBB.
930 Builder.SetInsertPoint(AfterBB);
Eric Christopherc0239362014-12-08 18:12:28 +0000931
Nick Lewycky109af622009-04-12 20:47:23 +0000932 // Restore the unshadowed variable.
933 if (OldVal)
934 NamedValues[VarName] = OldVal;
935 else
936 NamedValues.erase(VarName);
937
Nick Lewycky109af622009-04-12 20:47:23 +0000938 // for expr always returns 0.0.
Owen Anderson55f1c092009-08-13 21:58:54 +0000939 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky109af622009-04-12 20:47:23 +0000940}
941
942Value *VarExprAST::Codegen() {
943 std::vector<AllocaInst *> OldBindings;
Eric Christopherc0239362014-12-08 18:12:28 +0000944
Nick Lewycky109af622009-04-12 20:47:23 +0000945 Function *TheFunction = Builder.GetInsertBlock()->getParent();
946
947 // Register all variables and emit their initializer.
948 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
949 const std::string &VarName = VarNames[i].first;
Lang Hames09bf4c12015-08-18 18:11:06 +0000950 ExprAST *Init = VarNames[i].second.get();
Eric Christopherc0239362014-12-08 18:12:28 +0000951
Nick Lewycky109af622009-04-12 20:47:23 +0000952 // Emit the initializer before adding the variable to scope, this prevents
953 // the initializer from referencing the variable itself, and permits stuff
954 // like this:
955 // var a = 1 in
956 // var a = a in ... # refers to outer 'a'.
957 Value *InitVal;
958 if (Init) {
959 InitVal = Init->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000960 if (!InitVal)
961 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +0000962 } else { // If not specified, use 0.0.
Owen Anderson69c464d2009-07-27 20:59:43 +0000963 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky109af622009-04-12 20:47:23 +0000964 }
Eric Christopherc0239362014-12-08 18:12:28 +0000965
Nick Lewycky109af622009-04-12 20:47:23 +0000966 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
967 Builder.CreateStore(InitVal, Alloca);
968
969 // Remember the old variable binding so that we can restore the binding when
970 // we unrecurse.
971 OldBindings.push_back(NamedValues[VarName]);
Eric Christopherc0239362014-12-08 18:12:28 +0000972
Nick Lewycky109af622009-04-12 20:47:23 +0000973 // Remember this binding.
974 NamedValues[VarName] = Alloca;
975 }
Eric Christopherc0239362014-12-08 18:12:28 +0000976
Nick Lewycky109af622009-04-12 20:47:23 +0000977 // Codegen the body, now that all vars are in scope.
978 Value *BodyVal = Body->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +0000979 if (!BodyVal)
980 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +0000981
Nick Lewycky109af622009-04-12 20:47:23 +0000982 // Pop all our variables from scope.
983 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
984 NamedValues[VarNames[i].first] = OldBindings[i];
985
986 // Return the body computation.
987 return BodyVal;
988}
989
Nick Lewycky109af622009-04-12 20:47:23 +0000990Function *PrototypeAST::Codegen() {
991 // Make the function type: double(double,double) etc.
Eric Christopherc0239362014-12-08 18:12:28 +0000992 std::vector<Type *> Doubles(Args.size(),
993 Type::getDoubleTy(getGlobalContext()));
994 FunctionType *FT =
995 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
996
997 Function *F =
998 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
999
Nick Lewycky109af622009-04-12 20:47:23 +00001000 // If F conflicted, there was already something named 'Name'. If it has a
1001 // body, don't allow redefinition or reextern.
1002 if (F->getName() != Name) {
1003 // Delete the one we just made and get the existing one.
1004 F->eraseFromParent();
1005 F = TheModule->getFunction(Name);
Eric Christopherc0239362014-12-08 18:12:28 +00001006
Nick Lewycky109af622009-04-12 20:47:23 +00001007 // If F already has a body, reject this.
1008 if (!F->empty()) {
1009 ErrorF("redefinition of function");
Lang Hames09bf4c12015-08-18 18:11:06 +00001010 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001011 }
Eric Christopherc0239362014-12-08 18:12:28 +00001012
Nick Lewycky109af622009-04-12 20:47:23 +00001013 // If F took a different number of args, reject.
1014 if (F->arg_size() != Args.size()) {
1015 ErrorF("redefinition of function with different # args");
Lang Hames09bf4c12015-08-18 18:11:06 +00001016 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001017 }
1018 }
Eric Christopherc0239362014-12-08 18:12:28 +00001019
Nick Lewycky109af622009-04-12 20:47:23 +00001020 // Set names for all arguments.
1021 unsigned Idx = 0;
1022 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1023 ++AI, ++Idx)
1024 AI->setName(Args[Idx]);
Eric Christopherc0239362014-12-08 18:12:28 +00001025
Nick Lewycky109af622009-04-12 20:47:23 +00001026 return F;
1027}
1028
1029/// CreateArgumentAllocas - Create an alloca for each argument and register the
1030/// argument in the symbol table so that references to it will succeed.
1031void PrototypeAST::CreateArgumentAllocas(Function *F) {
1032 Function::arg_iterator AI = F->arg_begin();
1033 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1034 // Create an alloca for this variable.
1035 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1036
1037 // Store the initial value into the alloca.
1038 Builder.CreateStore(AI, Alloca);
1039
1040 // Add arguments to variable symbol table.
1041 NamedValues[Args[Idx]] = Alloca;
1042 }
1043}
1044
Nick Lewycky109af622009-04-12 20:47:23 +00001045Function *FunctionAST::Codegen() {
1046 NamedValues.clear();
Eric Christopherc0239362014-12-08 18:12:28 +00001047
Nick Lewycky109af622009-04-12 20:47:23 +00001048 Function *TheFunction = Proto->Codegen();
Lang Hames09bf4c12015-08-18 18:11:06 +00001049 if (!TheFunction)
1050 return nullptr;
Eric Christopherc0239362014-12-08 18:12:28 +00001051
Nick Lewycky109af622009-04-12 20:47:23 +00001052 // If this is an operator, install it.
1053 if (Proto->isBinaryOp())
1054 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
Eric Christopherc0239362014-12-08 18:12:28 +00001055
Nick Lewycky109af622009-04-12 20:47:23 +00001056 // Create a new basic block to start insertion into.
Owen Anderson55f1c092009-08-13 21:58:54 +00001057 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky109af622009-04-12 20:47:23 +00001058 Builder.SetInsertPoint(BB);
Eric Christopherc0239362014-12-08 18:12:28 +00001059
Nick Lewycky109af622009-04-12 20:47:23 +00001060 // Add all arguments to the symbol table and create their allocas.
1061 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001062
Nick Lewycky109af622009-04-12 20:47:23 +00001063 if (Value *RetVal = Body->Codegen()) {
1064 // Finish off the function.
1065 Builder.CreateRet(RetVal);
1066
1067 // Validate the generated code, checking for consistency.
1068 verifyFunction(*TheFunction);
1069
1070 // Optimize the function.
1071 TheFPM->run(*TheFunction);
Eric Christopherc0239362014-12-08 18:12:28 +00001072
Nick Lewycky109af622009-04-12 20:47:23 +00001073 return TheFunction;
1074 }
Eric Christopherc0239362014-12-08 18:12:28 +00001075
Nick Lewycky109af622009-04-12 20:47:23 +00001076 // Error reading body, remove function.
1077 TheFunction->eraseFromParent();
1078
1079 if (Proto->isBinaryOp())
1080 BinopPrecedence.erase(Proto->getOperatorName());
Lang Hames09bf4c12015-08-18 18:11:06 +00001081 return nullptr;
Nick Lewycky109af622009-04-12 20:47:23 +00001082}
1083
1084//===----------------------------------------------------------------------===//
1085// Top-Level parsing and JIT Driver
1086//===----------------------------------------------------------------------===//
1087
1088static ExecutionEngine *TheExecutionEngine;
1089
1090static void HandleDefinition() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001091 if (auto FnAST = ParseDefinition()) {
1092 if (auto *FnIR = FnAST->Codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001093 fprintf(stderr, "Read function definition:");
Lang Hames09bf4c12015-08-18 18:11:06 +00001094 FnIR->dump();
Nick Lewycky109af622009-04-12 20:47:23 +00001095 }
1096 } else {
1097 // Skip token for error recovery.
1098 getNextToken();
1099 }
1100}
1101
1102static void HandleExtern() {
Lang Hames09bf4c12015-08-18 18:11:06 +00001103 if (auto ProtoAST = ParseExtern()) {
1104 if (auto *FnIR = ProtoAST->Codegen()) {
Nick Lewycky109af622009-04-12 20:47:23 +00001105 fprintf(stderr, "Read extern: ");
Lang Hames09bf4c12015-08-18 18:11:06 +00001106 FnIR->dump();
Nick Lewycky109af622009-04-12 20:47:23 +00001107 }
1108 } else {
1109 // Skip token for error recovery.
1110 getNextToken();
1111 }
1112}
1113
1114static void HandleTopLevelExpression() {
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001115 // Evaluate a top-level expression into an anonymous function.
Lang Hames09bf4c12015-08-18 18:11:06 +00001116 if (auto FnAST = ParseTopLevelExpr()) {
1117 if (auto *FnIR = FnAST->Codegen()) {
Eric Christopher1b74b652014-12-08 18:00:38 +00001118 TheExecutionEngine->finalizeObject();
Nick Lewycky109af622009-04-12 20:47:23 +00001119 // JIT the function, returning a function pointer.
Lang Hames09bf4c12015-08-18 18:11:06 +00001120 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
Eric Christopherc0239362014-12-08 18:12:28 +00001121
Nick Lewycky109af622009-04-12 20:47:23 +00001122 // Cast it to the right type (takes no arguments, returns a double) so we
1123 // can call it as a native function.
Chris Lattner0813c0c2009-04-15 00:16:05 +00001124 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky109af622009-04-12 20:47:23 +00001125 fprintf(stderr, "Evaluated to %f\n", FP());
1126 }
1127 } else {
1128 // Skip token for error recovery.
1129 getNextToken();
1130 }
1131}
1132
1133/// top ::= definition | external | expression | ';'
1134static void MainLoop() {
1135 while (1) {
1136 fprintf(stderr, "ready> ");
1137 switch (CurTok) {
Eric Christopherc0239362014-12-08 18:12:28 +00001138 case tok_eof:
1139 return;
1140 case ';':
1141 getNextToken();
1142 break; // ignore top-level semicolons.
1143 case tok_def:
1144 HandleDefinition();
1145 break;
1146 case tok_extern:
1147 HandleExtern();
1148 break;
1149 default:
1150 HandleTopLevelExpression();
1151 break;
Nick Lewycky109af622009-04-12 20:47:23 +00001152 }
1153 }
1154}
1155
Nick Lewycky109af622009-04-12 20:47:23 +00001156//===----------------------------------------------------------------------===//
1157// "Library" functions that can be "extern'd" from user code.
1158//===----------------------------------------------------------------------===//
1159
1160/// putchard - putchar that takes a double and returns 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001161extern "C" double putchard(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001162 putchar((char)X);
1163 return 0;
1164}
1165
1166/// printd - printf that takes a double prints it as "%f\n", returning 0.
Eric Christopherc0239362014-12-08 18:12:28 +00001167extern "C" double printd(double X) {
Nick Lewycky109af622009-04-12 20:47:23 +00001168 printf("%f\n", X);
1169 return 0;
1170}
1171
1172//===----------------------------------------------------------------------===//
1173// Main driver code.
1174//===----------------------------------------------------------------------===//
1175
1176int main() {
Chris Lattnerd24df242009-06-17 16:48:44 +00001177 InitializeNativeTarget();
Eric Christopher1b74b652014-12-08 18:00:38 +00001178 InitializeNativeTargetAsmPrinter();
1179 InitializeNativeTargetAsmParser();
Owen Andersonc277dc42009-07-16 19:05:41 +00001180 LLVMContext &Context = getGlobalContext();
Erick Tryzelaar6e2b34bc2009-09-22 21:14:49 +00001181
Nick Lewycky109af622009-04-12 20:47:23 +00001182 // Install standard binary operators.
1183 // 1 is lowest precedence.
1184 BinopPrecedence['='] = 2;
1185 BinopPrecedence['<'] = 10;
1186 BinopPrecedence['+'] = 20;
1187 BinopPrecedence['-'] = 20;
Eric Christopherc0239362014-12-08 18:12:28 +00001188 BinopPrecedence['*'] = 40; // highest.
Nick Lewycky109af622009-04-12 20:47:23 +00001189
1190 // Prime the first token.
1191 fprintf(stderr, "ready> ");
1192 getNextToken();
1193
1194 // Make the module, which holds all the code.
Rafael Espindola2a8a2792014-08-19 04:04:25 +00001195 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1196 TheModule = Owner.get();
Nick Lewycky109af622009-04-12 20:47:23 +00001197
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001198 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001199 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001200 TheExecutionEngine =
1201 EngineBuilder(std::move(Owner))
1202 .setErrorStr(&ErrStr)
1203 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1204 .create();
Jeffrey Yasskin8a303242010-02-11 19:15:20 +00001205 if (!TheExecutionEngine) {
1206 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1207 exit(1);
1208 }
Reid Klecknere56676a2009-08-24 05:42:21 +00001209
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001210 legacy::FunctionPassManager OurFPM(TheModule);
Nick Lewycky109af622009-04-12 20:47:23 +00001211
Reid Klecknerab770042009-08-26 20:58:25 +00001212 // Set up the optimizer pipeline. Start with registering info about how the
1213 // target lays out data structures.
Mehdi Aminicd253da2015-07-16 16:47:18 +00001214 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
Dan Gohman56f3a4c2010-11-15 18:41:10 +00001215 // Provide basic AliasAnalysis support for GVN.
1216 OurFPM.add(createBasicAliasAnalysisPass());
Reid Klecknerab770042009-08-26 20:58:25 +00001217 // Promote allocas to registers.
1218 OurFPM.add(createPromoteMemoryToRegisterPass());
1219 // Do simple "peephole" optimizations and bit-twiddling optzns.
1220 OurFPM.add(createInstructionCombiningPass());
1221 // Reassociate expressions.
1222 OurFPM.add(createReassociatePass());
1223 // Eliminate Common SubExpressions.
1224 OurFPM.add(createGVNPass());
1225 // Simplify the control flow graph (deleting unreachable blocks, etc).
1226 OurFPM.add(createCFGSimplificationPass());
Eli Friedmane04169c2009-07-20 14:50:07 +00001227
Reid Klecknerab770042009-08-26 20:58:25 +00001228 OurFPM.doInitialization();
Nick Lewycky109af622009-04-12 20:47:23 +00001229
Reid Klecknerab770042009-08-26 20:58:25 +00001230 // Set the global so the code gen can use this.
1231 TheFPM = &OurFPM;
1232
1233 // Run the main "interpreter loop" now.
1234 MainLoop();
1235
1236 TheFPM = 0;
1237
1238 // Print out all of the generated code.
1239 TheModule->dump();
1240
Nick Lewycky109af622009-04-12 20:47:23 +00001241 return 0;
1242}