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" |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +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> |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 16 | #include <cstdio> |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 17 | #include <map> |
Chandler Carruth | 605e30e | 2012-12-04 10:16:57 +0000 | [diff] [blame] | 18 | #include <string> |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +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, |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +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 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +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, |
| 45 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 46 | // operators |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 47 | tok_binary = -11, |
| 48 | tok_unary = -12, |
| 49 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 50 | // var definition |
| 51 | tok_var = -13 |
| 52 | }; |
| 53 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 54 | static std::string IdentifierStr; // Filled in if tok_identifier |
| 55 | static double NumVal; // Filled in if tok_number |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 56 | |
| 57 | /// gettok - Return the next token from standard input. |
| 58 | static int gettok() { |
| 59 | static int LastChar = ' '; |
| 60 | |
| 61 | // Skip any whitespace. |
| 62 | while (isspace(LastChar)) |
| 63 | LastChar = getchar(); |
| 64 | |
| 65 | if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]* |
| 66 | IdentifierStr = LastChar; |
| 67 | while (isalnum((LastChar = getchar()))) |
| 68 | IdentifierStr += LastChar; |
| 69 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 70 | if (IdentifierStr == "def") |
| 71 | return tok_def; |
| 72 | if (IdentifierStr == "extern") |
| 73 | return tok_extern; |
| 74 | if (IdentifierStr == "if") |
| 75 | return tok_if; |
| 76 | if (IdentifierStr == "then") |
| 77 | return tok_then; |
| 78 | if (IdentifierStr == "else") |
| 79 | return tok_else; |
| 80 | if (IdentifierStr == "for") |
| 81 | return tok_for; |
| 82 | if (IdentifierStr == "in") |
| 83 | return tok_in; |
| 84 | if (IdentifierStr == "binary") |
| 85 | return tok_binary; |
| 86 | if (IdentifierStr == "unary") |
| 87 | return tok_unary; |
| 88 | if (IdentifierStr == "var") |
| 89 | return tok_var; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 90 | return tok_identifier; |
| 91 | } |
| 92 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 93 | if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+ |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 94 | std::string NumStr; |
| 95 | do { |
| 96 | NumStr += LastChar; |
| 97 | LastChar = getchar(); |
| 98 | } while (isdigit(LastChar) || LastChar == '.'); |
| 99 | |
| 100 | NumVal = strtod(NumStr.c_str(), 0); |
| 101 | return tok_number; |
| 102 | } |
| 103 | |
| 104 | if (LastChar == '#') { |
| 105 | // Comment until end of line. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 106 | do |
| 107 | LastChar = getchar(); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 108 | while (LastChar != EOF && LastChar != '\n' && LastChar != '\r'); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 109 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 110 | if (LastChar != EOF) |
| 111 | return gettok(); |
| 112 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 113 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 114 | // Check for end of file. Don't eat the EOF. |
| 115 | if (LastChar == EOF) |
| 116 | return tok_eof; |
| 117 | |
| 118 | // Otherwise, just return the character as its ascii value. |
| 119 | int ThisChar = LastChar; |
| 120 | LastChar = getchar(); |
| 121 | return ThisChar; |
| 122 | } |
| 123 | |
| 124 | //===----------------------------------------------------------------------===// |
| 125 | // Abstract Syntax Tree (aka Parse Tree) |
| 126 | //===----------------------------------------------------------------------===// |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 127 | namespace { |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 128 | /// ExprAST - Base class for all expression nodes. |
| 129 | class ExprAST { |
| 130 | public: |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 131 | virtual ~ExprAST() {} |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 132 | virtual Value *Codegen() = 0; |
| 133 | }; |
| 134 | |
| 135 | /// NumberExprAST - Expression class for numeric literals like "1.0". |
| 136 | class NumberExprAST : public ExprAST { |
| 137 | double Val; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 138 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 139 | public: |
| 140 | NumberExprAST(double val) : Val(val) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 141 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 142 | }; |
| 143 | |
| 144 | /// VariableExprAST - Expression class for referencing a variable, like "a". |
| 145 | class VariableExprAST : public ExprAST { |
| 146 | std::string Name; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 147 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 148 | public: |
| 149 | VariableExprAST(const std::string &name) : Name(name) {} |
| 150 | const std::string &getName() const { return Name; } |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 151 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 152 | }; |
| 153 | |
| 154 | /// UnaryExprAST - Expression class for a unary operator. |
| 155 | class UnaryExprAST : public ExprAST { |
| 156 | char Opcode; |
| 157 | ExprAST *Operand; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 158 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 159 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 160 | UnaryExprAST(char opcode, ExprAST *operand) |
| 161 | : Opcode(opcode), Operand(operand) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 162 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 163 | }; |
| 164 | |
| 165 | /// BinaryExprAST - Expression class for a binary operator. |
| 166 | class BinaryExprAST : public ExprAST { |
| 167 | char Op; |
| 168 | ExprAST *LHS, *RHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 169 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 170 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 171 | BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs) |
| 172 | : Op(op), LHS(lhs), RHS(rhs) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 173 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 174 | }; |
| 175 | |
| 176 | /// CallExprAST - Expression class for function calls. |
| 177 | class CallExprAST : public ExprAST { |
| 178 | std::string Callee; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 179 | std::vector<ExprAST *> Args; |
| 180 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 181 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 182 | CallExprAST(const std::string &callee, std::vector<ExprAST *> &args) |
| 183 | : Callee(callee), Args(args) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 184 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 185 | }; |
| 186 | |
| 187 | /// IfExprAST - Expression class for if/then/else. |
| 188 | class IfExprAST : public ExprAST { |
| 189 | ExprAST *Cond, *Then, *Else; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 190 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 191 | public: |
| 192 | IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 193 | : Cond(cond), Then(then), Else(_else) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 194 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 195 | }; |
| 196 | |
| 197 | /// ForExprAST - Expression class for for/in. |
| 198 | class ForExprAST : public ExprAST { |
| 199 | std::string VarName; |
| 200 | ExprAST *Start, *End, *Step, *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 201 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 202 | public: |
| 203 | ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end, |
| 204 | ExprAST *step, ExprAST *body) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 205 | : VarName(varname), Start(start), End(end), Step(step), Body(body) {} |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 206 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 207 | }; |
| 208 | |
| 209 | /// VarExprAST - Expression class for var/in |
| 210 | class VarExprAST : public ExprAST { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 211 | std::vector<std::pair<std::string, ExprAST *> > VarNames; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 212 | ExprAST *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 213 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 214 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 215 | VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames, |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 216 | ExprAST *body) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 217 | : VarNames(varnames), Body(body) {} |
| 218 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 219 | Value *Codegen() override; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 220 | }; |
| 221 | |
| 222 | /// PrototypeAST - This class represents the "prototype" for a function, |
| 223 | /// which captures its argument names as well as if it is an operator. |
| 224 | class PrototypeAST { |
| 225 | std::string Name; |
| 226 | std::vector<std::string> Args; |
| 227 | bool isOperator; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 228 | unsigned Precedence; // Precedence if a binary op. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 229 | public: |
| 230 | PrototypeAST(const std::string &name, const std::vector<std::string> &args, |
| 231 | bool isoperator = false, unsigned prec = 0) |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 232 | : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {} |
| 233 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 234 | bool isUnaryOp() const { return isOperator && Args.size() == 1; } |
| 235 | bool isBinaryOp() const { return isOperator && Args.size() == 2; } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 236 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 237 | char getOperatorName() const { |
| 238 | assert(isUnaryOp() || isBinaryOp()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 239 | return Name[Name.size() - 1]; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 240 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 241 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 242 | unsigned getBinaryPrecedence() const { return Precedence; } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 243 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 244 | Function *Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 245 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 246 | void CreateArgumentAllocas(Function *F); |
| 247 | }; |
| 248 | |
| 249 | /// FunctionAST - This class represents a function definition itself. |
| 250 | class FunctionAST { |
| 251 | PrototypeAST *Proto; |
| 252 | ExprAST *Body; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 253 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 254 | public: |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 255 | FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {} |
| 256 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 257 | Function *Codegen(); |
| 258 | }; |
Juergen Ributzka | 05c5a93 | 2013-11-19 03:08:35 +0000 | [diff] [blame] | 259 | } // end anonymous namespace |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 260 | |
| 261 | //===----------------------------------------------------------------------===// |
| 262 | // Parser |
| 263 | //===----------------------------------------------------------------------===// |
| 264 | |
| 265 | /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 266 | /// token the parser is looking at. getNextToken reads another token from the |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 267 | /// lexer and updates CurTok with its results. |
| 268 | static int CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 269 | static int getNextToken() { return CurTok = gettok(); } |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 270 | |
| 271 | /// BinopPrecedence - This holds the precedence for each binary operator that is |
| 272 | /// defined. |
| 273 | static std::map<char, int> BinopPrecedence; |
| 274 | |
| 275 | /// GetTokPrecedence - Get the precedence of the pending binary operator token. |
| 276 | static int GetTokPrecedence() { |
| 277 | if (!isascii(CurTok)) |
| 278 | return -1; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 279 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 280 | // Make sure it's a declared binop. |
| 281 | int TokPrec = BinopPrecedence[CurTok]; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 282 | if (TokPrec <= 0) |
| 283 | return -1; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 284 | return TokPrec; |
| 285 | } |
| 286 | |
| 287 | /// Error* - These are little helper functions for error handling. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 288 | ExprAST *Error(const char *Str) { |
| 289 | fprintf(stderr, "Error: %s\n", Str); |
| 290 | return 0; |
| 291 | } |
| 292 | PrototypeAST *ErrorP(const char *Str) { |
| 293 | Error(Str); |
| 294 | return 0; |
| 295 | } |
| 296 | FunctionAST *ErrorF(const char *Str) { |
| 297 | Error(Str); |
| 298 | return 0; |
| 299 | } |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 300 | |
| 301 | static ExprAST *ParseExpression(); |
| 302 | |
| 303 | /// identifierexpr |
| 304 | /// ::= identifier |
| 305 | /// ::= identifier '(' expression* ')' |
| 306 | static ExprAST *ParseIdentifierExpr() { |
| 307 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 308 | |
| 309 | getNextToken(); // eat identifier. |
| 310 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 311 | if (CurTok != '(') // Simple variable ref. |
| 312 | return new VariableExprAST(IdName); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 313 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 314 | // Call. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 315 | getNextToken(); // eat ( |
| 316 | std::vector<ExprAST *> Args; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 317 | if (CurTok != ')') { |
| 318 | while (1) { |
| 319 | ExprAST *Arg = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 320 | if (!Arg) |
| 321 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 322 | Args.push_back(Arg); |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 323 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 324 | if (CurTok == ')') |
| 325 | break; |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 326 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 327 | if (CurTok != ',') |
| 328 | return Error("Expected ')' or ',' in argument list"); |
| 329 | getNextToken(); |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // Eat the ')'. |
| 334 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 335 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 336 | return new CallExprAST(IdName, Args); |
| 337 | } |
| 338 | |
| 339 | /// numberexpr ::= number |
| 340 | static ExprAST *ParseNumberExpr() { |
| 341 | ExprAST *Result = new NumberExprAST(NumVal); |
| 342 | getNextToken(); // consume the number |
| 343 | return Result; |
| 344 | } |
| 345 | |
| 346 | /// parenexpr ::= '(' expression ')' |
| 347 | static ExprAST *ParseParenExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 348 | getNextToken(); // eat (. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 349 | ExprAST *V = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 350 | if (!V) |
| 351 | return 0; |
| 352 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 353 | if (CurTok != ')') |
| 354 | return Error("expected ')'"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 355 | getNextToken(); // eat ). |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 356 | return V; |
| 357 | } |
| 358 | |
| 359 | /// ifexpr ::= 'if' expression 'then' expression 'else' expression |
| 360 | static ExprAST *ParseIfExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 361 | getNextToken(); // eat the if. |
| 362 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 363 | // condition. |
| 364 | ExprAST *Cond = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 365 | if (!Cond) |
| 366 | return 0; |
| 367 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 368 | if (CurTok != tok_then) |
| 369 | return Error("expected then"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 370 | getNextToken(); // eat the then |
| 371 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 372 | ExprAST *Then = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 373 | if (Then == 0) |
| 374 | return 0; |
| 375 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 376 | if (CurTok != tok_else) |
| 377 | return Error("expected else"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 378 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 379 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 380 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 381 | ExprAST *Else = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 382 | if (!Else) |
| 383 | return 0; |
| 384 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 385 | return new IfExprAST(Cond, Then, Else); |
| 386 | } |
| 387 | |
| 388 | /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression |
| 389 | static ExprAST *ParseForExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 390 | getNextToken(); // eat the for. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 391 | |
| 392 | if (CurTok != tok_identifier) |
| 393 | return Error("expected identifier after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 394 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 395 | std::string IdName = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 396 | getNextToken(); // eat identifier. |
| 397 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 398 | if (CurTok != '=') |
| 399 | return Error("expected '=' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 400 | getNextToken(); // eat '='. |
| 401 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 402 | ExprAST *Start = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 403 | if (Start == 0) |
| 404 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 405 | if (CurTok != ',') |
| 406 | return Error("expected ',' after for start value"); |
| 407 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 408 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 409 | ExprAST *End = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 410 | if (End == 0) |
| 411 | return 0; |
| 412 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 413 | // The step value is optional. |
| 414 | ExprAST *Step = 0; |
| 415 | if (CurTok == ',') { |
| 416 | getNextToken(); |
| 417 | Step = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 418 | if (Step == 0) |
| 419 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 420 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 421 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 422 | if (CurTok != tok_in) |
| 423 | return Error("expected 'in' after for"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 424 | getNextToken(); // eat 'in'. |
| 425 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 426 | ExprAST *Body = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 427 | if (Body == 0) |
| 428 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 429 | |
| 430 | return new ForExprAST(IdName, Start, End, Step, Body); |
| 431 | } |
| 432 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 433 | /// varexpr ::= 'var' identifier ('=' expression)? |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 434 | // (',' identifier ('=' expression)?)* 'in' expression |
| 435 | static ExprAST *ParseVarExpr() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 436 | getNextToken(); // eat the var. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 437 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 438 | std::vector<std::pair<std::string, ExprAST *> > VarNames; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 439 | |
| 440 | // At least one variable name is required. |
| 441 | if (CurTok != tok_identifier) |
| 442 | return Error("expected identifier after var"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 443 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 444 | while (1) { |
| 445 | std::string Name = IdentifierStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 446 | getNextToken(); // eat identifier. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 447 | |
| 448 | // Read the optional initializer. |
| 449 | ExprAST *Init = 0; |
| 450 | if (CurTok == '=') { |
| 451 | getNextToken(); // eat the '='. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 452 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 453 | Init = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 454 | if (Init == 0) |
| 455 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 456 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 457 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 458 | VarNames.push_back(std::make_pair(Name, Init)); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 459 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 460 | // End of var list, exit loop. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 461 | if (CurTok != ',') |
| 462 | break; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 463 | getNextToken(); // eat the ','. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 464 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 465 | if (CurTok != tok_identifier) |
| 466 | return Error("expected identifier list after var"); |
| 467 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 468 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 469 | // At this point, we have to have 'in'. |
| 470 | if (CurTok != tok_in) |
| 471 | return Error("expected 'in' keyword after 'var'"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 472 | getNextToken(); // eat 'in'. |
| 473 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 474 | ExprAST *Body = ParseExpression(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 475 | if (Body == 0) |
| 476 | return 0; |
| 477 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 478 | return new VarExprAST(VarNames, Body); |
| 479 | } |
| 480 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 481 | /// primary |
| 482 | /// ::= identifierexpr |
| 483 | /// ::= numberexpr |
| 484 | /// ::= parenexpr |
| 485 | /// ::= ifexpr |
| 486 | /// ::= forexpr |
| 487 | /// ::= varexpr |
| 488 | static ExprAST *ParsePrimary() { |
| 489 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 490 | default: |
| 491 | return Error("unknown token when expecting an expression"); |
| 492 | case tok_identifier: |
| 493 | return ParseIdentifierExpr(); |
| 494 | case tok_number: |
| 495 | return ParseNumberExpr(); |
| 496 | case '(': |
| 497 | return ParseParenExpr(); |
| 498 | case tok_if: |
| 499 | return ParseIfExpr(); |
| 500 | case tok_for: |
| 501 | return ParseForExpr(); |
| 502 | case tok_var: |
| 503 | return ParseVarExpr(); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 504 | } |
| 505 | } |
| 506 | |
| 507 | /// unary |
| 508 | /// ::= primary |
| 509 | /// ::= '!' unary |
| 510 | static ExprAST *ParseUnary() { |
| 511 | // If the current token is not an operator, it must be a primary expr. |
| 512 | if (!isascii(CurTok) || CurTok == '(' || CurTok == ',') |
| 513 | return ParsePrimary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 514 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 515 | // If this is a unary operator, read it. |
| 516 | int Opc = CurTok; |
| 517 | getNextToken(); |
| 518 | if (ExprAST *Operand = ParseUnary()) |
| 519 | return new UnaryExprAST(Opc, Operand); |
| 520 | return 0; |
| 521 | } |
| 522 | |
| 523 | /// binoprhs |
| 524 | /// ::= ('+' unary)* |
| 525 | static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) { |
| 526 | // If this is a binop, find its precedence. |
| 527 | while (1) { |
| 528 | int TokPrec = GetTokPrecedence(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 529 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 530 | // If this is a binop that binds at least as tightly as the current binop, |
| 531 | // consume it, otherwise we are done. |
| 532 | if (TokPrec < ExprPrec) |
| 533 | return LHS; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 534 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 535 | // Okay, we know this is a binop. |
| 536 | int BinOp = CurTok; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 537 | getNextToken(); // eat binop |
| 538 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 539 | // Parse the unary expression after the binary operator. |
| 540 | ExprAST *RHS = ParseUnary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 541 | if (!RHS) |
| 542 | return 0; |
| 543 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 544 | // If BinOp binds less tightly with RHS than the operator after RHS, let |
| 545 | // the pending operator take RHS as its LHS. |
| 546 | int NextPrec = GetTokPrecedence(); |
| 547 | if (TokPrec < NextPrec) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 548 | RHS = ParseBinOpRHS(TokPrec + 1, RHS); |
| 549 | if (RHS == 0) |
| 550 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 551 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 552 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 553 | // Merge LHS/RHS. |
| 554 | LHS = new BinaryExprAST(BinOp, LHS, RHS); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /// expression |
| 559 | /// ::= unary binoprhs |
| 560 | /// |
| 561 | static ExprAST *ParseExpression() { |
| 562 | ExprAST *LHS = ParseUnary(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 563 | if (!LHS) |
| 564 | return 0; |
| 565 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 566 | return ParseBinOpRHS(0, LHS); |
| 567 | } |
| 568 | |
| 569 | /// prototype |
| 570 | /// ::= id '(' id* ')' |
| 571 | /// ::= binary LETTER number? (id, id) |
| 572 | /// ::= unary LETTER (id) |
| 573 | static PrototypeAST *ParsePrototype() { |
| 574 | std::string FnName; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 575 | |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 576 | unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 577 | unsigned BinaryPrecedence = 30; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 578 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 579 | switch (CurTok) { |
| 580 | default: |
| 581 | return ErrorP("Expected function name in prototype"); |
| 582 | case tok_identifier: |
| 583 | FnName = IdentifierStr; |
| 584 | Kind = 0; |
| 585 | getNextToken(); |
| 586 | break; |
| 587 | case tok_unary: |
| 588 | getNextToken(); |
| 589 | if (!isascii(CurTok)) |
| 590 | return ErrorP("Expected unary operator"); |
| 591 | FnName = "unary"; |
| 592 | FnName += (char)CurTok; |
| 593 | Kind = 1; |
| 594 | getNextToken(); |
| 595 | break; |
| 596 | case tok_binary: |
| 597 | getNextToken(); |
| 598 | if (!isascii(CurTok)) |
| 599 | return ErrorP("Expected binary operator"); |
| 600 | FnName = "binary"; |
| 601 | FnName += (char)CurTok; |
| 602 | Kind = 2; |
| 603 | getNextToken(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 604 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 605 | // Read the precedence if present. |
| 606 | if (CurTok == tok_number) { |
| 607 | if (NumVal < 1 || NumVal > 100) |
| 608 | return ErrorP("Invalid precedecnce: must be 1..100"); |
| 609 | BinaryPrecedence = (unsigned)NumVal; |
| 610 | getNextToken(); |
| 611 | } |
| 612 | break; |
| 613 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 614 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 615 | if (CurTok != '(') |
| 616 | return ErrorP("Expected '(' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 617 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 618 | std::vector<std::string> ArgNames; |
| 619 | while (getNextToken() == tok_identifier) |
| 620 | ArgNames.push_back(IdentifierStr); |
| 621 | if (CurTok != ')') |
| 622 | return ErrorP("Expected ')' in prototype"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 623 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 624 | // success. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 625 | getNextToken(); // eat ')'. |
| 626 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 627 | // Verify right number of names for operator. |
| 628 | if (Kind && ArgNames.size() != Kind) |
| 629 | return ErrorP("Invalid number of operands for operator"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 630 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 631 | return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence); |
| 632 | } |
| 633 | |
| 634 | /// definition ::= 'def' prototype expression |
| 635 | static FunctionAST *ParseDefinition() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 636 | getNextToken(); // eat def. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 637 | PrototypeAST *Proto = ParsePrototype(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 638 | if (Proto == 0) |
| 639 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 640 | |
| 641 | if (ExprAST *E = ParseExpression()) |
| 642 | return new FunctionAST(Proto, E); |
| 643 | return 0; |
| 644 | } |
| 645 | |
| 646 | /// toplevelexpr ::= expression |
| 647 | static FunctionAST *ParseTopLevelExpr() { |
| 648 | if (ExprAST *E = ParseExpression()) { |
| 649 | // Make an anonymous proto. |
| 650 | PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>()); |
| 651 | return new FunctionAST(Proto, E); |
| 652 | } |
| 653 | return 0; |
| 654 | } |
| 655 | |
| 656 | /// external ::= 'extern' prototype |
| 657 | static PrototypeAST *ParseExtern() { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 658 | getNextToken(); // eat extern. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 659 | return ParsePrototype(); |
| 660 | } |
| 661 | |
| 662 | //===----------------------------------------------------------------------===// |
| 663 | // Code Generation |
| 664 | //===----------------------------------------------------------------------===// |
| 665 | |
| 666 | static Module *TheModule; |
Owen Anderson | a771459 | 2009-07-08 20:50:47 +0000 | [diff] [blame] | 667 | static IRBuilder<> Builder(getGlobalContext()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 668 | static std::map<std::string, AllocaInst *> NamedValues; |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 669 | static legacy::FunctionPassManager *TheFPM; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 670 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 671 | Value *ErrorV(const char *Str) { |
| 672 | Error(Str); |
| 673 | return 0; |
| 674 | } |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 675 | |
| 676 | /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of |
| 677 | /// the function. This is used for mutable variables etc. |
| 678 | static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction, |
| 679 | const std::string &VarName) { |
| 680 | IRBuilder<> TmpB(&TheFunction->getEntryBlock(), |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 681 | TheFunction->getEntryBlock().begin()); |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 682 | return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0, |
| 683 | VarName.c_str()); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 684 | } |
| 685 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 686 | Value *NumberExprAST::Codegen() { |
Owen Anderson | 69c464d | 2009-07-27 20:59:43 +0000 | [diff] [blame] | 687 | return ConstantFP::get(getGlobalContext(), APFloat(Val)); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 688 | } |
| 689 | |
| 690 | Value *VariableExprAST::Codegen() { |
| 691 | // Look this variable up in the function. |
| 692 | Value *V = NamedValues[Name]; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 693 | if (V == 0) |
| 694 | return ErrorV("Unknown variable name"); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 695 | |
| 696 | // Load the value. |
| 697 | return Builder.CreateLoad(V, Name.c_str()); |
| 698 | } |
| 699 | |
| 700 | Value *UnaryExprAST::Codegen() { |
| 701 | Value *OperandV = Operand->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 702 | if (OperandV == 0) |
| 703 | return 0; |
| 704 | |
| 705 | Function *F = TheModule->getFunction(std::string("unary") + Opcode); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 706 | if (F == 0) |
| 707 | return ErrorV("Unknown unary operator"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 708 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 709 | return Builder.CreateCall(F, OperandV, "unop"); |
| 710 | } |
| 711 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 712 | Value *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 Hames | e7c28bc | 2015-04-22 20:41:34 +0000 | [diff] [blame] | 716 | // 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 Hames | a327644 | 2015-04-22 20:58:34 +0000 | [diff] [blame] | 719 | VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 720 | if (!LHSE) |
| 721 | return ErrorV("destination of '=' must be a variable"); |
| 722 | // Codegen the RHS. |
| 723 | Value *Val = RHS->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 724 | if (Val == 0) |
| 725 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 726 | |
| 727 | // Look up the name. |
| 728 | Value *Variable = NamedValues[LHSE->getName()]; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 729 | if (Variable == 0) |
| 730 | return ErrorV("Unknown variable name"); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 731 | |
| 732 | Builder.CreateStore(Val, Variable); |
| 733 | return Val; |
| 734 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 735 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 736 | Value *L = LHS->Codegen(); |
| 737 | Value *R = RHS->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 738 | if (L == 0 || R == 0) |
| 739 | return 0; |
| 740 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 741 | switch (Op) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 742 | 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 748 | case '<': |
| 749 | L = Builder.CreateFCmpULT(L, R, "cmptmp"); |
| 750 | // Convert bool 0/1 to double 0.0 or 1.0 |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 751 | return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()), |
| 752 | "booltmp"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 753 | default: |
| 754 | break; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 755 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 756 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 757 | // If it wasn't a builtin binary operator, it must be a user defined one. Emit |
| 758 | // a call to it. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 759 | Function *F = TheModule->getFunction(std::string("binary") + Op); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 760 | assert(F && "binary operator not found!"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 761 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 762 | Value *Ops[] = { L, R }; |
Francois Pichet | c5d1050 | 2011-07-15 10:59:52 +0000 | [diff] [blame] | 763 | return Builder.CreateCall(F, Ops, "binop"); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 764 | } |
| 765 | |
| 766 | Value *CallExprAST::Codegen() { |
| 767 | // Look up the name in the global module table. |
| 768 | Function *CalleeF = TheModule->getFunction(Callee); |
| 769 | if (CalleeF == 0) |
| 770 | return ErrorV("Unknown function referenced"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 771 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 772 | // If argument mismatch error. |
| 773 | if (CalleeF->arg_size() != Args.size()) |
| 774 | return ErrorV("Incorrect # arguments passed"); |
| 775 | |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 776 | std::vector<Value *> ArgsV; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 777 | for (unsigned i = 0, e = Args.size(); i != e; ++i) { |
| 778 | ArgsV.push_back(Args[i]->Codegen()); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 779 | if (ArgsV.back() == 0) |
| 780 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 781 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 782 | |
Francois Pichet | c5d1050 | 2011-07-15 10:59:52 +0000 | [diff] [blame] | 783 | return Builder.CreateCall(CalleeF, ArgsV, "calltmp"); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 784 | } |
| 785 | |
| 786 | Value *IfExprAST::Codegen() { |
| 787 | Value *CondV = Cond->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 788 | if (CondV == 0) |
| 789 | return 0; |
| 790 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 791 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 792 | CondV = Builder.CreateFCmpONE( |
| 793 | CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond"); |
| 794 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 795 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 796 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 797 | // Create blocks for the then and else cases. Insert the 'then' block at the |
| 798 | // end of the function. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 799 | BasicBlock *ThenBB = |
| 800 | BasicBlock::Create(getGlobalContext(), "then", TheFunction); |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 801 | BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else"); |
| 802 | BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont"); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 803 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 804 | Builder.CreateCondBr(CondV, ThenBB, ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 805 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 806 | // Emit then value. |
| 807 | Builder.SetInsertPoint(ThenBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 808 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 809 | Value *ThenV = Then->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 810 | if (ThenV == 0) |
| 811 | return 0; |
| 812 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 813 | Builder.CreateBr(MergeBB); |
| 814 | // Codegen of 'Then' can change the current block, update ThenBB for the PHI. |
| 815 | ThenBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 816 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 817 | // Emit else block. |
| 818 | TheFunction->getBasicBlockList().push_back(ElseBB); |
| 819 | Builder.SetInsertPoint(ElseBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 820 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 821 | Value *ElseV = Else->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 822 | if (ElseV == 0) |
| 823 | return 0; |
| 824 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 825 | Builder.CreateBr(MergeBB); |
| 826 | // Codegen of 'Else' can change the current block, update ElseBB for the PHI. |
| 827 | ElseBB = Builder.GetInsertBlock(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 828 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 829 | // Emit merge block. |
| 830 | TheFunction->getBasicBlockList().push_back(MergeBB); |
| 831 | Builder.SetInsertPoint(MergeBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 832 | PHINode *PN = |
| 833 | Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp"); |
| 834 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 835 | PN->addIncoming(ThenV, ThenBB); |
| 836 | PN->addIncoming(ElseV, ElseBB); |
| 837 | return PN; |
| 838 | } |
| 839 | |
| 840 | Value *ForExprAST::Codegen() { |
| 841 | // Output this as: |
| 842 | // var = alloca double |
| 843 | // ... |
| 844 | // start = startexpr |
| 845 | // store start -> var |
| 846 | // goto loop |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 847 | // loop: |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 848 | // ... |
| 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 860 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 861 | Function *TheFunction = Builder.GetInsertBlock()->getParent(); |
| 862 | |
| 863 | // Create an alloca for the variable in the entry block. |
| 864 | AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 865 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 866 | // Emit the start code first, without 'variable' in scope. |
| 867 | Value *StartVal = Start->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 868 | if (StartVal == 0) |
| 869 | return 0; |
| 870 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 871 | // Store the value into the alloca. |
| 872 | Builder.CreateStore(StartVal, Alloca); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 873 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 874 | // Make the new basic block for the loop header, inserting after current |
| 875 | // block. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 876 | BasicBlock *LoopBB = |
| 877 | BasicBlock::Create(getGlobalContext(), "loop", TheFunction); |
| 878 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 879 | // 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 884 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 885 | // 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 889 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 890 | // 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. |
| 893 | if (Body->Codegen() == 0) |
| 894 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 895 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 896 | // Emit the step value. |
| 897 | Value *StepVal; |
| 898 | if (Step) { |
| 899 | StepVal = Step->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 900 | if (StepVal == 0) |
| 901 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 902 | } else { |
| 903 | // If not specified, use 1.0. |
Owen Anderson | 69c464d | 2009-07-27 20:59:43 +0000 | [diff] [blame] | 904 | StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0)); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 905 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 906 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 907 | // Compute the end condition. |
| 908 | Value *EndCond = End->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 909 | if (EndCond == 0) |
| 910 | return EndCond; |
| 911 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 912 | // 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 Lattner | 26d7950 | 2010-06-21 22:51:14 +0000 | [diff] [blame] | 915 | Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar"); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 916 | Builder.CreateStore(NextVar, Alloca); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 917 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 918 | // Convert condition to a bool by comparing equal to 0.0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 919 | EndCond = Builder.CreateFCmpONE( |
| 920 | EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond"); |
| 921 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 922 | // Create the "after loop" block and insert it. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 923 | BasicBlock *AfterBB = |
| 924 | BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction); |
| 925 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 926 | // Insert the conditional branch into the end of LoopEndBB. |
| 927 | Builder.CreateCondBr(EndCond, LoopBB, AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 928 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 929 | // Any new code will be inserted in AfterBB. |
| 930 | Builder.SetInsertPoint(AfterBB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 931 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 932 | // Restore the unshadowed variable. |
| 933 | if (OldVal) |
| 934 | NamedValues[VarName] = OldVal; |
| 935 | else |
| 936 | NamedValues.erase(VarName); |
| 937 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 938 | // for expr always returns 0.0. |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 939 | return Constant::getNullValue(Type::getDoubleTy(getGlobalContext())); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 940 | } |
| 941 | |
| 942 | Value *VarExprAST::Codegen() { |
| 943 | std::vector<AllocaInst *> OldBindings; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 944 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 945 | 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; |
| 950 | ExprAST *Init = VarNames[i].second; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 951 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 952 | // 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(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 960 | if (InitVal == 0) |
| 961 | return 0; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 962 | } else { // If not specified, use 0.0. |
Owen Anderson | 69c464d | 2009-07-27 20:59:43 +0000 | [diff] [blame] | 963 | InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0)); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 964 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 965 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 966 | 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 972 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 973 | // Remember this binding. |
| 974 | NamedValues[VarName] = Alloca; |
| 975 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 976 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 977 | // Codegen the body, now that all vars are in scope. |
| 978 | Value *BodyVal = Body->Codegen(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 979 | if (BodyVal == 0) |
| 980 | return 0; |
| 981 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 982 | // 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 990 | Function *PrototypeAST::Codegen() { |
| 991 | // Make the function type: double(double,double) etc. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 992 | 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1000 | // 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1006 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1007 | // If F already has a body, reject this. |
| 1008 | if (!F->empty()) { |
| 1009 | ErrorF("redefinition of function"); |
| 1010 | return 0; |
| 1011 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1012 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1013 | // If F took a different number of args, reject. |
| 1014 | if (F->arg_size() != Args.size()) { |
| 1015 | ErrorF("redefinition of function with different # args"); |
| 1016 | return 0; |
| 1017 | } |
| 1018 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1019 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1020 | // 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1025 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1026 | 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. |
| 1031 | void 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1045 | Function *FunctionAST::Codegen() { |
| 1046 | NamedValues.clear(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1047 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1048 | Function *TheFunction = Proto->Codegen(); |
| 1049 | if (TheFunction == 0) |
| 1050 | return 0; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1051 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1052 | // If this is an operator, install it. |
| 1053 | if (Proto->isBinaryOp()) |
| 1054 | BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence(); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1055 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1056 | // Create a new basic block to start insertion into. |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1057 | BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1058 | Builder.SetInsertPoint(BB); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1059 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1060 | // Add all arguments to the symbol table and create their allocas. |
| 1061 | Proto->CreateArgumentAllocas(TheFunction); |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 1062 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1063 | 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 Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1072 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1073 | return TheFunction; |
| 1074 | } |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1075 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1076 | // Error reading body, remove function. |
| 1077 | TheFunction->eraseFromParent(); |
| 1078 | |
| 1079 | if (Proto->isBinaryOp()) |
| 1080 | BinopPrecedence.erase(Proto->getOperatorName()); |
| 1081 | return 0; |
| 1082 | } |
| 1083 | |
| 1084 | //===----------------------------------------------------------------------===// |
| 1085 | // Top-Level parsing and JIT Driver |
| 1086 | //===----------------------------------------------------------------------===// |
| 1087 | |
| 1088 | static ExecutionEngine *TheExecutionEngine; |
| 1089 | |
| 1090 | static void HandleDefinition() { |
| 1091 | if (FunctionAST *F = ParseDefinition()) { |
| 1092 | if (Function *LF = F->Codegen()) { |
| 1093 | fprintf(stderr, "Read function definition:"); |
| 1094 | LF->dump(); |
| 1095 | } |
| 1096 | } else { |
| 1097 | // Skip token for error recovery. |
| 1098 | getNextToken(); |
| 1099 | } |
| 1100 | } |
| 1101 | |
| 1102 | static void HandleExtern() { |
| 1103 | if (PrototypeAST *P = ParseExtern()) { |
| 1104 | if (Function *F = P->Codegen()) { |
| 1105 | fprintf(stderr, "Read extern: "); |
| 1106 | F->dump(); |
| 1107 | } |
| 1108 | } else { |
| 1109 | // Skip token for error recovery. |
| 1110 | getNextToken(); |
| 1111 | } |
| 1112 | } |
| 1113 | |
| 1114 | static void HandleTopLevelExpression() { |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 1115 | // Evaluate a top-level expression into an anonymous function. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1116 | if (FunctionAST *F = ParseTopLevelExpr()) { |
| 1117 | if (Function *LF = F->Codegen()) { |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 1118 | TheExecutionEngine->finalizeObject(); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1119 | // JIT the function, returning a function pointer. |
| 1120 | void *FPtr = TheExecutionEngine->getPointerToFunction(LF); |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1121 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1122 | // Cast it to the right type (takes no arguments, returns a double) so we |
| 1123 | // can call it as a native function. |
Chris Lattner | 0813c0c | 2009-04-15 00:16:05 +0000 | [diff] [blame] | 1124 | double (*FP)() = (double (*)())(intptr_t)FPtr; |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1125 | 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 | ';' |
| 1134 | static void MainLoop() { |
| 1135 | while (1) { |
| 1136 | fprintf(stderr, "ready> "); |
| 1137 | switch (CurTok) { |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1138 | 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1152 | } |
| 1153 | } |
| 1154 | } |
| 1155 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1156 | //===----------------------------------------------------------------------===// |
| 1157 | // "Library" functions that can be "extern'd" from user code. |
| 1158 | //===----------------------------------------------------------------------===// |
| 1159 | |
| 1160 | /// putchard - putchar that takes a double and returns 0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1161 | extern "C" double putchard(double X) { |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1162 | putchar((char)X); |
| 1163 | return 0; |
| 1164 | } |
| 1165 | |
| 1166 | /// printd - printf that takes a double prints it as "%f\n", returning 0. |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1167 | extern "C" double printd(double X) { |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1168 | printf("%f\n", X); |
| 1169 | return 0; |
| 1170 | } |
| 1171 | |
| 1172 | //===----------------------------------------------------------------------===// |
| 1173 | // Main driver code. |
| 1174 | //===----------------------------------------------------------------------===// |
| 1175 | |
| 1176 | int main() { |
Chris Lattner | d24df24 | 2009-06-17 16:48:44 +0000 | [diff] [blame] | 1177 | InitializeNativeTarget(); |
Eric Christopher | 1b74b65 | 2014-12-08 18:00:38 +0000 | [diff] [blame] | 1178 | InitializeNativeTargetAsmPrinter(); |
| 1179 | InitializeNativeTargetAsmParser(); |
Owen Anderson | c277dc4 | 2009-07-16 19:05:41 +0000 | [diff] [blame] | 1180 | LLVMContext &Context = getGlobalContext(); |
Erick Tryzelaar | 6e2b34bc | 2009-09-22 21:14:49 +0000 | [diff] [blame] | 1181 | |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1182 | // Install standard binary operators. |
| 1183 | // 1 is lowest precedence. |
| 1184 | BinopPrecedence['='] = 2; |
| 1185 | BinopPrecedence['<'] = 10; |
| 1186 | BinopPrecedence['+'] = 20; |
| 1187 | BinopPrecedence['-'] = 20; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1188 | BinopPrecedence['*'] = 40; // highest. |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1189 | |
| 1190 | // Prime the first token. |
| 1191 | fprintf(stderr, "ready> "); |
| 1192 | getNextToken(); |
| 1193 | |
| 1194 | // Make the module, which holds all the code. |
Rafael Espindola | 2a8a279 | 2014-08-19 04:04:25 +0000 | [diff] [blame] | 1195 | std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context); |
| 1196 | TheModule = Owner.get(); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1197 | |
Jeffrey Yasskin | 091217b | 2010-01-27 20:34:15 +0000 | [diff] [blame] | 1198 | // Create the JIT. This takes ownership of the module. |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 1199 | std::string ErrStr; |
Eric Christopher | c023936 | 2014-12-08 18:12:28 +0000 | [diff] [blame] | 1200 | TheExecutionEngine = |
| 1201 | EngineBuilder(std::move(Owner)) |
| 1202 | .setErrorStr(&ErrStr) |
| 1203 | .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>()) |
| 1204 | .create(); |
Jeffrey Yasskin | 8a30324 | 2010-02-11 19:15:20 +0000 | [diff] [blame] | 1205 | if (!TheExecutionEngine) { |
| 1206 | fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str()); |
| 1207 | exit(1); |
| 1208 | } |
Reid Kleckner | e56676a | 2009-08-24 05:42:21 +0000 | [diff] [blame] | 1209 | |
Chandler Carruth | 7ecd991 | 2015-02-13 10:21:05 +0000 | [diff] [blame] | 1210 | legacy::FunctionPassManager OurFPM(TheModule); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1211 | |
Reid Kleckner | ab77004 | 2009-08-26 20:58:25 +0000 | [diff] [blame] | 1212 | // Set up the optimizer pipeline. Start with registering info about how the |
| 1213 | // target lays out data structures. |
Mehdi Amini | cd253da | 2015-07-16 16:47:18 +0000 | [diff] [blame] | 1214 | TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); |
Dan Gohman | 56f3a4c | 2010-11-15 18:41:10 +0000 | [diff] [blame] | 1215 | // Provide basic AliasAnalysis support for GVN. |
| 1216 | OurFPM.add(createBasicAliasAnalysisPass()); |
Reid Kleckner | ab77004 | 2009-08-26 20:58:25 +0000 | [diff] [blame] | 1217 | // 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 Friedman | e04169c | 2009-07-20 14:50:07 +0000 | [diff] [blame] | 1227 | |
Reid Kleckner | ab77004 | 2009-08-26 20:58:25 +0000 | [diff] [blame] | 1228 | OurFPM.doInitialization(); |
Nick Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1229 | |
Reid Kleckner | ab77004 | 2009-08-26 20:58:25 +0000 | [diff] [blame] | 1230 | // 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 Lewycky | 109af62 | 2009-04-12 20:47:23 +0000 | [diff] [blame] | 1241 | return 0; |
| 1242 | } |