-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtacgenerator.cpp
1372 lines (1235 loc) · 42.6 KB
/
tacgenerator.cpp
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "tacgenerator.h"
#include <iterator>
#include <set>
#include "utils.h"
namespace
{
/// 传入一个有符号版本,然后撅定用有符号还是无符号版本
Tac::Opcode properLoadInst(const std::shared_ptr<Type>& ty, Tac::Opcode op)
{
auto toUnsignedVersion = [](Tac::Opcode top) -> Tac::Opcode {
switch (top) {
case Tac::Loadi: return Tac::Loadiu;
case Tac::Loadr: return Tac::Loadru;
case Tac::Loadrc: return Tac::Loadrcu;
default: assert(false);
}
};
if (Type::isInteger(ty)) {
auto intTy = static_cast<BuiltInType*>(ty.get());
if (intTy->isUnsigned()) {
return toUnsignedVersion(op);
} else {
return op;
}
} else {
return toUnsignedVersion(op);
}
}
int paramSeq(SymtabEntry* ent, const std::shared_ptr<Type>& retType)
{
assert(ent->isParam);
if (!Type::isScalar(retType) && !Type::isVoid(retType)) {
return ent->seq + 1;
} else {
return ent->seq;
}
}
}
#define ExprType(expr) ((expr)->promotedTo ? (expr)->promotedTo : (expr)->evalType)
void TacGenerator::visit(ASTRoot* node)
{
// TODO some global information
pushScope(&node->symtab_);
for (auto& n : node->contents_) {
n->accept(*this);
}
popScope();
assert(scopeStack_.empty());
}
void TacGenerator::visit(FuncDef* node)
{
FuncGenerator funcGen(*this, node->name_, &node->params_, node->type_->retType());
funcGen.visit(node);
ir_.funcs.push_back(std::move(funcGen.yieldFunc()));
}
void TacGenerator::visit(VarDef* node)
{
/// this function collects variables in the outest scope(global).
auto size = node->type_->width();
auto align = Type::alignAt(node->type_);
if (node->init_) {
if (Type::isArithmetic(node->type_)) {
/// so far only literal init expression is permitted
/// 这么写的话,要求全局变量定义中一定没有发生类型转换。
if (node->init_->tag() == ExprTag::Literal) {
auto literalExpr = static_cast<LiteralExpr*>(node->init_.get());
auto literalTok = literalExpr->tok();
std::vector<Tac::StaticObject::BinData> data;
switch (literalTok->type()) {
case Token::IntLiteral:
data.emplace_back(literalTok->intLiteral());
break;
case Token::UnsignedLiteral:
data.emplace_back(static_cast<int>(literalTok->uintLiteral()));
break;
case Token::DoubleLiteral: {
double v = literalTok->doubleLiteral();
data.emplace_back(*reinterpret_cast<int64_t*>(&v));
break;
}
case Token::CharLiteral:
data.emplace_back((int8_t)literalTok->charLiteral());
break;
default:
assert(false);
}
Tac::StaticObject so(node->type_->width(),
Type::alignAt(node->type_), std::move(data));
addGlobalVar(node->name_, so);
} else {
assert(false && "not implemented");
}
} else {
// TODO not implemented
assert(false);
}
} else {
/// no init
addGlobalVar(node->name_, Tac::StaticObject(node->type_->width(),
Type::alignAt(node->type_)));
}
}
void FuncGenerator::visit(IfStmt* node)
{
Tac::Label falseLabel = nextLabel();
BranchGenerator bg(*this, false, falseLabel);
node->cond_->accept(bg);
if (node->else_) {
/// has else
node->then_->accept(*this);
auto iter = emit({Tac::LabelLine, falseLabel});
node->else_->accept(*this);
auto outLabel = nextLabel();
emit({Tac::LabelLine, outLabel});
quads_.insert(iter, {Tac::Jmp, Tac::Var::empty, Tac::Var::empty, outLabel});
} else {
node->then_->accept(*this);
emit({Tac::LabelLine, falseLabel});
}
}
void FuncGenerator::visit(WhileStmt* node)
{
auto beginLabel = nextLabel();
auto outLabel = nextLabel();
BranchGenerator bg(*this, false, outLabel);
emit({Tac::LabelLine, beginLabel});
node->cond_->accept(bg);
node->body_->accept(*this);
emit({Tac::Jmp, Tac::Var::empty, Tac::Var::empty, beginLabel});
emit({Tac::LabelLine, outLabel});
}
void FuncGenerator::visit(ForStmt* node)
{
auto beginLabel = nextLabel();
auto outLabel = nextLabel();
BranchGenerator bg(*this, false, outLabel);
if (node->init_)
node->init_->accept(*this);
emit({Tac::LabelLine, beginLabel});
if (node->cond_)
node->cond_->accept(bg);
else {
// nothing need to do
}
node->body_->accept(*this);
if (node->stepby_)
node->stepby_->accept(*this);
emit({Tac::Jmp, Tac::Var::empty, Tac::Var::empty, beginLabel});
emit({Tac::LabelLine, outLabel});
}
void FuncGenerator::visit(DoWhileStmt* node)
{
auto beginLabel = nextLabel();
emit({Tac::LabelLine, beginLabel});
BranchGenerator bg(*this, true, beginLabel);
node->body_->accept(*this);
node->cond_->accept(bg);
}
Tac::Reg FuncGenerator::nextReg()
{
// count from 0
return Tac::Reg(regNo_++);
}
std::list<Tac::Quad>::iterator
FuncGenerator::emit(Tac::Quad&& quad)
{
quads_.push_back(std::move(quad));
return std::prev(quads_.end());;
}
std::list<Tac::Quad>::iterator FuncGenerator::lastQuad()
{
return std::prev(quads_.end());
}
Tac::Label FuncGenerator::nextLabel()
{
return tacGen_.nextLabel();
}
Tac::StackObject FuncGenerator::nextStackObject(uint64_t size, size_t align)
{
return Tac::StackObject(stackObjectNo_++, size, align);
}
void FuncGenerator::visit(FuncDef* node)
{
node->body_->accept(*this);
}
void FuncGenerator::visit(VarDef* node)
{
// TODO compute offset
auto ent = currScope().find(node->name_);
if (ent->ambiguous) {
auto size = node->type_->width();
auto align = Type::alignAt(node->type_);
auto stackMem = nextStackObject(size, align);
ent->irBinding = stackMem;
emit({Tac::Alloca, stackMem});
} else {
// struct union array should be in memory
if (Type::isScalar(ent->type)) {
ent->irBinding = nextReg();
} else {
auto size = node->type_->width();
auto align = Type::alignAt(node->type_);
auto stackMem = nextStackObject(size, align);
ent->irBinding = stackMem;
emit({Tac::Alloca, stackMem});
}
}
if (node->init_) {
// use a temporary ast node to emulate initialization
auto tempAssignExpr =
std::make_shared<BinaryOpExpr>(node->tok_,
std::make_shared<VarExpr>(node->tok_, node->name_),
node->init_, Token::Assign);
tempAssignExpr->lhs_->evalType = node->type_;
tempAssignExpr->rhs_->evalType = node->init_->evalType;
tempAssignExpr->rhs_->promotedTo = node->init_->promotedTo;
tempAssignExpr->accept(*this);
}
}
void FuncGenerator::visit(Block* node)
{
pushScope(&node->symtab_);
for (auto& n : node->stmts_) {
n->accept(*this);
}
popScope();
}
void FuncGenerator::visit(UnaryOpExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(BinaryOpExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
auto op = node->operator_;
switch (op) {
case Token::Assign: {
if (Type::isScalar(node->lhs_->evalType)) {
// ValueGenerator rhsGen(*this);
LValueGenerator lhsGen(*this);
// node->rhs_->accept(rhsGen);
node->lhs_->accept(lhsGen);
auto width = ExprType(node->lhs_)->width();
/// 右值和左值之间的类型差异已经由checkAssignE2T在标记promotedTo中指出。
/// 我们假定这种隐式转换由ValueGenerator妥善解决。
if (lhsGen.inMemory()) {
ValueGenerator rhsGen(*this);
node->rhs_->accept(rhsGen);
emit({Tac::Storer, rhsGen.value(), Tac::Var::empty, lhsGen.addr(), width});
} else {
ValueGenerator rhsGen(*this, lhsGen.addr());
node->rhs_->accept(rhsGen);
if ( ! (rhsGen.value() == lhsGen.addr())) {
/// There are some cases that ValueGenerator WON'T generate code that
/// writes the target register. So we check these cases here.
emit({Tac::Movrr, rhsGen.value(), Tac::Var::empty, lhsGen.addr()});
}
// emit({Tac::Movrr, rhsGen.value(), Tac::Var::empty, lhsGen.addr()});
}
} else {
/// assignment between variables of compound type
auto ty = Type::derefIfIsUserDefinedType(node->lhs_->evalType);
assert(ty->tag() == Type::Compound);
assert(node->lhs_->evalType->equalUnqual(node->rhs_->evalType));
LValueGenerator rhsGen(*this);
LValueGenerator lhsGen(*this);
node->rhs_->accept(rhsGen);
node->lhs_->accept(lhsGen);
assert(lhsGen.inMemory() && rhsGen.inMemory());
auto compoundTy = static_cast<CompoundType*>(ty.get());
compoundAssignment(compoundTy, lhsGen.addr(), rhsGen.addr());
}
break;
}
default: {
ValueGenerator vg(*this);
vg.visit(node);
}
}
}
void FuncGenerator::compoundAssignment(CompoundType* type, Tac::Reg lhsAddr, Tac::Reg rhsAddr)
{
/**
* 还有许多需要做compound类型变量之间复制的操作,在现阶段的ir中无法反映,
* 所以我认为,目前没有必要将这一操作展开,而应该采用一个指令取代替
*/
auto wholeSize = type->width();
/*auto tempReg = nextReg();
std::size_t pos, offset;
for (pos = 0, offset = 0;
pos < wholeSize / PTRSIZE;
pos += 1, offset += PTRSIZE) {
emit({Tac::Loadrc, rhsAddr, offset, tempReg});
emit({Tac::Storerc, tempReg, lhsAddr, offset});
}
for ( ; offset < wholeSize; ++offset) {
emit({Tac::Loadrcu, rhsAddr, offset, tempReg, 1});
emit({Tac::Storerc, tempReg, lhsAddr, offset, 1});
}*/
emit({Tac::Memcpy, rhsAddr, Tac::Var::ImmType(wholeSize), lhsAddr});
}
/// trivial visit functions:
void FuncGenerator::visit(FuncCallExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(MemberExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(ArrayRefExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(VarExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(CastExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(LiteralExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(SizeofExpr* node)
{
TempStackObjectDeallocGuard guard(*this);
ValueGenerator vg(*this);
vg.visit(node);
}
void FuncGenerator::visit(ReturnStmt* node)
{
TempStackObjectDeallocGuard guard(*this);
if (Type::isScalar(node->func_->type_->retType())) {
ValueGenerator vg(*this);
node->retExpr_->accept(vg);
emit({Tac::Ret, vg.value()});
} else {
auto ty = Type::derefIfIsUserDefinedType(node->func_->type_->retType());
auto compoundTy = static_cast<CompoundType*>(ty.get());
assert(ty->tag() == Type::Compound);
LValueGenerator retGen(*this);
node->retExpr_->accept(retGen);
assert(retGen.inMemory());
auto ptr = nextReg();
/// 返回非标量是通过在第一个参数的位置传指针实现的
emit({Tac::GetParamVal, Tac::Var::ImmType(1), Tac::Var::empty, ptr});
compoundAssignment(compoundTy, ptr, retGen.addr());
}
}
namespace
{
void addEdge(Tac::BasicBlockPtr p1, Tac::BasicBlockPtr p2)
{
for (auto s : p1->succs) {
if (s == p2)
return;
}
p1->succs.push_back(p2);
p2->preds.push_back(p1);
}
}
Tac::Function& FuncGenerator::yieldFunc()
{
/// make CFG from linear code
std::map<Tac::Label, Tac::BasicBlockPtr> labelToBlock;
auto iter = quads_.begin();
if (iter != quads_.end()) {
Tac::BasicBlock block;
auto afterAddBasicBlock = [&labelToBlock](Tac::BasicBlockPtr bp) {
if (bp->quads.front().op == Tac::LabelLine) {
auto [it, inserted] = labelToBlock.insert(
{std::get<Tac::Label>(bp->quads.front().opnd1.uvar), bp});
assert(inserted);
}
};
block.addQuad(std::move(*iter));
++iter;
while (iter != quads_.end()) {
if (iter->op == Tac::LabelLine
|| enumBetween(Tac::Jmp, std::prev(iter)->op, Tac::Jleu)) {
currFunction_.addBasicBlock(std::move(block), afterAddBasicBlock);
block = Tac::BasicBlock();
}
block.addQuad(std::move(*iter));
++iter;
}
currFunction_.addBasicBlock(std::move(block), afterAddBasicBlock);
}
std::unordered_set<Tac::BasicBlockPtr> unusedBlocks;
for (auto blockIter = std::next(currFunction_.basicBlocks.begin());
blockIter != currFunction_.basicBlocks.end(); ++blockIter) {
unusedBlocks.insert(blockIter);
}
for (auto blockIter = currFunction_.basicBlocks.begin();
blockIter != currFunction_.basicBlocks.end(); ++blockIter) {
for (auto quadIter = blockIter->quads.begin();
true; ++quadIter) {
if (quadIter == blockIter->quads.end()) {
auto nextBlock = std::next(blockIter);
if (nextBlock != currFunction_.basicBlocks.end()) {
addEdge(blockIter, nextBlock);
unusedBlocks.erase(nextBlock);
}
break;
}
if (enumBetween(Tac::Jmp, quadIter->op, Tac::Jleu)) {
Tac::Label target = std::get<Tac::Label>(quadIter->res.uvar);
auto found = labelToBlock.find(target);
assert(found != labelToBlock.end());
addEdge(blockIter, found->second);
unusedBlocks.erase(found->second);
if (quadIter->op != Tac::Jmp) {
/// conditional jump; add fall through edges
if (auto nextBlock = std::next(blockIter);
nextBlock != currFunction_.basicBlocks.end()) {
addEdge(blockIter, nextBlock);
unusedBlocks.erase(nextBlock);
}
}
assert(std::next(quadIter) == blockIter->quads.end());
break;
} else if (quadIter->op == Tac::Ret) {
/// unconditional quit
blockIter->quads.erase(std::next(quadIter), blockIter->quads.end());
break;
}
}
}
for (auto b : unusedBlocks) {
currFunction_.basicBlocks.erase(b);
}
return currFunction_;
}
FuncGenerator::FuncGenerator(TacGenerator& tacgen, std::string funcName, ListSymtab* params,
std::shared_ptr<Type> retType)
: tacGen_(tacgen),
currFunction_(std::move(funcName), std::move(retType))
{
if (!Type::isVoid(currFunction_.retType)
&& !Type::isScalar(currFunction_.retType)) {
currFunction_.params.push_back(Tac::ParamInfo{PTRSIZE, PTRSIZE, true, false});
}
for (auto& nameEntryPair : *params) {
auto& type = nameEntryPair.second.type;
currFunction_.params.push_back({type->width(), Type::alignAt(type),
Type::isScalar(type),
nameEntryPair.second.ambiguous,
Type::isUnsignedInteger(type)});
}
}
void BranchGenerator::visit(BinaryOpExpr* node)
{
assert(node->isCond);
switch (node->operator_) {
case Token::And: {
if (!when_) {
/// when cond is false goto label else fall through
// 虽然这两个Generator和*this是一个东西,但是为了清晰,还是创建他们
BranchGenerator lhs(funcGenerator_, false, goto_);
BranchGenerator rhs(funcGenerator_, false, goto_);
node->lhs_->accept(lhs);
node->rhs_->accept(rhs);
} else {
assert(when_);
auto outLabel = nextLabel();
BranchGenerator lhs(funcGenerator_, false, outLabel);
BranchGenerator rhs(funcGenerator_, true, goto_);
node->lhs_->accept(lhs);
node->rhs_->accept(rhs);
emit({Tac::LabelLine, outLabel});
}
break;
}
case Token::Or: {
if (!when_) {
auto outLabel = nextLabel();
BranchGenerator lhs(funcGenerator_, true, outLabel);
BranchGenerator rhs(funcGenerator_, false, goto_);
node->lhs_->accept(lhs);
node->rhs_->accept(rhs);
emit({Tac::LabelLine, outLabel});
} else {
assert(when_);
BranchGenerator lhs(funcGenerator_, true, goto_);
BranchGenerator rhs(funcGenerator_, true, goto_);
node->lhs_->accept(lhs);
node->rhs_->accept(rhs);
}
break;
}
case Token::Grtr:
case Token::Ge:
case Token::Smlr:
case Token::Se:
case Token::Eq:
case Token::Ne: {
ValueGenerator vgl(funcGenerator_);
ValueGenerator vgr(funcGenerator_);
node->lhs_->accept(vgl);
node->rhs_->accept(vgr);
Tac::Reg lhs = vgl.value(),
rhs = vgr.value();
Tac::Opcode op = genJumpInst(node->operator_, node->lhs_, node->rhs_);
emit({op, lhs, rhs, goto_});
break;
}
default: {
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
break;
}
}
}
void BranchGenerator::visit(UnaryOpExpr* node)
{
switch (node->operator_) {
case Token::Not: {
BranchGenerator bg(funcGenerator_, !when_, goto_);
node->operand_->accept(bg);
break;
}
default: {
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
break;
}
}
}
void BranchGenerator::visit(FuncCallExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(MemberExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(ArrayRefExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(VarExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(CastExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(LiteralExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
void BranchGenerator::visit(SizeofExpr* node)
{
ValueGenerator vg(funcGenerator_);
vg.visit(node);
implicitCond(vg.value(), ExprType(node));
}
Tac::Opcode
BranchGenerator::genJumpInst(Token::OperatorType op,
const std::shared_ptr<Expr>& lhs, const std::shared_ptr<Expr>& rhs)
{
auto& lhsTy = ExprType(lhs);
auto& rhsTy = ExprType(rhs);
auto sign = false;
if (Type::isFloating(lhsTy)) {
assert(Type::isFloating(rhsTy));
assert(false && "floating operations are not implemented");
}
if (Type::isInteger(lhsTy)) {
assert(Type::isInteger(rhsTy));
sign = not static_cast<BuiltInType*>(lhsTy.get())->isUnsigned();
assert(sign == !static_cast<BuiltInType*>(rhsTy.get())->isUnsigned());
}
Tac::Opcode ret;
switch (op) {
case Token::Grtr:
if (when_ == true) {
if (sign) {
return Tac::Jgs;
} else {
return Tac::Jgu;
}
} else {
if (sign) {
return Tac::Jles;
} else {
return Tac::Jleu;
}
}
case Token::Smlr:
if (when_ == true) {
if (sign) {
return Tac::Jls;
} else {
return Tac::Jlu;
}
} else {
if (sign) {
return Tac::Jges;
} else {
return Tac::Jgeu;
}
}
case Token::Ge:
if (when_ == true) {
if (sign) {
return Tac::Jgeu;
} else {
return Tac::Jges;
}
} else {
if (sign) {
return Tac::Jls;
} else {
return Tac::Jlu;
}
}
case Token::Se:
if (when_ == true) {
if (sign) {
return Tac::Jles;
} else {
return Tac::Jleu;
}
} else {
if (sign) {
return Tac::Jgs;
} else {
return Tac::Jgu;
}
}
case Token::Eq:
if (when_ == true) {
return Tac::Jeq;
} else {
return Tac::Jne;
}
case Token::Ne:
if (when_ == true) {
return Tac::Jne;
} else {
return Tac::Jeq;
}
default:
assert(false);
}
assert(false);
}
void BranchGenerator::implicitCond(Tac::Reg val, const std::shared_ptr<Type>& ty)
{
Tac::Reg zero = nextReg();
emit({Tac::Loadi, Tac::Var::ImmType(0), Tac::Var::empty, zero}); // load immidiate 0
if (Type::isInteger(ty) || Type::isPointer(ty)) {
if (when_) {
emit({Tac::Jne, val, zero, goto_});
} else {
emit({Tac::Jeq, val, zero, goto_});
}
} else {
assert(false && "not implemented");
}
}
Tac::Reg ValueGenerator::cast(Tac::Reg reg,
const std::shared_ptr<Type>& from, const std::shared_ptr<Type>& to,
bool inplace)
{
/** return reg; is a kind of optimization of:
* auto dest = nextReg();
* emit({Tac::Movrr, reg, Tac::Var::empty, dest});
* return dest; """
*/
if (from->equalUnqual(to)) {
return reg;
}
if (Type::isArithmetic(from) && Type::isArithmetic(to)) {
auto fromTy = static_cast<BuiltInType*>(from.get());
auto toTy = static_cast<BuiltInType*>(to.get());
if (fromTy->isInteger() && toTy->isInteger()) {
if (toTy->width() == PTRSIZE) {
return reg;
}
Tac::Reg dest;
if (inplace)
dest = reg;
else
dest = regToWrite();
auto op = toTy->isUnsigned() ? Tac::Extu : Tac::Exts;
emit({op, reg, Tac::Var::empty, dest, toTy->width()});
return dest;
} else {
//TODO
assert(false && "floating number not implemented");
}
} else if (Type::isPointer(from) && Type::isInteger(to)) {
auto fromTy = static_cast<PointerType*>(from.get());
auto toTy = static_cast<BuiltInType*>(to.get());
if (toTy->width() == PTRSIZE) {
return reg;
} else {
Tac::Reg dest;
if (inplace)
dest = reg;
else
dest = regToWrite();
auto op = toTy->isUnsigned() ? Tac::Extu : Tac::Exts;
emit({op, reg, Tac::Var::empty, dest, toTy->width()});
return dest;
}
} else if (Type::isInteger(from) && Type::isPointer(to)) {
return reg;
} else if (Type::isPointer(from) && Type::isPointer(to)) {
return reg;
} else if (from->tag() == Type::Array && Type::isPointer(to)) {
return reg;
} else {
assert(false);
}
}
void ValueGenerator::visit(UnaryOpExpr* node)
{
auto op = node->operator_;
if (op == Token::BitAnd) {
/// & 取地址
if (Type::isArray(node->operand_->evalType)) {
assert(!node->operand_->promotedTo);
ValueGenerator vg(funcGenerator_);
node->operand_->accept(vg);
reg_ = vg.value();
} else {
LValueGenerator lg(funcGenerator_);
node->operand_->accept(lg);
assert(lg.inMemory());
reg_ = lg.addr();
}
} else if (op == Token::Not) {
auto falseLabel = nextLabel();
BranchGenerator bg(funcGenerator_, false, falseLabel);
bg.visit(node);
reg_ = regToWrite();
auto outLabel = nextLabel();
emit({Tac::Loadi, Tac::Var::ImmType(1), Tac::Var::empty, reg_});
emit({Tac::Jmp, Tac::Var::empty, Tac::Var::empty, outLabel});
emit({Tac::LabelLine, falseLabel});
emit({Tac::Loadi, Tac::Var::ImmType(0), Tac::Var::empty, reg_});
emit({Tac::LabelLine, outLabel});
} else {
ValueGenerator opndGen(funcGenerator_);
node->operand_->accept(opndGen);
auto res = opndGen.value();
switch (op) {
case Token::Add:
reg_ = res;
break;
case Token::Sub: {
reg_ = regToWrite();
Tac::Reg zero = nextReg();
emit({Tac::Loadi, Tac::Var::ImmType(0), Tac::Var::empty, zero}); // load immidiate 0
emit({Tac::Sub, zero, res, reg_});
break;
}
case Token::BitInv:
reg_ = regToWrite();
emit({Tac::BInv, res, Tac::Var::empty, reg_});
break;
case Token::Mult: {
/// * dereference
assert(Type::isPointer(node->operand_->evalType));
auto ptrTy = static_cast<PointerType*>(node->operand_->evalType.get());
if (Type::isArray(ptrTy->base())) {
/// 数组的地址即是数组名的值
reg_ = res;
} else {
auto width = node->evalType->width();
reg_ = regToWrite();
Tac::Opcode inst = properLoadInst(node->evalType, Tac::Loadr);
emit({inst, res, Tac::Var::empty, reg_, width});
}
break;
}
default:
assert(false);
}
}
if (node->promotedTo) {
// need cast
reg_ = cast(reg_, node->evalType, node->promotedTo, true);
}
}
void ValueGenerator::visit(BinaryOpExpr* node)
{
if (Type::isFloating(ExprType(node->lhs_))) {
assert(false && "floating number not implemented");
}
auto op = node->operator_;
/// not assignment:
assert((int)op < (int)Token::Assign || (int)op > (int)Token::SftRAssign);
if ((int)Token::Eq <= (int)op && (int)op <= (int)Token::Or) {
auto falseLabel = nextLabel();
BranchGenerator bg(funcGenerator_, false, falseLabel);
bg.visit(node);
reg_ = regToWrite();
auto outLabel = nextLabel();
emit({Tac::Loadi, Tac::Var::ImmType(1), Tac::Var::empty, reg_});
emit({Tac::Jmp, Tac::Var::empty, Tac::Var::empty, outLabel});
emit({Tac::LabelLine, falseLabel});
emit({Tac::Loadi, Tac::Var::ImmType(0), Tac::Var::empty, reg_});
emit({Tac::LabelLine, outLabel});
} else {
ValueGenerator lhsGen(funcGenerator_),
rhsGen(funcGenerator_);
node->lhs_->accept(lhsGen);
node->rhs_->accept(rhsGen);
auto lhs = lhsGen.value();
auto rhs = rhsGen.value();
reg_ = regToWrite();
auto inst = Tac::Nop;
switch(op) {
case Token::Add:
inst = Tac::Add;
break;
case Token::Sub:
inst = Tac::Sub;
break;
case Token::Mult:
inst = Tac::Mul;
break;
case Token::Div: {
auto p = static_cast<BuiltInType*>(ExprType(node->lhs_).get())->isUnsigned();
inst = p ? Tac::Divu : Tac::Divs;
break;
}
case Token::Mod: {
auto p = static_cast<BuiltInType*>(ExprType(node->lhs_).get())->isUnsigned();
inst = p ? Tac::Modu : Tac::Mods;
break;
}
case Token::SftL:
inst = Tac::Shl;
break;
case Token::SftR: {
auto p = static_cast<BuiltInType*>(ExprType(node->lhs_).get())->isUnsigned();
inst = p ? Tac::Shrl : Tac::Shra;
break;
}
case Token::BitAnd:
inst = Tac::BAnd;
break;
case Token::BitXor:
inst = Tac::BXor;
break;
case Token::BitOr:
inst = Tac::BOr;
break;
default:
assert(false);
}
auto opnd1 = lhs;
auto opnd2 = rhs;
if (op == Token::Add || op == Token::Sub) {
if (Type::isPointer(node->lhs_->evalType)) {
assert(Type::isInteger(ExprType(node->rhs_)));
auto timed = nextReg();
emit({Tac::Mul,
rhs,
Tac::Var::ImmType(
static_cast<PointerType*>(node->lhs_->evalType.get())->base()->width()),
timed});
opnd2 = timed;