NAKAMURA Takumi | 85c9bac | 2015-03-02 01:04:34 +0000 | [diff] [blame] | 1 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 2 | #include "llvm/Analysis/Passes.h" |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 3 | #include "llvm/ExecutionEngine/ExecutionEngine.h" |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 4 | #include "llvm/ExecutionEngine/MCJIT.h" |
| 5 | #include "llvm/ExecutionEngine/SectionMemoryManager.h" |
Chandler Carruth | 005f27a | 2013-01-02 11:56:33 +0000 | [diff] [blame] | 6 | #include "llvm/IR/DataLayout.h" |
| 7 | #include "llvm/IR/DerivedTypes.h" |
| 8 | #include "llvm/IR/IRBuilder.h" |
| 9 | #include "llvm/IR/LLVMContext.h" |
Chandler Carruth | 30d69c2 | 2015-02-13 10:01:29 +0000 | [diff] [blame] | 10 | #include "llvm/IR/LegacyPassManager.h" |
Chandler Carruth | 005f27a | 2013-01-02 11:56:33 +0000 | [diff] [blame] | 11 | #include "llvm/IR/Module.h" |
Chandler Carruth | 20d4e6b | 2014-01-13 09:58:03 +0000 | [diff] [blame] | 12 | #include "llvm/IR/Verifier.h" |
Evan Cheng | 2bb4035 | 2011-08-24 18:08:43 +0000 | [diff] [blame] | 13 | #include "llvm/Support/TargetSelect.h" |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 14 | #include "llvm/Transforms/Scalar.h" |
Will Dietz | 981af00 | 2013-10-12 00:55:57 +0000 | [diff] [blame] | 15 | #include <cctype> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 16 | #include <cstdio> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 17 | #include <map> |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 18 | #include <string> |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 19 | #include <vector> |
| 20 | using namespace llvm; |
| 21 | |
| 22 | //===----------------------------------------------------------------------===// |
| 23 | // Lexer |
| 24 | //===----------------------------------------------------------------------===// |
| 25 | |
| 26 | // The lexer returns tokens [0-255] if it is an unknown character, otherwise one |
| 27 | // of these for known things. |
| 28 | enum Token { |
| 29 | tok_eof = -1, |
| 30 | |
| 31 | // commands |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 32 | tok_def = -2, |
| 33 | tok_extern = -3, |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 34 | |
| 35 | // primary |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 36 | tok_identifier = -4, |
| 37 | tok_number = -5, |
| 38 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 39 | // control |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 40 | tok_if = -6, |
| 41 | tok_then = -7, |
| 42 | tok_else = -8, |
| 43 | tok_for = -9, |
| 44 | tok_in = -10 |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 45 | }; |
| 46 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 47 | static std::string IdentifierStr; // Filled in if tok_identifier |
| 48 | static double NumVal; // Filled in if tok_number |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 49 | |
| 50 | /// gettok - Return the next token from standard input. |
| 51 | static int gettok() { |
| 52 | static int LastChar = ' '; |
| 53 | |
| 54 | // Skip any whitespace. |
| 55 | while (isspace(LastChar)) |
| 56 | LastChar = getchar(); |
| 57 | |
| 58 | if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* |
| 59 | IdentifierStr = LastChar; |
| 60 | while (isalnum((LastChar = getchar()))) |
| 61 | IdentifierStr += LastChar; |
| 62 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 63 | if (IdentifierStr == "def") |
| 64 | return tok_def; |
| 65 | if (IdentifierStr == "extern") |
| 66 | return tok_extern; |
| 67 | if (IdentifierStr == "if") |
| 68 | return tok_if; |
| 69 | if (IdentifierStr == "then") |
| 70 | return tok_then; |
| 71 | if (IdentifierStr == "else") |
| 72 | return tok_else; |
| 73 | if (IdentifierStr == "for") |
| 74 | return tok_for; |
| 75 | if (IdentifierStr == "in") |
| 76 | return tok_in; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 77 | return tok_identifier; |
| 78 | } |
| 79 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 80 | if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 81 | std::string NumStr; |
| 82 | do { |
| 83 | NumStr += LastChar; |
| 84 | LastChar = getchar(); |
| 85 | } while (isdigit(LastChar) || LastChar == '.'); |
| 86 | |
| 87 | NumVal = strtod(NumStr.c_str(), 0); |
| 88 | return tok_number; |
| 89 | } |
| 90 | |
| 91 | if (LastChar == '#') { |
| 92 | // Comment until end of line. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 93 | do |
| 94 | LastChar = getchar(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 95 | while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 96 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 97 | if (LastChar != EOF) |
| 98 | return gettok(); |
| 99 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 100 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 101 | // Check for end of file. Don't eat the EOF. |
| 102 | if (LastChar == EOF) |
| 103 | return tok_eof; |
| 104 | |
| 105 | // Otherwise, just return the character as its ascii value. |
| 106 | int ThisChar = LastChar; |
| 107 | LastChar = getchar(); |
| 108 | return ThisChar; |
| 109 | } |
| 110 | |
| 111 | //===----------------------------------------------------------------------===// |
| 112 | // Abstract Syntax Tree (aka Parse Tree) |
| 113 | //===----------------------------------------------------------------------===// |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 114 | namespace { |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 115 | /// ExprAST - Base class for all expression nodes. |
| 116 | class ExprAST { |
| 117 | public: |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 118 | virtual ~ExprAST() {} |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 119 | virtual Value *Codegen() = 0; |
| 120 | }; |
| 121 | |
| 122 | /// NumberExprAST - Expression class for numeric literals like "1.0". |
| 123 | class NumberExprAST : public ExprAST { |
| 124 | double Val; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 125 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 126 | public: |
| 127 | NumberExprAST(double val) : Val(val) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 128 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 129 | }; |
| 130 | |
| 131 | /// VariableExprAST - Expression class for referencing a variable, like "a". |
| 132 | class VariableExprAST : public ExprAST { |
| 133 | std::string Name; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 134 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 135 | public: |
| 136 | VariableExprAST(const std::string &name) : Name(name) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 137 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 138 | }; |
| 139 | |
| 140 | /// BinaryExprAST - Expression class for a binary operator. |
| 141 | class BinaryExprAST : public ExprAST { |
| 142 | char Op; |
| 143 | ExprAST *LHS, *RHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 144 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 145 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 146 | BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) |
| 147 | : Op(op), LHS(lhs), RHS(rhs) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 148 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 149 | }; |
| 150 | |
| 151 | /// CallExprAST - Expression class for function calls. |
| 152 | class CallExprAST : public ExprAST { |
| 153 | std::string Callee; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 154 | std::vector<ExprAST *> Args; |
| 155 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 156 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 157 | CallExprAST(const std::string &callee, std::vector<ExprAST *> &args) |
| 158 | : Callee(callee), Args(args) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 159 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 160 | }; |
| 161 | |
| 162 | /// IfExprAST - Expression class for if/then/else. |
| 163 | class IfExprAST : public ExprAST { |
| 164 | ExprAST *Cond, *Then, *Else; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 165 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 166 | public: |
| 167 | IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 168 | : Cond(cond), Then(then), Else(_else) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 169 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 170 | }; |
| 171 | |
| 172 | /// ForExprAST - Expression class for for/in. |
| 173 | class ForExprAST : public ExprAST { |
| 174 | std::string VarName; |
| 175 | ExprAST *Start, *End, *Step, *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 176 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 177 | public: |
| 178 | ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end, |
| 179 | ExprAST *step, ExprAST *body) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 180 | : VarName(varname), Start(start), End(end), Step(step), Body(body) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame^] | 181 | Value *Codegen() override; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 182 | }; |
| 183 | |
| 184 | /// PrototypeAST - This class represents the "prototype" for a function, |
| 185 | /// which captures its name, and its argument names (thus implicitly the number |
| 186 | /// of arguments the function takes). |
| 187 | class PrototypeAST { |
| 188 | std::string Name; |
| 189 | std::vector<std::string> Args; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 190 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 191 | public: |
| 192 | PrototypeAST(const std::string &name, const std::vector<std::string> &args) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 193 | : Name(name), Args(args) {} |
| 194 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 195 | Function *Codegen(); |
| 196 | }; |
| 197 | |
| 198 | /// FunctionAST - This class represents a function definition itself. |
| 199 | class FunctionAST { |
| 200 | PrototypeAST *Proto; |
| 201 | ExprAST *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 202 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 203 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 204 | FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {} |
| 205 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 206 | Function *Codegen(); |
| 207 | }; |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 208 | } // end anonymous namespace |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 209 | |
| 210 | //===----------------------------------------------------------------------===// |
| 211 | // Parser |
| 212 | //===----------------------------------------------------------------------===// |
| 213 | |
| 214 | /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current |
| 215 | /// token the parser is looking at. getNextToken reads another token from the |
| 216 | /// lexer and updates CurTok with its results. |
| 217 | static int CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 218 | static int getNextToken() { return CurTok = gettok(); } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 219 | |
| 220 | /// BinopPrecedence - This holds the precedence for each binary operator that is |
| 221 | /// defined. |
| 222 | static std::map<char, int> BinopPrecedence; |
| 223 | |
| 224 | /// GetTokPrecedence - Get the precedence of the pending binary operator token. |
| 225 | static int GetTokPrecedence() { |
| 226 | if (!isascii(CurTok)) |
| 227 | return -1; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 228 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 229 | // Make sure it's a declared binop. |
| 230 | int TokPrec = BinopPrecedence[CurTok]; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 231 | if (TokPrec <= 0) |
| 232 | return -1; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 233 | return TokPrec; |
| 234 | } |
| 235 | |
| 236 | /// Error* - These are little helper functions for error handling. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 237 | ExprAST *Error(const char *Str) { |
| 238 | fprintf(stderr, "Error: %s\n", Str); |
| 239 | return 0; |
| 240 | } |
| 241 | PrototypeAST *ErrorP(const char *Str) { |
| 242 | Error(Str); |
| 243 | return 0; |
| 244 | } |
| 245 | FunctionAST *ErrorF(const char *Str) { |
| 246 | Error(Str); |
| 247 | return 0; |
| 248 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 249 | |
| 250 | static ExprAST *ParseExpression(); |
| 251 | |
| 252 | /// identifierexpr |
| 253 | /// ::= identifier |
| 254 | /// ::= identifier '(' expression* ')' |
| 255 | static ExprAST *ParseIdentifierExpr() { |
| 256 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 257 | |
| 258 | getNextToken(); // eat identifier. |
| 259 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 260 | if (CurTok != '(') // Simple variable ref. |
| 261 | return new VariableExprAST(IdName); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 262 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 263 | // Call. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 264 | getNextToken(); // eat ( |
| 265 | std::vector<ExprAST *> Args; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 266 | if (CurTok != ')') { |
| 267 | while (1) { |
| 268 | ExprAST *Arg = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 269 | if (!Arg) |
| 270 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 271 | Args.push_back(Arg); |
| 272 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 273 | if (CurTok == ')') |
| 274 | break; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 275 | |
| 276 | if (CurTok != ',') |
| 277 | return Error("Expected ')' or ',' in argument list"); |
| 278 | getNextToken(); |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Eat the ')'. |
| 283 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 284 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 285 | return new CallExprAST(IdName, Args); |
| 286 | } |
| 287 | |
| 288 | /// numberexpr ::= number |
| 289 | static ExprAST *ParseNumberExpr() { |
| 290 | ExprAST *Result = new NumberExprAST(NumVal); |
| 291 | getNextToken(); // consume the number |
| 292 | return Result; |
| 293 | } |
| 294 | |
| 295 | /// parenexpr ::= '(' expression ')' |
| 296 | static ExprAST *ParseParenExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 297 | getNextToken(); // eat (. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 298 | ExprAST *V = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 299 | if (!V) |
| 300 | return 0; |
| 301 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 302 | if (CurTok != ')') |
| 303 | return Error("expected ')'"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 304 | getNextToken(); // eat ). |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 305 | return V; |
| 306 | } |
| 307 | |
| 308 | /// ifexpr ::= 'if' expression 'then' expression 'else' expression |
| 309 | static ExprAST *ParseIfExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 310 | getNextToken(); // eat the if. |
| 311 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 312 | // condition. |
| 313 | ExprAST *Cond = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 314 | if (!Cond) |
| 315 | return 0; |
| 316 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 317 | if (CurTok != tok_then) |
| 318 | return Error("expected then"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 319 | getNextToken(); // eat the then |
| 320 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 321 | ExprAST *Then = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 322 | if (Then == 0) |
| 323 | return 0; |
| 324 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 325 | if (CurTok != tok_else) |
| 326 | return Error("expected else"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 327 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 328 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 329 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 330 | ExprAST *Else = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 331 | if (!Else) |
| 332 | return 0; |
| 333 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 334 | return new IfExprAST(Cond, Then, Else); |
| 335 | } |
| 336 | |
| 337 | /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression |
| 338 | static ExprAST *ParseForExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 339 | getNextToken(); // eat the for. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 340 | |
| 341 | if (CurTok != tok_identifier) |
| 342 | return Error("expected identifier after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 343 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 344 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 345 | getNextToken(); // eat identifier. |
| 346 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 347 | if (CurTok != '=') |
| 348 | return Error("expected '=' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 349 | getNextToken(); // eat '='. |
| 350 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 351 | ExprAST *Start = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 352 | if (Start == 0) |
| 353 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 354 | if (CurTok != ',') |
| 355 | return Error("expected ',' after for start value"); |
| 356 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 357 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 358 | ExprAST *End = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 359 | if (End == 0) |
| 360 | return 0; |
| 361 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 362 | // The step value is optional. |
| 363 | ExprAST *Step = 0; |
| 364 | if (CurTok == ',') { |
| 365 | getNextToken(); |
| 366 | Step = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 367 | if (Step == 0) |
| 368 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 369 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 370 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 371 | if (CurTok != tok_in) |
| 372 | return Error("expected 'in' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 373 | getNextToken(); // eat 'in'. |
| 374 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 375 | ExprAST *Body = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 376 | if (Body == 0) |
| 377 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 378 | |
| 379 | return new ForExprAST(IdName, Start, End, Step, Body); |
| 380 | } |
| 381 | |
| 382 | /// primary |
| 383 | /// ::= identifierexpr |
| 384 | /// ::= numberexpr |
| 385 | /// ::= parenexpr |
| 386 | /// ::= ifexpr |
| 387 | /// ::= forexpr |
| 388 | static ExprAST *ParsePrimary() { |
| 389 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 390 | default: |
| 391 | return Error("unknown token when expecting an expression"); |
| 392 | case tok_identifier: |
| 393 | return ParseIdentifierExpr(); |
| 394 | case tok_number: |
| 395 | return ParseNumberExpr(); |
| 396 | case '(': |
| 397 | return ParseParenExpr(); |
| 398 | case tok_if: |
| 399 | return ParseIfExpr(); |
| 400 | case tok_for: |
| 401 | return ParseForExpr(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 402 | } |
| 403 | } |
| 404 | |
| 405 | /// binoprhs |
| 406 | /// ::= ('+' primary)* |
| 407 | static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) { |
| 408 | // If this is a binop, find its precedence. |
| 409 | while (1) { |
| 410 | int TokPrec = GetTokPrecedence(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 411 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 412 | // If this is a binop that binds at least as tightly as the current binop, |
| 413 | // consume it, otherwise we are done. |
| 414 | if (TokPrec < ExprPrec) |
| 415 | return LHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 416 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 417 | // Okay, we know this is a binop. |
| 418 | int BinOp = CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 419 | getNextToken(); // eat binop |
| 420 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 421 | // Parse the primary expression after the binary operator. |
| 422 | ExprAST *RHS = ParsePrimary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 423 | if (!RHS) |
| 424 | return 0; |
| 425 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 426 | // If BinOp binds less tightly with RHS than the operator after RHS, let |
| 427 | // the pending operator take RHS as its LHS. |
| 428 | int NextPrec = GetTokPrecedence(); |
| 429 | if (TokPrec < NextPrec) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 430 | RHS = ParseBinOpRHS(TokPrec + 1, RHS); |
| 431 | if (RHS == 0) |
| 432 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 433 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 434 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 435 | // Merge LHS/RHS. |
| 436 | LHS = new BinaryExprAST(BinOp, LHS, RHS); |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /// expression |
| 441 | /// ::= primary binoprhs |
| 442 | /// |
| 443 | static ExprAST *ParseExpression() { |
| 444 | ExprAST *LHS = ParsePrimary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 445 | if (!LHS) |
| 446 | return 0; |
| 447 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 448 | return ParseBinOpRHS(0, LHS); |
| 449 | } |
| 450 | |
| 451 | /// prototype |
| 452 | /// ::= id '(' id* ')' |
| 453 | static PrototypeAST *ParsePrototype() { |
| 454 | if (CurTok != tok_identifier) |
| 455 | return ErrorP("Expected function name in prototype"); |
| 456 | |
| 457 | std::string FnName = IdentifierStr; |
| 458 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 459 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 460 | if (CurTok != '(') |
| 461 | return ErrorP("Expected '(' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 462 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 463 | std::vector<std::string> ArgNames; |
| 464 | while (getNextToken() == tok_identifier) |
| 465 | ArgNames.push_back(IdentifierStr); |
| 466 | if (CurTok != ')') |
| 467 | return ErrorP("Expected ')' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 468 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 469 | // success. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 470 | getNextToken(); // eat ')'. |
| 471 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 472 | return new PrototypeAST(FnName, ArgNames); |
| 473 | } |
| 474 | |
| 475 | /// definition ::= 'def' prototype expression |
| 476 | static FunctionAST *ParseDefinition() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 477 | getNextToken(); // eat def. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 478 | PrototypeAST *Proto = ParsePrototype(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 479 | if (Proto == 0) |
| 480 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 481 | |
| 482 | if (ExprAST *E = ParseExpression()) |
| 483 | return new FunctionAST(Proto, E); |
| 484 | return 0; |
| 485 | } |
| 486 | |
| 487 | /// toplevelexpr ::= expression |
| 488 | static FunctionAST *ParseTopLevelExpr() { |
| 489 | if (ExprAST *E = ParseExpression()) { |
| 490 | // Make an anonymous proto. |
| 491 | PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); |
| 492 | return new FunctionAST(Proto, E); |
| 493 | } |
| 494 | return 0; |
| 495 | } |
| 496 | |
| 497 | /// external ::= 'extern' prototype |
| 498 | static PrototypeAST *ParseExtern() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 499 | getNextToken(); // eat extern. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 500 | return ParsePrototype(); |
| 501 | } |
| 502 | |
| 503 | //===----------------------------------------------------------------------===// |
| 504 | // Code Generation |
| 505 | //===----------------------------------------------------------------------===// |
| 506 | |
| 507 | static Module *TheModule; |
| 508 | static IRBuilder<> Builder(getGlobalContext()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 509 | static std::map<std::string, Value *> NamedValues; |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 510 | static legacy::FunctionPassManager *TheFPM; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 511 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 512 | Value *ErrorV(const char *Str) { |
| 513 | Error(Str); |
| 514 | return 0; |
| 515 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 516 | |
| 517 | Value *NumberExprAST::Codegen() { |
| 518 | return ConstantFP::get(getGlobalContext(), APFloat(Val)); |
| 519 | } |
| 520 | |
| 521 | Value *VariableExprAST::Codegen() { |
| 522 | // Look this variable up in the function. |
| 523 | Value *V = NamedValues[Name]; |
| 524 | return V ? V : ErrorV("Unknown variable name"); |
| 525 | } |
| 526 | |
| 527 | Value *BinaryExprAST::Codegen() { |
| 528 | Value *L = LHS->Codegen(); |
| 529 | Value *R = RHS->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 530 | if (L == 0 || R == 0) |
| 531 | return 0; |
| 532 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 533 | switch (Op) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 534 | case '+': |
| 535 | return Builder.CreateFAdd(L, R, "addtmp"); |
| 536 | case '-': |
| 537 | return Builder.CreateFSub(L, R, "subtmp"); |
| 538 | case '*': |
| 539 | return Builder.CreateFMul(L, R, "multmp"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 540 | case '<': |
| 541 | L = Builder.CreateFCmpULT(L, R, "cmptmp"); |
| 542 | // Convert bool 0/1 to double 0.0 or 1.0 |
| 543 | return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()), |
| 544 | "booltmp"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 545 | default: |
| 546 | return ErrorV("invalid binary operator"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 547 | } |
| 548 | } |
| 549 | |
| 550 | Value *CallExprAST::Codegen() { |
| 551 | // Look up the name in the global module table. |
| 552 | Function *CalleeF = TheModule->getFunction(Callee); |
| 553 | if (CalleeF == 0) |
| 554 | return ErrorV("Unknown function referenced"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 555 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 556 | // If argument mismatch error. |
| 557 | if (CalleeF->arg_size() != Args.size()) |
| 558 | return ErrorV("Incorrect # arguments passed"); |
| 559 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 560 | std::vector<Value *> ArgsV; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 561 | for (unsigned i = 0, e = Args.size(); i != e; ++i) { |
| 562 | ArgsV.push_back(Args[i]->Codegen()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 563 | if (ArgsV.back() == 0) |
| 564 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 565 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 566 | |
Francois Pichet | c5d1050 | 2011-07-15 10:59:52 +0000 | [diff] [blame] | 567 | return Builder.CreateCall(CalleeF, ArgsV, "calltmp"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 568 | } |
| 569 | |
| 570 | Value *IfExprAST::Codegen() { |
| 571 | Value *CondV = Cond->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 572 | if (CondV == 0) |
| 573 | return 0; |
| 574 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 575 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 576 | CondV = Builder.CreateFCmpONE( |
| 577 | CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond"); |
| 578 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 579 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 580 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 581 | // Create blocks for the then and else cases. Insert the 'then' block at the |
| 582 | // end of the function. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 583 | BasicBlock *ThenBB = |
| 584 | BasicBlock::Create(getGlobalContext(), "then", TheFunction); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 585 | BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else"); |
| 586 | BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 587 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 588 | Builder.CreateCondBr(CondV, ThenBB, ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 589 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 590 | // Emit then value. |
| 591 | Builder.SetInsertPoint(ThenBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 592 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 593 | Value *ThenV = Then->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 594 | if (ThenV == 0) |
| 595 | return 0; |
| 596 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 597 | Builder.CreateBr(MergeBB); |
| 598 | // Codegen of 'Then' can change the current block, update ThenBB for the PHI. |
| 599 | ThenBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 600 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 601 | // Emit else block. |
| 602 | TheFunction->getBasicBlockList().push_back(ElseBB); |
| 603 | Builder.SetInsertPoint(ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 604 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 605 | Value *ElseV = Else->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 606 | if (ElseV == 0) |
| 607 | return 0; |
| 608 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 609 | Builder.CreateBr(MergeBB); |
| 610 | // Codegen of 'Else' can change the current block, update ElseBB for the PHI. |
| 611 | ElseBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 612 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 613 | // Emit merge block. |
| 614 | TheFunction->getBasicBlockList().push_back(MergeBB); |
| 615 | Builder.SetInsertPoint(MergeBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 616 | PHINode *PN = |
| 617 | Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp"); |
| 618 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 619 | PN->addIncoming(ThenV, ThenBB); |
| 620 | PN->addIncoming(ElseV, ElseBB); |
| 621 | return PN; |
| 622 | } |
| 623 | |
| 624 | Value *ForExprAST::Codegen() { |
| 625 | // Output this as: |
| 626 | // ... |
| 627 | // start = startexpr |
| 628 | // goto loop |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 629 | // loop: |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 630 | // variable = phi [start, loopheader], [nextvariable, loopend] |
| 631 | // ... |
| 632 | // bodyexpr |
| 633 | // ... |
| 634 | // loopend: |
| 635 | // step = stepexpr |
| 636 | // nextvariable = variable + step |
| 637 | // endcond = endexpr |
| 638 | // br endcond, loop, endloop |
| 639 | // outloop: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 640 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 641 | // Emit the start code first, without 'variable' in scope. |
| 642 | Value *StartVal = Start->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 643 | if (StartVal == 0) |
| 644 | return 0; |
| 645 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 646 | // Make the new basic block for the loop header, inserting after current |
| 647 | // block. |
| 648 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
| 649 | BasicBlock *PreheaderBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 650 | BasicBlock *LoopBB = |
| 651 | BasicBlock::Create(getGlobalContext(), "loop", TheFunction); |
| 652 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 653 | // Insert an explicit fall through from the current block to the LoopBB. |
| 654 | Builder.CreateBr(LoopBB); |
| 655 | |
| 656 | // Start insertion in LoopBB. |
| 657 | Builder.SetInsertPoint(LoopBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 658 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 659 | // Start the PHI node with an entry for Start. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 660 | PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), |
| 661 | 2, VarName.c_str()); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 662 | Variable->addIncoming(StartVal, PreheaderBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 663 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 664 | // Within the loop, the variable is defined equal to the PHI node. If it |
| 665 | // shadows an existing variable, we have to restore it, so save it now. |
| 666 | Value *OldVal = NamedValues[VarName]; |
| 667 | NamedValues[VarName] = Variable; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 668 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 669 | // Emit the body of the loop. This, like any other expr, can change the |
| 670 | // current BB. Note that we ignore the value computed by the body, but don't |
| 671 | // allow an error. |
| 672 | if (Body->Codegen() == 0) |
| 673 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 674 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 675 | // Emit the step value. |
| 676 | Value *StepVal; |
| 677 | if (Step) { |
| 678 | StepVal = Step->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 679 | if (StepVal == 0) |
| 680 | return 0; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 681 | } else { |
| 682 | // If not specified, use 1.0. |
| 683 | StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); |
| 684 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 685 | |
Chris Lattner | 26d7950 | 2010-06-21 22:51:14 +0000 | [diff] [blame] | 686 | Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar"); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 687 | |
| 688 | // Compute the end condition. |
| 689 | Value *EndCond = End->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 690 | if (EndCond == 0) |
| 691 | return EndCond; |
| 692 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 693 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 694 | EndCond = Builder.CreateFCmpONE( |
| 695 | EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond"); |
| 696 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 697 | // Create the "after loop" block and insert it. |
| 698 | BasicBlock *LoopEndBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 699 | BasicBlock *AfterBB = |
| 700 | BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); |
| 701 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 702 | // Insert the conditional branch into the end of LoopEndBB. |
| 703 | Builder.CreateCondBr(EndCond, LoopBB, AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 704 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 705 | // Any new code will be inserted in AfterBB. |
| 706 | Builder.SetInsertPoint(AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 707 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 708 | // Add a new entry to the PHI node for the backedge. |
| 709 | Variable->addIncoming(NextVar, LoopEndBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 710 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 711 | // Restore the unshadowed variable. |
| 712 | if (OldVal) |
| 713 | NamedValues[VarName] = OldVal; |
| 714 | else |
| 715 | NamedValues.erase(VarName); |
| 716 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 717 | // for expr always returns 0.0. |
| 718 | return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); |
| 719 | } |
| 720 | |
| 721 | Function *PrototypeAST::Codegen() { |
| 722 | // Make the function type: double(double,double) etc. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 723 | std::vector<Type *> Doubles(Args.size(), |
| 724 | Type::getDoubleTy(getGlobalContext())); |
| 725 | FunctionType *FT = |
| 726 | FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false); |
| 727 | |
| 728 | Function *F = |
| 729 | Function::Create(FT, Function::ExternalLinkage, Name, TheModule); |
| 730 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 731 | // If F conflicted, there was already something named 'Name'. If it has a |
| 732 | // body, don't allow redefinition or reextern. |
| 733 | if (F->getName() != Name) { |
| 734 | // Delete the one we just made and get the existing one. |
| 735 | F->eraseFromParent(); |
| 736 | F = TheModule->getFunction(Name); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 737 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 738 | // If F already has a body, reject this. |
| 739 | if (!F->empty()) { |
| 740 | ErrorF("redefinition of function"); |
| 741 | return 0; |
| 742 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 743 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 744 | // If F took a different number of args, reject. |
| 745 | if (F->arg_size() != Args.size()) { |
| 746 | ErrorF("redefinition of function with different # args"); |
| 747 | return 0; |
| 748 | } |
| 749 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 750 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 751 | // Set names for all arguments. |
| 752 | unsigned Idx = 0; |
| 753 | for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size(); |
| 754 | ++AI, ++Idx) { |
| 755 | AI->setName(Args[Idx]); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 756 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 757 | // Add arguments to variable symbol table. |
| 758 | NamedValues[Args[Idx]] = AI; |
| 759 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 760 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 761 | return F; |
| 762 | } |
| 763 | |
| 764 | Function *FunctionAST::Codegen() { |
| 765 | NamedValues.clear(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 766 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 767 | Function *TheFunction = Proto->Codegen(); |
| 768 | if (TheFunction == 0) |
| 769 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 770 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 771 | // Create a new basic block to start insertion into. |
| 772 | BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction); |
| 773 | Builder.SetInsertPoint(BB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 774 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 775 | if (Value *RetVal = Body->Codegen()) { |
| 776 | // Finish off the function. |
| 777 | Builder.CreateRet(RetVal); |
| 778 | |
| 779 | // Validate the generated code, checking for consistency. |
| 780 | verifyFunction(*TheFunction); |
| 781 | |
| 782 | // Optimize the function. |
| 783 | TheFPM->run(*TheFunction); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 784 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 785 | return TheFunction; |
| 786 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 787 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 788 | // Error reading body, remove function. |
| 789 | TheFunction->eraseFromParent(); |
| 790 | return 0; |
| 791 | } |
| 792 | |
| 793 | //===----------------------------------------------------------------------===// |
| 794 | // Top-Level parsing and JIT Driver |
| 795 | //===----------------------------------------------------------------------===// |
| 796 | |
| 797 | static ExecutionEngine *TheExecutionEngine; |
| 798 | |
| 799 | static void HandleDefinition() { |
| 800 | if (FunctionAST *F = ParseDefinition()) { |
| 801 | if (Function *LF = F->Codegen()) { |
| 802 | fprintf(stderr, "Read function definition:"); |
| 803 | LF->dump(); |
| 804 | } |
| 805 | } else { |
| 806 | // Skip token for error recovery. |
| 807 | getNextToken(); |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | static void HandleExtern() { |
| 812 | if (PrototypeAST *P = ParseExtern()) { |
| 813 | if (Function *F = P->Codegen()) { |
| 814 | fprintf(stderr, "Read extern: "); |
| 815 | F->dump(); |
| 816 | } |
| 817 | } else { |
| 818 | // Skip token for error recovery. |
| 819 | getNextToken(); |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | static void HandleTopLevelExpression() { |
| 824 | // Evaluate a top-level expression into an anonymous function. |
| 825 | if (FunctionAST *F = ParseTopLevelExpr()) { |
| 826 | if (Function *LF = F->Codegen()) { |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 827 | TheExecutionEngine->finalizeObject(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 828 | // JIT the function, returning a function pointer. |
| 829 | void *FPtr = TheExecutionEngine->getPointerToFunction(LF); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 830 | |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 831 | // Cast it to the right type (takes no arguments, returns a double) so we |
| 832 | // can call it as a native function. |
| 833 | double (*FP)() = (double (*)())(intptr_t)FPtr; |
| 834 | fprintf(stderr, "Evaluated to %f\n", FP()); |
| 835 | } |
| 836 | } else { |
| 837 | // Skip token for error recovery. |
| 838 | getNextToken(); |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | /// top ::= definition | external | expression | ';' |
| 843 | static void MainLoop() { |
| 844 | while (1) { |
| 845 | fprintf(stderr, "ready> "); |
| 846 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 847 | case tok_eof: |
| 848 | return; |
| 849 | case ';': |
| 850 | getNextToken(); |
| 851 | break; // ignore top-level semicolons. |
| 852 | case tok_def: |
| 853 | HandleDefinition(); |
| 854 | break; |
| 855 | case tok_extern: |
| 856 | HandleExtern(); |
| 857 | break; |
| 858 | default: |
| 859 | HandleTopLevelExpression(); |
| 860 | break; |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 861 | } |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | //===----------------------------------------------------------------------===// |
| 866 | // "Library" functions that can be "extern'd" from user code. |
| 867 | //===----------------------------------------------------------------------===// |
| 868 | |
| 869 | /// putchard - putchar that takes a double and returns 0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 870 | extern "C" double putchard(double X) { |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 871 | putchar((char)X); |
| 872 | return 0; |
| 873 | } |
| 874 | |
| 875 | //===----------------------------------------------------------------------===// |
| 876 | // Main driver code. |
| 877 | //===----------------------------------------------------------------------===// |
| 878 | |
| 879 | int main() { |
| 880 | InitializeNativeTarget(); |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 881 | InitializeNativeTargetAsmPrinter(); |
| 882 | InitializeNativeTargetAsmParser(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 883 | LLVMContext &Context = getGlobalContext(); |
| 884 | |
| 885 | // Install standard binary operators. |
| 886 | // 1 is lowest precedence. |
| 887 | BinopPrecedence['<'] = 10; |
| 888 | BinopPrecedence['+'] = 20; |
| 889 | BinopPrecedence['-'] = 20; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 890 | BinopPrecedence['*'] = 40; // highest. |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 891 | |
| 892 | // Prime the first token. |
| 893 | fprintf(stderr, "ready> "); |
| 894 | getNextToken(); |
| 895 | |
| 896 | // Make the module, which holds all the code. |
Rafael Espindola | 2a8a279 | 2014-08-19 04:04:25 +0000 | [diff] [blame] | 897 | std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context); |
| 898 | TheModule = Owner.get(); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 899 | |
Jeffrey Yasskin | 091217b | 2010-01-27 20:34:15 +0000 | [diff] [blame] | 900 | // Create the JIT. This takes ownership of the module. |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 901 | std::string ErrStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 902 | TheExecutionEngine = |
| 903 | EngineBuilder(std::move(Owner)) |
| 904 | .setErrorStr(&ErrStr) |
| 905 | .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>()) |
| 906 | .create(); |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 907 | if (!TheExecutionEngine) { |
| 908 | fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); |
| 909 | exit(1); |
| 910 | } |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 911 | |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 912 | legacy::FunctionPassManager OurFPM(TheModule); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 913 | |
| 914 | // Set up the optimizer pipeline. Start with registering info about how the |
| 915 | // target lays out data structures. |
Rafael Espindola | 265ffbe | 2015-03-04 19:15:29 +0000 | [diff] [blame] | 916 | TheModule->setDataLayout(*TheExecutionEngine->getDataLayout()); |
Dan Gohman | 56f3a4c | 2010-11-15 18:41:10 +0000 | [diff] [blame] | 917 | // Provide basic AliasAnalysis support for GVN. |
| 918 | OurFPM.add(createBasicAliasAnalysisPass()); |
Erick Tryzelaar | 21e83ea | 2009-09-22 21:15:19 +0000 | [diff] [blame] | 919 | // Do simple "peephole" optimizations and bit-twiddling optzns. |
| 920 | OurFPM.add(createInstructionCombiningPass()); |
| 921 | // Reassociate expressions. |
| 922 | OurFPM.add(createReassociatePass()); |
| 923 | // Eliminate Common SubExpressions. |
| 924 | OurFPM.add(createGVNPass()); |
| 925 | // Simplify the control flow graph (deleting unreachable blocks, etc). |
| 926 | OurFPM.add(createCFGSimplificationPass()); |
| 927 | |
| 928 | OurFPM.doInitialization(); |
| 929 | |
| 930 | // Set the global so the code gen can use this. |
| 931 | TheFPM = &OurFPM; |
| 932 | |
| 933 | // Run the main "interpreter loop" now. |
| 934 | MainLoop(); |
| 935 | |
| 936 | TheFPM = 0; |
| 937 | |
| 938 | // Print out all of the generated code. |
| 939 | TheModule->dump(); |
| 940 | |
| 941 | return 0; |
| 942 | } |