-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnode.cpp
More file actions
581 lines (537 loc) · 18.8 KB
/
node.cpp
File metadata and controls
581 lines (537 loc) · 18.8 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#include "node.h"
using namespace std;
using namespace llvm;
Value* ConstAST::Codegen(CodeGenContext& astcontext)//by ly
{
cout<<"const"<<endl;
Value *constVal, *alloc;
if (type->type == Integer) {
NumberExprAST *n = new NumberExprAST(value.i);
// n->type = Number;
constVal = n->Codegen(astcontext);//生成对应常量
} else if (type->type == Real) {
RealExprAST *d = new RealExprAST(value.d);
// r.type = Real;
constVal = d->Codegen(astcontext);
} else if (type->type == Bool) {
BoolExprAST *b = new BoolExprAST(value.b);
// b.type = Bool;
constVal = b->Codegen(astcontext);
} else if (type->type == String) {
StringExprAST *s = new StringExprAST(value.s);
// s.type = String;
constVal = s->Codegen(astcontext);
} else if (type->type == Char) {
CharExprAST *c = new CharExprAST(value.c);
// c.type = Char;
constVal = c->Codegen(astcontext);
}
std::vector<string> v;
v.push_back(variableName);
VariableDeclAST *variabledecl = new VariableDeclAST(type, v);
variabledecl->Codegen(astcontext);//定义对应类型的变量
return builder.CreateStore(constVal, astcontext.locals.find(variableName)->second);//对变量进行赋值
}
/*Value* SelfdefineTypeAST::Codegen(CodeGenContext& context) //by ly
{
return NULL;
}
Value* RecordTypeAST::Codegen(CodeGenContext& context) //by ly
{
return NULL;
}
Value* ChangeNameTypeAST::Codegen(CodeGenContext& context) //by ly
{
return NULL;
}*/
Value* VariableDeclAST::Codegen(CodeGenContext& astcontext)
{
cout<<"var"<<endl;
Value *alloc;
for(int i = 0; i < variableName.size(); i++)
{
if (astcontext.locals.count(variableName[i])!=0){
return NULL;
}
if (type->type == Integer)
{
cout<<"new integer"<<endl;
Value *val = builder.getInt32(0);
if (isGlobal)
alloc = new llvm::GlobalVariable(module, Type::getInt32Ty(llvm::getGlobalContext()), false, GlobalValue::ExternalLinkage, builder.getInt32(0));
else
alloc = builder.CreateAlloca(Type::getInt32Ty(llvm::getGlobalContext()));
// alloc = builder.CreateAlloca(Type::getInt32Ty(llvm::getGlobalContext()));
// cout<<"create store"<<endl;
// cout << alloc << endl;
builder.CreateStore(val, alloc);
cout<<"sign up at varTable"<<endl;
cout << variableName[i] << endl;
// astcontext.locals.find(this->variableName[i])->second = alloc;
astcontext.locals[variableName[i]] = alloc;
}
else if (type->type == Real)
{
cout<<"new real"<<endl;
Value *val = ConstantFP::get(Type::getDoubleTy(getGlobalContext()), 0.0);
alloc = new llvm::GlobalVariable(module, Type::getDoubleTy(llvm::getGlobalContext()), false, GlobalValue::ExternalLinkage, ConstantFP::get(Type::getDoubleTy(getGlobalContext()), 0.0));
// alloc = builder.CreateAlloca(Type::getInt32Ty(llvm::getGlobalContext()));
// cout<<"create store"<<endl;
// cout << alloc << endl;
builder.CreateStore(val, alloc);
cout<<"sign up at varTable"<<endl;
cout << variableName[i] << endl;
// astcontext.locals.find(this->variableName[i])->second = alloc;
astcontext.locals[variableName[i]] = alloc;
}
else if (type->type == Bool)
{
cout<<"new bool"<<endl;
alloc = new llvm::AllocaInst(Type::getInt32Ty(llvm::getGlobalContext()), this->variableName[i].c_str());
// builder.CreateStore(NULL, alloc);
astcontext.locals[variableName[i]] = alloc;
} else {
return NULL;
}
}
return alloc;
}
//表达式Codegen
//整数常数表达式,如“1”
Value* NumberExprAST::Codegen(CodeGenContext& astcontext)
{
std::cout << "Creating integer: " << val << std::endl;
return ConstantInt::get(Type::getInt32Ty(getGlobalContext()), val, true);
}
//实数常数表达式,如“1.0”
Value* RealExprAST::Codegen(CodeGenContext& astcontext)
{
std::cout << "Creating double: " << val << std::endl;
return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), val);
}
Value* BoolExprAST::Codegen(CodeGenContext& astcontext)
{
std::cout << "Creating bool: " << val << std::endl;
return ConstantInt::get(Type::getInt64Ty(getGlobalContext()), val, true);
}
Value* StringExprAST::Codegen(CodeGenContext& astcontext) //by ly
{
cout << "Creating string: " << val << endl;
return builder.CreateGlobalStringPtr(val);
}
Value* CharExprAST::Codegen(CodeGenContext& astcontext) //by ly
{
cout << "Create char: " << val << endl;
string s = "";
s = s + val;
return builder.CreateGlobalStringPtr(s);
}
Value* VariableExprAST::Codegen(CodeGenContext& astcontext)
{
// Look this variable up in the function.
Value *V = astcontext.locals.find(name)->second;
for (int i=0; i<astcontext.loopVar.size(); i++)
if (name==astcontext.loopVar[i]){
cout<<"pick variableName"<<endl;
return V;
}
cout<<"pick variable:"<<name<<endl;
return builder.CreateLoad(V);
}
/*Value* ArrayVariableExprAST::Codegen(CodeGenContext& context)
{
return NULL;
}
Value* RecordVariableExprAST::Codegen(CodeGenContext& context)
{
return NULL;
}*/
Value* UnaryExprAST::Codegen(CodeGenContext& astcontext)
{
// if(op == '-'){
// float tmp = -(expr->val);
// return ConstantFP::get(Type::getDoubleTy(getGlobalContext()), tmp);
// }
// else
return NULL;
}
Value* BinaryExprAST::Codegen(CodeGenContext& astcontext)
{
Value *L, *R;
if (op!=assignmentKind)
L = LExpr->Codegen(astcontext);
R = RExpr->Codegen(astcontext);
// if (L == 0 || R == 0) return 0;
std::cout << "Creating binary operation " << op << std::endl;
/*if (op == plusKind)
{
return builder.CreateFAdd(L, R, "addtmp"); }
else if (op == minusKind)
{
return builder.CreateFSub(L, R, "subtmp");
}
else if (op == orKind)
{
return NULL;
}
else if (op == mulKind)
{
return builder.CreateFMul(L, R, "multmp");
}
else if (op == divKind)
{
return builder.CreateSDiv(L, R, "divtmp");
}
else if (op == modKind)
{
return NULL;
}
else if (op == andKind)
{
return NULL;
}
else if (op == geKind)
{
return NULL;
}
else if (op == gtKind)
{
return NULL;
}
else if (op == leKind)
{
return NULL;
}
else if (op == ltKind)
{
L = builder.CreateFCmpULT(L, R, "cmptmp");
// Convert bool 0/1 to double 0.0 or 1.0
return builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),"booltmp");
}
else if (op == eqKind)
{
return NULL;
}
else if (op == ueqKind)
{
return NULL;
}
else if (op == assignmentKind)
{
if (context.locals().find(LExpr->name) == context.locals().end()) {
throw std::domain_error("Undeclared variable " + LExpr->name);
return nullptr;
}
return builder.CreateStore(RExpr->Codegen(context),context.locals()[LExpr->name]);
}
return NULL;*/
switch (op){
case plusKind: return builder.CreateAdd(L, R, "addtmp");
case minusKind: return builder.CreateSub(L, R, "subtmp");
case modKind:
{
return builder.CreateSRem(L, R, "modtmp");;
}
case ltKind:
{
L = builder.CreateICmpSLT(L, R, "cmptmp");
// cout<<"expr val="<<L<<endl;
// Convert bool 0/1 to double 0.0 or 1.0
return L;
}
case eqKind:{
L = builder.CreateICmpEQ(L, R, "cmptmp");
return L;
}
case assignmentKind:
{
Value *v = astcontext.locals.find((dynamic_cast<VariableExprAST *>(LExpr))->name)->second;
builder.CreateStore(R, v);
return NULL;
}
default: return NULL;
}
}
Value* CallFunctionExprAST::Codegen(CodeGenContext& astcontext)
{
cout<<"call"<<endl;
Function *CalleeF = module.getFunction(callee);
if (CalleeF == 0)
// return ErrorV("Unknown function referenced");
return NULL;
// If argument mismatch error.
if (CalleeF->arg_size() != args.size())
// return ErrorV("Incorrect # arguments passed");
return NULL;
std::vector<Value*> ArgsV;
for (unsigned i = 0, e = args.size(); i != e; ++i) {
ArgsV.push_back(args[i]->Codegen(astcontext));
if (ArgsV.back() == 0) return 0;
}
ArrayRef<Value*> args(ArgsV);
return builder.CreateCall(CalleeF, args, "calltmp");
}
Value* CallProcedureExprAST::Codegen(CodeGenContext& astcontext)
{
cout<<"call"<<endl;
Function *CalleeF = module.getFunction(callee);
if (CalleeF == 0)
// return ErrorV("Unknown function referenced");
return NULL;
// If argument mismatch error.
if (CalleeF->arg_size() != args.size())
// return ErrorV("Incorrect # arguments passed");
return NULL;
std::vector<Value*> ArgsV;
for (unsigned i = 0, e = args.size(); i != e; ++i) {
ArgsV.push_back(args[i]->Codegen(astcontext));
if (ArgsV.back() == 0) return 0;
}
cout<<"call end"<<endl;
ArrayRef<Value*> args(ArgsV);
return builder.CreateCall(CalleeF, args);
}
Value* IfExprAST::Codegen(CodeGenContext& astcontext)
{
cout<<"if"<<endl;
Value *CondV = ifCond->Codegen(astcontext);
if (CondV == 0)
return 0;
// Convert condition to a bool by comparing equal to 0.0.
CondV = builder.CreateICmpNE(
CondV, ConstantInt::get(Type::getInt1Ty(getGlobalContext()), 0, true), "ifcond");
Function *TheFunction = builder.GetInsertBlock()->getParent();
// Create blocks for the then and else cases.Insert the 'then' block at the
// end of the function.
BasicBlock *ThenBB =
BasicBlock::Create(getGlobalContext(), "then", TheFunction);
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
builder.CreateCondBr(CondV, ThenBB, ElseBB);
// Emit then value.
builder.SetInsertPoint(ThenBB);
vector<Value *> ThenV;
// cout<<"then size"<<thenComponent.size()<<endl;
for (int i = 0; i < thenComponent.size(); i++){
// thenComponent[i]->print(1);
ThenV.push_back(thenComponent[i]->Codegen(astcontext));
}
builder.CreateBr(MergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
ThenBB = builder.GetInsertBlock();
// Emit else block.
TheFunction->getBasicBlockList().push_back(ElseBB);
builder.SetInsertPoint(ElseBB);
vector<Value *> ElseV;
for (int i = 0; i < elseComponent.size(); i++)
ElseV.push_back(elseComponent[i]->Codegen(astcontext));
builder.CreateBr(MergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
ElseBB = builder.GetInsertBlock();
// Emit merge block.
TheFunction->getBasicBlockList().push_back(MergeBB);
builder.SetInsertPoint(MergeBB);
/*PHINode *PN =
builder.CreatePHI(Type::getInt32Ty(getGlobalContext()), 2, "iftmp");
for (int i = 0; i < ThenV.size(); i++)
PN->addIncoming(ThenV[i], ThenBB);
for (int i = 0; i < ElseV.size(); i++)
PN->addIncoming(ElseV[i], ElseBB);*/
return NULL;
}
Value* ForExprAST::Codegen(CodeGenContext& astcontext)
{
Value *StartVal = start->Codegen(astcontext);
if (StartVal == 0)
return 0;
// Make the new basic block for the loop header, inserting after current
// block.
Function *TheFunction = builder.GetInsertBlock()->getParent();
BasicBlock *PreheaderBB = builder.GetInsertBlock();
BasicBlock *LoopBB =
BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
builder.CreateBr(LoopBB);
// Start insertion in LoopBB.
builder.SetInsertPoint(LoopBB);
// Start the PHI node with an entry for Start.
PHINode *Variable = builder.CreatePHI(Type::getInt32Ty(getGlobalContext()),
2, varName.c_str());
Variable->addIncoming(StartVal, PreheaderBB);
// Within the loop, the variable is defined equal to the PHI node.If it
// shadows an existing variable, we have to restore it, so save it now.
Value *OldVal = astcontext.locals.find(varName)->second;
astcontext.locals[varName] = Variable;
astcontext.loopVar.push_back(varName);
cout<<"push "<<varName<<endl;
// Emit the body of the loop.This, like any other expr, can change the
// current BB.Note that we ignore the value computed by the body, but don't
// allow an error.
for (int i=0; i<body.size(); i++)
body[i]->Codegen(astcontext);
// Emit the step value.
Value *StepVal;
StepVal = ConstantInt::get(Type::getInt32Ty(getGlobalContext()), 1, true);
Value *NextVar = builder.CreateAdd(Variable, StepVal, "nextvar");
// Compute the end condition.
// cout<<"end not null"<<endl;
// Convert condition to a bool by comparing equal to 0.0.
Value *EndCond = builder.CreateICmpNE(Variable, end->Codegen(astcontext), "loopcond");
// Create the "after loop" block and insert it.
BasicBlock *LoopEndBB = builder.GetInsertBlock();
BasicBlock *AfterBB =
BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
builder.CreateCondBr(EndCond, LoopBB, AfterBB);
// Any new code will be inserted in AfterBB.
builder.SetInsertPoint(AfterBB);
// Add a new entry to the PHI node for the backedge.
Variable->addIncoming(NextVar, LoopEndBB);
// Restore the unshadowed variable.
if (OldVal)
astcontext.locals[varName] = OldVal;
else
astcontext.locals.erase(varName);
astcontext.loopVar.pop_back();
cout<<"pop "<<varName<<endl;
// for expr always returns 0.0.
return Constant::getNullValue(Type::getInt32Ty(getGlobalContext()));
}
Value* WhileExprAST::Codegen(CodeGenContext& context)
{
cout << "-1" << endl;
Function *TheFunction = builder.GetInsertBlock()->getParent();
cout << "0" << endl;
BasicBlock *sloop = BasicBlock::Create(getGlobalContext(), "startloop", TheFunction);
BasicBlock *bloop = BasicBlock::Create(getGlobalContext(), "loopStmt", TheFunction);
BasicBlock *bexit = BasicBlock::Create(getGlobalContext(), "eixtStmt", TheFunction);
builder.CreateBr(sloop);
cout << "1" << endl;
TheFunction->getBasicBlockList().push_back(sloop);
builder.SetInsertPoint(sloop);
Value *CondV = whileCond->Codegen(context);
builder.CreateCondBr(CondV, bloop, bexit);
TheFunction->getBasicBlockList().pop_back();
for (int i = 0; i < body.size(); i ++)
body[i]->Codegen(context);
builder.CreateBr(bexit);
TheFunction->getBasicBlockList().pop_back();
TheFunction->getBasicBlockList().push_back(bexit);
builder.SetInsertPoint(bexit);
return NULL;
}
Value* RepeatExprAST::Codegen(CodeGenContext& context)
{
BasicBlock *bloop = BasicBlock::Create(getGlobalContext(), "loopStmt", TheFunction);
BasicBlock *bexit = BasicBlock::Create(getGlobalContext(), "eixtStmt", TheFunction);
builder.CreateBr(sloop);
TheFunction->getBasicBlockList().push_back(sloop);
builder.SetInsertPoint(sloop);
for (int i = 0; i < body.size(); i++) {
body[i]->Codegen(context);
}
Value *CondV = untilCond->Codegen(context);
builder.CreateCondBr(CondV, bexit, bloop);
TheFunction->getBasicBlockList().pop_back();
builder.CreateBr(bexit);
TheFunction->getBasicBlockList().push_back(bexit);
builder.SetInsertPoint(bexit);
return NULL;
}
Value* FunctionAST::Codegen(CodeGenContext& astcontext)
{
cout<<"function"<<endl;
std::vector<llvm::Type*> arg_types;
for (int i = 0; i < functions.size(); i++)
{
functions[i]->Codegen(astcontext);
}
for(int i = 0;i < headerDecl.size();i++)
{
cout<<"args"<<endl;
for (int j=0; j<headerDecl[i]->variableName.size(); j++)
if (headerDecl[i]->type->type == Integer)
arg_types.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
else
arg_types.push_back(llvm::Type::getVoidTy(llvm::getGlobalContext()));
}
FunctionType *f_type;
cout<<"create f_type"<<endl;
if (returnType && returnType->type == Integer)
f_type = llvm::FunctionType::get(this->isProcedure() ? llvm::Type::getVoidTy(llvm::getGlobalContext()) : llvm::Type::getInt32Ty(llvm::getGlobalContext()), llvm::makeArrayRef(arg_types), false);
else
f_type = llvm::FunctionType::get(this->isProcedure() ? llvm::Type::getVoidTy(llvm::getGlobalContext()) : llvm::Type::getVoidTy(llvm::getGlobalContext()), llvm::makeArrayRef(arg_types), false);
cout<<"create function"<<endl;
Function *function = llvm::Function::Create(f_type, llvm::GlobalValue::InternalLinkage, this->name.c_str(), &module);
// auto block = llvm::BasicBlock::Create(getGlobalContext(), "entry", function, 0);
builder.SetInsertPoint(BasicBlock::Create(context,"entry",function));
// push block and start routine
// context.pushBlock(block);
// deal with arguments
llvm::Value* arg_value;
cout<<"create args_values"<<endl;
auto args_values = function->arg_begin();
for (int i = 0; i < headerDecl.size(); i++)
{
cout<<"create code for headerDecl"<<endl;
headerDecl[i]->Codegen(astcontext);
cout<<"set argValue"<<endl;
for (int j=0; j<headerDecl[i]->variableName.size(); j++){
cout<<"args_values++"<<endl;
arg_value = args_values++;
cout<<"set Name"<<endl;
arg_value->setName(headerDecl[i]->variableName[j].c_str());
cout<<"Create store"<<endl;
builder.CreateStore(arg_value,astcontext.locals.find(headerDecl[i]->variableName[j])->second);
}
// auto inst = new llvm::StoreInst(arg_value, context.locals()[arg->name->name], false, block);
}
// add function return variable
if (this->isFunction()) {
std::cout << "Creating function return value declaration" << std::endl;
Value *retVal;
if (this->returnType->type == Integer){
retVal = builder.CreateAlloca(Type::getInt32Ty(llvm::getGlobalContext()));
// retVal = new llvm::AllocaInst(Type::getInt32Ty(llvm::getGlobalContext()), name.c_str());
} else {
retVal = builder.CreateAlloca(Type::getVoidTy(llvm::getGlobalContext()));
// retVal = new llvm::AllocaInst(Type::getVoidTy(llvm::getGlobalContext()), "retVal");
}
// builder.CreateStore(NULL, alloc);
astcontext.locals[this->name] = retVal;
// auto alloc = new llvm::AllocaInst(this->return_type->toLLVMType(), this->routine_name->name.c_str(), context.currentBlock());
}
// deal with constant define
for (int i=0; i<consts.size(); i++){
consts[i]->Codegen(astcontext);
}
// deal with variable declaration
for (int i = 0; i < bodyDecl.size(); i++)
{
bodyDecl[i]->Codegen(astcontext);
}
// deal with program statements
for (int i = 0; i < body.size(); i++)
{
cout<<"stmt"<<endl;
body[i]->Codegen(astcontext);
}
// return value
if (this->isFunction()) {
std::cout << "Generating return value for function" << std::endl;
auto load_ret = builder.CreateLoad(astcontext.locals.find(this->name)->second);
// auto load_ret = new llvm::LoadInst(astcontext.locals.find(this->name)->second, this->name);
// llvm::ReturnInst::Create(llvm::getGlobalContext(), load_ret, block);
builder.CreateRet(load_ret);
/* free return value */
astcontext.locals.erase(this->name);
} else {
std::cout << "Generating return void for procedure" << std::endl;
builder.CreateRetVoid();
// llvm::ReturnInst::Create(llvm::getGlobalContext(), block);
}
// pop block and finsh
//context.popBlock();
//std::cout << "Creating " << this->toString() << ":" << this->routine_name->name << std::endl;
return function;
}