-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathone.cpp
More file actions
390 lines (387 loc) · 11 KB
/
one.cpp
File metadata and controls
390 lines (387 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Verifier.h"
using namespace std;
enum class Token(int value){
tok_eof = -1,
tok_def = -2,
tok_extern = -3,
tok_identifier = -4,
tok_number = -5
}
static string IdentifierStr;
static double NumVal;
static int gettok(){
static int LastChar = ' ';
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar)){
IdentifierStr = LastChar;
while (isalunum((LastChar = getchar())))
IdentifierStr += LastChar;
if (IdentifierStr == "def")
return toK_def;
if (IdentifierStr == "extern")
return toK_extern;
return toK_identifier;
}
if(isdigit(LastChar) || LastChar == '.'){
string NumStr;
do{
NumStr += LastChar;
LastChar = getchar();
}while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(), nullptr);
return toK_number;
}
if (LastChar == '#'){
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
return gettok();
}
if(LastChar == EOF)
return toK_eof;
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
namespace {
class ExprAST {
public:
virtual ~ExprAST() = default;
virtual Value *codegen() = 0;
};
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double Val) : Val(Val) {}
Value *codegen() override;
};
class VariableExprAST : public ExprAST {
string Name;
public:
VariableExprAST(const string &Name) : Name(Name) {}
Value *codegen() override;
};
class BinaryExprAST : public ExprAST {
char Op;
unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char Op, unique_ptr<ExprAST> LHS,
unique_ptr<ExprAST> RHS)
: Op(Op), LHS(move(LHS)), RHS(move(RHS)) {}
Value *codegen() override;
};
class CallExprAST : public ExprAST {
string Callee;
vector<unique_ptr<ExprAST>> Args;
public:
CallExprAST(const string &Callee,
vector<unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(move(Args)) {}
Value *codegen() override;
};
class PrototypeAST {
string Name;
vector<string> Args;
public:
PrototypeAST(const string &Name, vector<string> Args)
: Name(Name), Args(move(Args)) {}
Value *codegen() override;
const string &getName() const { return Name; }
};
class FunctionAST {
unique_ptr<PrototypeAST> Proto;
unique_ptr<ExprAST> Body;
public:
FunctionAST(unique_ptr<PrototypeAST> Proto,
unique_ptr<ExprAST> Body)
: Proto(move(Proto)), Body(move(Body)) {}
Function *codegen();
};
}
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }
static map<char, int> BinopPrecedence;
static int GetTokPrecedence() {
if (!isascii(CurTok))
return -1;
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0)
return -1;
return TokPrec;
}
unique_ptr<ExprAST> LogError(const char *Str) {
fprintf(stderr, "Error: %s\n", Str);
return nullptr;
}
unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
LogError(Str);
return nullptr;
}
unique_ptr<ExprAST> ParseExpression();
unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = make_unique<NumberExprAST>(NumVal);
getNextToken();
return move(Result);
}
static unique_ptr<ExprAST> ParseParenExpr() {
getNextToken();
auto V = ParseExpression();
if (!V)
return nullptr;
if (CurTok != ')')
return LogError("expected ')'");
getNextToken();
return V;
}
static unique_ptr<ExprAST> ParseIdentifierExpr() {
string IdName = IdentifierStr;
getNextToken();
if (CurTok != '(')
return make_unique<VariableExprAST>(IdName);
getNextToken();
vector<unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while (true) {
if (auto Arg = ParseExpression())
Args.push_back(move(Arg));
else
return nullptr;
if (CurTok == ')')
break;
if (CurTok != ',')
return LogError("Expected ')' or ',' in argument list");
getNextToken();
}
}
getNextToken();
return make_unique<CallExprAST>(IdName, move(Args));
}
static unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default:
return LogError("unknown token when expecting an expression");
case toK_identifier:
return ParseIdentifierExpr();
case toK_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
static unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,unique_ptr<ExprAST> LHS) {
while (true) {
int TokPrec = GetTokPrecedence();
if (TokPrec < ExprPrec)
return LHS;
int BinOp = CurTok;
getNextToken();
auto RHS = ParsePrimary();
if (!RHS)
return nullptr;
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec + 1, move(RHS));
if (!RHS)
return nullptr;
}
LHS = make_unique<BinaryExprAST>(BinOp, move(LHS), move(RHS));
}
}
static unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS)
return nullptr;
return ParseBinOpRHS(0, move(LHS));
}
static unique_ptr<PrototypeAST> ParsePrototype() {
if (CurTok != toK_identifier)
return LogErrorP("Expected function name in prototype");
string FnName = IdentifierStr;
getNextToken();
if (CurTok != '(')
return LogErrorP("Expected '(' in prototype");
vector<string> ArgNames;
while (getNextToken() == toK_identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return LogErrorP("Expected ')' in prototype");
getNextToken();
return make_unique<PrototypeAST>(FnName, move(ArgNames));
}
static unique_ptr<FunctionAST> ParseDefinition() {
getNextToken();
auto Proto = ParsePrototype();
if (!Proto)
return nullptr;
if (auto E = ParseExpression())
return make_unique<FunctionAST>(move(Proto), move(E));
return nullptr;
}
static unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
auto Proto = make_unique<PrototypeAST>("__anon_expr",
vector<string>());
return make_unique<FunctionAST>(move(Proto), move(E));
}
return nullptr;
}
static unique_ptr<PrototypeAST> ParseExtern() {
getNextToken();
return ParsePrototype();
}
static std::unique_ptr<LLVMContext> TheContext;
static std::unique_ptr<Module> TheModule;
static std::unique_ptr<IRBuilder<>> Builder;
static std::map<std::string, Value *> NamedValues;
Value *LogErrorV(const char *Str) {
LogError(Str);
return nullptr;
}
Value *NumberExprAST::codegen() {
return ConstantFP::get(*TheContext, APFloat(Val));
}
Value *VariableExprAST::codegen() {
Value *V = NamedValues[Name];
if (!V)
return LogErrorV("Unknown variable name");
return V;
}
Value *BinaryExprAST::codegen() {
Value *L = LHS->codegen();
Value *R = RHS->codegen();
if (!L || !R)
return nullptr;
switch (Op) {
case '+':
return Builder->CreateFAdd(L, R, "addtmp");
case '-':
return Builder->CreateFSub(L, R, "subtmp");
case '*':
return Builder->CreateFMul(L, R, "multmp");
case '<':
L = Builder->CreateFCmpULT(L, R, "cmptmp");
return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext),
"booltmp");
default:
return LogErrorV("invalid binary operator");
}
}
Value *CallExprAST::codegen() {
Function *CalleeF = TheModule->getFunction(Callee);
if (!CalleeF)
return LogErrorV("Unknown function referenced");
if (CalleeF->arg_size() != Args.size())
return LogErrorV("Incorrect # arguments passed");
vector<Value *> ArgsV;
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
ArgsV.push_back(Args[i]->codegen());
if (!ArgsV.back())
return nullptr;
}
return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
}
Function *PrototypeAST::codegen() {
vector<Type *> Doubles(Args.size(), Type::getDoubleTy(*TheContext));
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(*TheContext), Doubles, false);
Function *F =
Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
unsigned Idx = 0;
for (auto &Arg : F->args())
Arg.setName(Args[Idx++]);
return F;
}
Function *FunctionAST::codegen() {
Function *TheFunction = Proto->codegen();
if (!TheFunction)
return nullptr;
BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", TheFunction);
Builder->SetInsertPoint(BB);
NamedValues.clear();
for (auto &Arg : TheFunction->args())
NamedValues[string(Arg.getName())] = &Arg;
if (Value *RetVal = Body->codegen()) {
Builder->CreateRet(RetVal);
verifyFunction(*TheFunction);
return TheFunction;
}
TheFunction->eraseFromParent();
return nullptr;
}
static void InitializeModule(){
TheContext = make_unique<LLVMContext>();
TheModule = make_unique<Module>("my cool jit", *TheContext);
Builder = make_unique<IRBuilder<>>(*TheContext);
}
static void HandleDefinition() {
if (auto FnAST = ParseDefinition()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Parsed a function definition.\n");
FnIR->print(errs());
fprintf(stderr, "\n");
}
} else {
getNextToken();
}
}
static void HandleTopLevelExpression() {
if (auto FnAST = ParseTopLevelExpr()) {
if (auto *FnIR = FnAST->codegen()) {
fprintf(stderr, "Parsed a top-level expr\n");
FnIR->print(errs());
fprintf(stderr, "\n");
}
} else {
getNextToken();
}
}
static void MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case toK_eof:
return;
case toK_def:
HandleDefinition();
break;
case toK_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
int main() {
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['*'] = 40;
fprintf(stderr, "ready> ");
getNextToken();
InitializeModule();
MainLoop();
TheModule->print(errs(), nullptr);
return 0;
}