-
-
Notifications
You must be signed in to change notification settings - Fork 246
/
CfrontCodeGenerator.cpp
1236 lines (963 loc) · 46.4 KB
/
CfrontCodeGenerator.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
/******************************************************************************
*
* C++ Insights, copyright (C) by Andreas Fertig
* Distributed under an MIT license. See LICENSE for details
*
****************************************************************************/
#include <clang/AST/VTableBuilder.h>
#include <algorithm>
#include <vector>
#include "CodeGenerator.h"
#include "DPrint.h"
#include "Insights.h"
#include "InsightsHelpers.h"
#include "InsightsOnce.h"
#include "InsightsStrCat.h"
#include "NumberIterator.h"
#include "ASTHelpers.h"
//-----------------------------------------------------------------------------
namespace clang::insights {
using namespace asthelpers;
//-----------------------------------------------------------------------------
//! Store the `this` pointer offset from derived to base class.
static llvm::DenseMap<std::pair<const CXXRecordDecl*, const CXXRecordDecl*>, int> mThisPointerOffset{};
//-----------------------------------------------------------------------------
static MemberExpr* AccessMember(std::string_view name, const ValueDecl* vd, QualType type)
{
auto* rhsDeclRef = mkVarDeclRefExpr(name, type);
auto* rhsMemberExpr = AccessMember(rhsDeclRef, vd);
return rhsMemberExpr;
}
//-----------------------------------------------------------------------------
CfrontCodeGenerator::CfrontVtableData::CfrontVtableData()
: vptpTypedef{Typedef("__vptp"sv, Function("vptp"sv, GetGlobalAST().IntTy, {})->getType())}
, vtableRecorDecl{}
{
vtableRecorDecl = Struct("__mptr"sv);
auto AddField = [&](FieldDecl* field) { vtableRecorDecl->addDecl(field); };
d = mkFieldDecl(vtableRecorDecl, "d"sv, GetGlobalAST().ShortTy);
AddField(d);
AddField(mkFieldDecl(vtableRecorDecl, "i"sv, GetGlobalAST().ShortTy));
f = mkFieldDecl(vtableRecorDecl, "f"sv, vptpTypedef);
AddField(f);
vtableRecorDecl->completeDefinition();
vtableRecordType = QualType{vtableRecorDecl->getTypeForDecl(), 0u};
}
//-----------------------------------------------------------------------------
VarDecl* CfrontCodeGenerator::CfrontVtableData::VtblArrayVar(int size)
{
return Variable("__vtbl_array"sv, ContantArrayTy(Ptr(vtableRecordType), size));
}
//-----------------------------------------------------------------------------
FieldDecl* CfrontCodeGenerator::CfrontVtableData::VtblPtrField(const CXXRecordDecl* parent)
{
return mkFieldDecl(const_cast<CXXRecordDecl*>(parent), StrCat("__vptr"sv, GetName(*parent)), Ptr(vtableRecordType));
}
//-----------------------------------------------------------------------------
CfrontCodeGenerator::CfrontVtableData& CfrontCodeGenerator::VtableData()
{
static CfrontVtableData data{};
return data;
}
//-----------------------------------------------------------------------------
CodeGeneratorVariant::CodeGenerators::CodeGenerators(OutputFormatHelper& _outputFormatHelper,
CodeGenerator::LambdaStackType& lambdaStack,
CodeGenerator::ProcessingPrimaryTemplate processingPrimaryTemplate)
{
if(GetInsightsOptions().UseShow2C) {
new(&cfcg) CfrontCodeGenerator{
_outputFormatHelper, lambdaStack, CodeGenerator::LambdaInInitCapture::No, processingPrimaryTemplate};
} else {
new(&cg) CodeGenerator{
_outputFormatHelper, lambdaStack, CodeGenerator::LambdaInInitCapture::No, processingPrimaryTemplate};
}
}
//-----------------------------------------------------------------------------
CodeGeneratorVariant::CodeGenerators::CodeGenerators(OutputFormatHelper& _outputFormatHelper,
CodeGenerator::LambdaInInitCapture lambdaInitCapture)
{
if(GetInsightsOptions().UseShow2C) {
new(&cfcg) CfrontCodeGenerator{_outputFormatHelper, lambdaInitCapture};
} else {
new(&cg) CodeGenerator{_outputFormatHelper, lambdaInitCapture};
}
}
//-----------------------------------------------------------------------------
CodeGeneratorVariant::CodeGenerators::~CodeGenerators()
{
if(GetInsightsOptions().UseShow2C) {
cfcg.~CfrontCodeGenerator();
} else {
cg.~CodeGenerator();
}
}
//-----------------------------------------------------------------------------
void CodeGeneratorVariant::Set()
{
if(GetInsightsOptions().UseShow2C) {
cg = &cgs.cfcg;
} else {
cg = &cgs.cg;
}
}
//-----------------------------------------------------------------------------
static bool IsCopyOrMoveCtor(const CXXConstructorDecl* ctor)
{
return ctor and (ctor->isCopyConstructor() or ctor->isMoveConstructor());
}
//-----------------------------------------------------------------------------
static bool IsCopyOrMoveAssign(const CXXMethodDecl* stmt)
{
return stmt and (stmt->isCopyAssignmentOperator() or stmt->isMoveAssignmentOperator());
}
//-----------------------------------------------------------------------------
static std::string GetSpecialMemberName(const ValueDecl* vd, QualType type)
{
if(const auto* md = dyn_cast_or_null<CXXMethodDecl>(vd)) {
// GetName below would return a[4] for example. To avoid the array part we go for the underlying type.
if(const auto* ar = dyn_cast_or_null<ArrayType>(type)) {
type = ar->getElementType();
}
auto rdName = GetName(type);
if(const auto* ctor = dyn_cast_or_null<CXXConstructorDecl>(md)) {
if(ctor->isCopyConstructor()) {
return StrCat("CopyConstructor_"sv, rdName);
} else if(ctor->isMoveConstructor()) {
return StrCat("MoveConstructor_"sv, rdName);
}
return StrCat("Constructor_"sv, rdName);
} else if(isa<CXXDestructorDecl>(md)) {
return StrCat("Destructor_"sv, rdName);
}
}
return GetName(*vd);
}
//-----------------------------------------------------------------------------
std::string GetSpecialMemberName(const ValueDecl* vd)
{
if(const auto* md = dyn_cast_or_null<CXXMethodDecl>(vd)) {
return GetSpecialMemberName(vd, GetRecordDeclType(md));
}
return {};
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXThisExpr*)
{
mOutputFormatHelper.Append(kwInternalThis);
}
//-----------------------------------------------------------------------------
static bool HasCtor(QualType t)
{
if(auto* cxxRecordDecl = t->getAsCXXRecordDecl(); cxxRecordDecl and not cxxRecordDecl->isTrivial()) {
return true;
}
return false;
}
//-----------------------------------------------------------------------------
static bool HasDtor(QualType t)
{
if(auto* cxxRecordDecl = t->getAsCXXRecordDecl(); cxxRecordDecl and not cxxRecordDecl->hasTrivialDestructor()) {
return true;
}
return false;
}
//-----------------------------------------------------------------------------
static auto* CallVecDeleteOrDtor(Expr* objectParam, QualType allocatedType, std::string_view name, uint64_t size)
{
auto dtorName = GetSpecialMemberName(allocatedType->getAsCXXRecordDecl()->getDestructor());
SmallVector<Expr*, 4> args{objectParam,
Sizeof(allocatedType),
Int32(size), // XXX what is the correct value?
CastToVoidFunPtr(dtorName)};
return Call(name, args);
}
//-----------------------------------------------------------------------------
static auto* CallVecDelete(Expr* objectParam, QualType allocatedType)
{
EnableGlobalInsert(GlobalInserts::FuncCxaVecDel);
return CallVecDeleteOrDtor(objectParam, allocatedType, "__cxa_vec_delete"sv, 0);
}
//-----------------------------------------------------------------------------
static auto* CallVecDtor(Expr* objectParam, const ConstantArrayType* ar)
{
EnableGlobalInsert(GlobalInserts::FuncCxaVecDtor);
return CallVecDeleteOrDtor(objectParam, ar->getElementType(), "__cxa_vec_dtor"sv, GetSize(ar));
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXDeleteExpr* stmt)
{
auto destroyedType = stmt->getDestroyedType();
auto* arg = const_cast<Expr*>(stmt->getArgument());
StmtsContainer bodyStmts{};
if(const auto hasDtor{HasDtor(destroyedType)}; stmt->isArrayForm() and hasDtor) {
bodyStmts.Add(CallVecDelete(arg, destroyedType));
} else if(hasDtor) {
bodyStmts.Add(Call(StrCat("Destructor_"sv, GetName(destroyedType)), {arg}));
}
EnableGlobalInsert(GlobalInserts::FuncFree);
bodyStmts.Add(Call("free"sv, {arg}));
InsertArg(If(arg, {bodyStmts}));
mInsertSemi = false; // Since we tamper with a CompoundStmt we signal _not_ to insert the usual semi
}
//-----------------------------------------------------------------------------
static auto* CallVecNewOrCtor(std::string_view ctorName,
Expr* objectParam,
QualType allocatedType,
Expr* arraySizeExpr,
std::string_view funName)
{
// According to "Inside the C++ Object Model" the dtor is required in case one of the array element ctors fails the
// already constructed one must be destroyed.
// See also: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#array-ctor
auto dtorName = [&]() {
if(HasDtor(allocatedType)) {
return GetSpecialMemberName(allocatedType->getAsCXXRecordDecl()->getDestructor());
}
return std::string{kwNull};
}();
SmallVector<Expr*, 6> args{objectParam,
Sizeof(allocatedType),
arraySizeExpr,
Int32(0), // XXX what is the correct value?
CastToVoidFunPtr(ctorName),
CastToVoidFunPtr(dtorName)};
return Call(funName, args);
}
//-----------------------------------------------------------------------------
static auto* CallVecNew(std::string_view ctorName, Expr* objectParam, QualType allocatedType, Expr* arraySizeExpr)
{
EnableGlobalInsert(GlobalInserts::FuncCxaVecNew);
return CallVecNewOrCtor(ctorName, objectParam, allocatedType, arraySizeExpr, "__cxa_vec_new"sv);
}
//-----------------------------------------------------------------------------
static auto*
CallVecCtor(std::string_view ctorName, const VarDecl* objectParam, QualType allocatedType, Expr* arraySizeExpr)
{
EnableGlobalInsert(GlobalInserts::FuncCxaVecCtor);
return CallVecNewOrCtor(ctorName, mkDeclRefExpr(objectParam), allocatedType, arraySizeExpr, "__cxa_vec_ctor"sv);
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXNewExpr* cstmt)
{
auto* stmt = const_cast<CXXNewExpr*>(cstmt);
auto allocatedType = stmt->getAllocatedType();
auto ctorName = StrCat("Constructor_"sv, GetName(allocatedType));
if(stmt->isArray()) {
EnableGlobalInsert(GlobalInserts::FuncMalloc);
auto* arraySizeExpr = stmt->getArraySize().value();
auto* callMalloc = Call("malloc"sv, {Mul(Sizeof(allocatedType), arraySizeExpr)});
Expr* assign{};
// According to "Inside the C++ Object Model" a trivial and literal type does use plain malloc as it does not
// require a ctor/dtor.
if(not HasCtor(allocatedType) and not HasDtor(allocatedType)) {
assign = Cast(callMalloc, Ptr(allocatedType));
} else {
if(allocatedType->getAsCXXRecordDecl()->ctors().empty()) {
EnableGlobalInsert(GlobalInserts::HeaderStddef);
ctorName = kwNull;
}
assign = Cast(CallVecNew(ctorName, callMalloc, allocatedType, arraySizeExpr), Ptr(allocatedType));
}
InsertArg(assign);
if(stmt->hasInitializer() and allocatedType->isBuiltinType()) { // Ignore CXXConstructExpr
// The resulting code here is slightly different from the cfront code. For
//
// int* p = new int(2);
//
// C++ Insights generates:
//
// int* p = (int*)malloc(sizeof(int));
// if(p) { *p = 2; }
//
// However, due to Cs requirement to only declare variables and delay initialization the cfront code is
//
// int* p;
// if(p = (int*)malloc(sizeof(int))) { *p = 2; }
mOutputFormatHelper.AppendSemiNewLine();
if(auto* inits = dyn_cast_or_null<InitListExpr>(stmt->getInitializer())) {
auto* expr = [&]() -> const Expr* {
if(auto* vd = dyn_cast_or_null<VarDecl>(mLastDecl)) {
return mkDeclRefExpr(vd);
}
return mLastExpr;
}();
StmtsContainer bodyStmts{};
for(auto idx : NumberIterator(inits->getNumInits())) {
bodyStmts.Add(Assign(ArraySubscript(expr, idx, allocatedType), inits->getInit(idx)));
}
InsertArg(If(expr, {bodyStmts}));
mInsertSemi = false; // Since we tamper with a CompoundStmt we signal _not_ to insert the usual semi
}
}
return;
}
auto* mallocCall = [&]() -> Expr* {
if(stmt->getNumPlacementArgs()) {
return stmt->getPlacementArg(0);
}
EnableGlobalInsert(GlobalInserts::FuncMalloc);
return Call("malloc"sv, {Sizeof(allocatedType)});
}();
mallocCall = Cast(mallocCall, Ptr(allocatedType));
if(allocatedType->isBuiltinType()) {
InsertArg(mallocCall);
if(stmt->hasInitializer()) {
// The resulting code here is slightly different from the cfront code. For
//
// int* p = new int(2);
//
// C++ Insights generates:
//
// int* p = (int*)malloc(sizeof(int));
// if(p) { *p = 2; }
//
// However, due to Cs requirement to only declare variables and delay initialization the cfront code is
//
// int* p;
// if(p = (int*)malloc(sizeof(int))) { *p = 2; }
mOutputFormatHelper.AppendSemiNewLine();
auto* varDeclRefExpr = mkDeclRefExpr(dyn_cast_or_null<VarDecl>(mLastDecl));
StmtsContainer bodyStmts{Assign(Dref(varDeclRefExpr), stmt->getInitializer())};
InsertArg(If(varDeclRefExpr, {bodyStmts}));
mInsertSemi = false; // Since we tamper with a CompoundStmt we signal _not_ to insert the usual semi
}
return;
}
SmallVector<Expr*, 16> args{mallocCall};
if(auto* ncCtorExpr = const_cast<CXXConstructExpr*>(stmt->getConstructExpr())) {
args.append(ncCtorExpr->arg_begin(), ncCtorExpr->arg_end());
}
InsertArg(Call(ctorName, args));
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXOperatorCallExpr* stmt)
{
const auto* callee = stmt->getDirectCallee();
if(const auto* cxxCallee = dyn_cast_or_null<CXXMethodDecl>(callee); IsCopyOrMoveAssign(cxxCallee)) {
SmallVector<Expr*, 16> args{};
for(const auto& arg : stmt->arguments()) {
args.push_back(Ref(arg));
}
InsertArg(Call(callee, args));
} else {
InsertArg(dyn_cast_or_null<CallExpr>(stmt));
}
}
//-----------------------------------------------------------------------------
static void InsertVtblPtr(const CXXMethodDecl* stmt, const CXXRecordDecl* cur, StmtsContainer& bodyStmts)
{
if(cur->isPolymorphic() and (0 == cur->getNumBases())) {
auto* fieldDecl = CfrontCodeGenerator::VtableData().VtblPtrField(cur);
auto* lhsMemberExpr = AccessMember(kwInternalThis, fieldDecl, Ptr(GetRecordDeclType(cur)));
// struct __mptr *__ptbl_vec__c___src_C_[]
auto* vtablAr = CfrontCodeGenerator::VtableData().VtblArrayVar(1);
auto* vtblArrayPos =
ArraySubscript(mkDeclRefExpr(vtablAr), GetGlobalVtablePos(stmt->getParent(), cur), fieldDecl->getType());
bodyStmts.AddBodyStmts(Assign(lhsMemberExpr, fieldDecl, vtblArrayPos));
} else if(cur->isPolymorphic() and (0 < cur->getNumBases()) and (cur != stmt->getParent())) {
for(const auto& base : cur->bases()) {
InsertVtblPtr(stmt, base.getType()->getAsCXXRecordDecl(), bodyStmts);
}
}
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertCXXMethodDecl(const CXXMethodDecl* stmt, SkipBody)
{
// Skip if he method is unused like assignment operators by default.
RETURN_IF(not stmt->isUsed() and
(IsCopyOrMoveAssign(stmt) or (not stmt->hasBody() and not isa<CXXConstructorDecl>(stmt))));
OutputFormatHelper initOutputFormatHelper{};
initOutputFormatHelper.SetIndent(mOutputFormatHelper, OutputFormatHelper::SkipIndenting::Yes);
auto recordDeclType = GetRecordDeclType(stmt);
if(stmt->isConst()) {
recordDeclType.addConst();
}
auto parentType = Ptr(recordDeclType);
auto* body = stmt->getBody();
StmtsContainer bodyStmts{};
auto retType = stmt->getReturnType();
auto processBaseClassesAndFields = [&](const CXXRecordDecl* parent) {
auto* thisOfParent = mkVarDeclRefExpr(kwInternalThis, parentType);
auto insertFields = [&](const RecordDecl* rd) {
for(auto* fieldDecl : rd->fields()) {
if(const auto* cxxRecordDecl = fieldDecl->getType()->getAsCXXRecordDecl()) {
// We don't need any checks like isDefaultConstructible. We would not reach this
// point in any other case.
auto lvalueRefType = GetGlobalAST().getLValueReferenceType(parentType);
auto* lhsMemberExpr = AccessMember(kwInternalThis, fieldDecl, lvalueRefType);
auto* rhsMemberExpr = AccessMember("__rhs"sv, fieldDecl, lvalueRefType);
// Add call to ctor
bodyStmts.AddBodyStmts(Call(GetSpecialMemberName(stmt, GetRecordDeclType(cxxRecordDecl)),
{Ref(lhsMemberExpr), Ref(rhsMemberExpr)}));
} else {
auto* rhsMemberExpr = AccessMember("__rhs"sv, fieldDecl, parentType);
bodyStmts.AddBodyStmts(Assign(thisOfParent, fieldDecl, rhsMemberExpr));
}
}
};
for(const auto& base : parent->bases()) {
const auto rd = base.getType()->getAsRecordDecl();
auto* lhsCast = StaticCast(GetRecordDeclType(rd), thisOfParent, true);
auto* rhsDeclRef = mkVarDeclRefExpr("__rhs"sv, parentType);
auto* rhsCast = StaticCast(GetRecordDeclType(rd), rhsDeclRef, true);
auto* callAssignBase = Call(GetSpecialMemberName(stmt, GetRecordDeclType(rd)), {lhsCast, rhsCast});
bodyStmts.AddBodyStmts(callAssignBase);
}
// insert own fields
insertFields(parent);
};
// Skip ctor for trivial types
if(const auto* ctorDecl = dyn_cast_or_null<CXXConstructorDecl>(stmt)) {
const auto* parent = stmt->getParent();
if(not stmt->doesThisDeclarationHaveABody()) {
if(IsCopyOrMoveCtor(ctorDecl)) {
if(const bool showSpecialMemberFunc{stmt->isUserProvided() or stmt->isExplicitlyDefaulted()};
not showSpecialMemberFunc) {
return;
}
processBaseClassesAndFields(parent);
}
} else if(ctorDecl->isDefaultConstructor()) {
auto insertFields = [&](const RecordDecl* rd) {
for(auto* fieldDecl : rd->fields()) {
if(auto* initializer = fieldDecl->getInClassInitializer();
initializer and fieldDecl->hasInClassInitializer()) {
const bool isConstructorExpr{isa<CXXConstructExpr>(initializer) or
isa<ExprWithCleanups>(initializer)};
if(not isConstructorExpr) {
auto* lhsMemberExpr = AccessMember(kwInternalThis, fieldDecl, Ptr(GetRecordDeclType(rd)));
bodyStmts.AddBodyStmts(Assign(lhsMemberExpr, fieldDecl, initializer));
} else {
bodyStmts.AddBodyStmts(CallConstructor(fieldDecl->getType(),
Ptr(GetRecordDeclType(rd)),
fieldDecl,
ArgsToExprVector(initializer),
DoCast::No,
AsReference::Yes));
}
} else if(const auto* cxxRecordDecl = fieldDecl->getType()->getAsCXXRecordDecl()) {
// We don't need any checks like isDefaultConstructible. We would not reach this
// point in any other cause.
if(auto lhsType = fieldDecl->getType(); HasCtor(lhsType)) {
bodyStmts.AddBodyStmts(CallConstructor(GetRecordDeclType(cxxRecordDecl),
Ptr(GetRecordDeclType(cxxRecordDecl)),
fieldDecl,
{},
DoCast::No,
AsReference::Yes));
} else {
bodyStmts.Add(
Comment(StrCat(GetName(*fieldDecl), " // trivial type, maybe uninitialized"sv)));
// Nothing to do here, we are looking at an uninitialized variable
}
}
}
};
for(const auto& base : parent->bases()) {
auto baseType = base.getType();
if(const auto* baseRd = baseType->getAsCXXRecordDecl();
baseRd and baseRd->hasNonTrivialDefaultConstructor()) {
bodyStmts.AddBodyStmts(CallConstructor(baseType, Ptr(baseType), nullptr, {}, DoCast::Yes));
}
}
// insert our vtable pointer
InsertVtblPtr(stmt, stmt->getParent(), bodyStmts);
// in case of multi inheritance insert additional vtable pointers
for(const auto& base : parent->bases()) {
InsertVtblPtr(stmt, base.getType()->getAsCXXRecordDecl(), bodyStmts);
}
// insert own fields
insertFields(parent);
} else {
// user ctor
for(const auto* init : ctorDecl->inits()) {
auto* member = init->getMember();
if(not isa<CXXConstructExpr>(init->getInit())) {
if(not init->getAnyMember()) {
continue;
}
auto* lhsMemberExpr = AccessMember(kwInternalThis, member, Ptr(GetRecordDeclType(parent)));
bodyStmts.AddBodyStmts(Assign(lhsMemberExpr, member, init->getInit()));
continue;
} else if(init->isBaseInitializer()) {
bodyStmts.AddBodyStmts(init->getInit());
continue;
}
auto ctorType = member->getType();
auto* lhsMemberExpr = AccessMember(kwInternalThis, member, ctorType);
auto callParams{ArgsToExprVector(init->getInit())};
callParams.insert(callParams.begin(), Ref(lhsMemberExpr));
bodyStmts.AddBodyStmts(
Call(GetSpecialMemberName(stmt, GetRecordDeclType(ctorType->getAsRecordDecl())), callParams));
}
}
if(body) {
bodyStmts.AddBodyStmts(body);
}
bodyStmts.AddBodyStmts(Return(mkVarDeclRefExpr(kwInternalThis, Ptr(ctorDecl->getType()))));
body = mkCompoundStmt({bodyStmts});
retType = parentType;
// copy and move assignment op
} else if(IsCopyOrMoveAssign(stmt)) {
if(not stmt->doesThisDeclarationHaveABody() or stmt->isDefaulted()) {
// we don't want the default generated body
bodyStmts.clear();
processBaseClassesAndFields(stmt->getParent());
} else if(body) {
bodyStmts.AddBodyStmts(body);
}
bodyStmts.AddBodyStmts(Return(mkVarDeclRefExpr(kwInternalThis, Ptr(stmt->getType()))));
body = mkCompoundStmt({bodyStmts});
retType = parentType;
} else if(const auto* dtor = dyn_cast_or_null<CXXDestructorDecl>(stmt)) {
// Based on: https://www.dre.vanderbilt.edu/~schmidt/PDF/C++-translation.pdf
if(body) {
bodyStmts.AddBodyStmts(body);
}
if(not HasDtor(GetRecordDeclType(dtor->getParent()))) {
return;
}
for(const auto& base : llvm::reverse(dtor->getParent()->bases())) {
if(not dtor->isVirtual()) {
continue;
}
auto* lhsDeclRef = mkVarDeclRefExpr(kwInternalThis, Ptr(base.getType()));
auto* cast = Cast(lhsDeclRef, lhsDeclRef->getType());
bodyStmts.Add(
Call(GetSpecialMemberName(stmt, GetRecordDeclType(base.getType()->getAsRecordDecl())), {cast}));
body = mkCompoundStmt({bodyStmts});
}
}
params_store params{};
params.reserve(stmt->getNumParams() + 1);
if(not IsStaticStorageClass(stmt) and not stmt->isStatic()) {
params.emplace_back(kwInternalThis, parentType);
}
for(const auto& param : stmt->parameters()) {
std::string name{GetName(*param)};
auto type = param->getType();
// at least in case of a copy constructor modify the parameters
if((0 == name.length()) and
(IsCopyOrMoveCtor(dyn_cast_or_null<CXXConstructorDecl>(stmt)) or IsCopyOrMoveAssign(stmt))) {
name = "__rhs"sv;
type = Ptr(type.getNonReferenceType());
}
params.emplace_back(name, type);
}
auto* callSpecialMemberFn = Function(GetSpecialMemberName(stmt), retType, to_params_view(params));
callSpecialMemberFn->setInlineSpecified(stmt->isInlined());
callSpecialMemberFn->setStorageClass((stmt->isStatic() or IsStaticStorageClass(stmt)) ? SC_Static : SC_None);
callSpecialMemberFn->setBody(body);
InsertArg(callSpecialMemberFn);
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::FormatCast(const std::string_view,
const QualType& castDestType,
const Expr* subExpr,
const CastKind& kind)
{
// C does not have a rvalue notation and we already transformed the temporary into an object. Skip the cast to &&.
// Ignore CK_UncheckedDerivedToBase which would lead to (A)c where neither A nor c is a pointer.
if(not castDestType->isRValueReferenceType() and not(CastKind::CK_UncheckedDerivedToBase == kind)) {
mOutputFormatHelper.Append("(", GetName(castDestType), ")");
// ARM p 221:
// C* pc = new C;
// B* pb = pc -> pc = (B*) ((char*)pc+delta(B))
if(is{kind}.any_of(CastKind::CK_DerivedToBase, CastKind::CK_BaseToDerived)) {
// We have to switch in case of a base to derived cast
auto [key,
sign] = [&]() -> std::pair<std::pair<const CXXRecordDecl*, const CXXRecordDecl*>, std::string_view> {
auto plainType = [](QualType t) {
if(const auto* pt = dyn_cast_or_null<PointerType>(t.getTypePtrOrNull())) {
return pt->getPointeeType()->getAsCXXRecordDecl();
}
return t->getAsCXXRecordDecl();
};
auto base = plainType(castDestType);
auto derived = plainType(subExpr->getType());
if((CastKind::CK_BaseToDerived == kind)) {
return {{base, derived}, "-"sv};
}
return {{derived, base}, "+"sv};
}();
if(auto off = mThisPointerOffset[key]) {
mOutputFormatHelper.Append("((char*)"sv);
InsertArg(subExpr);
mOutputFormatHelper.Append(sign, off, ")"sv);
return;
}
}
}
InsertArg(subExpr);
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXNullPtrLiteralExpr*)
{
EnableGlobalInsert(GlobalInserts::HeaderStddef);
mOutputFormatHelper.Append(kwNull);
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const StaticAssertDecl* stmt)
{
EnableGlobalInsert(GlobalInserts::HeaderAssert);
mOutputFormatHelper.Append("_Static_assert"sv);
WrapInParens([&] {
InsertArg(stmt->getAssertExpr());
if(stmt->getMessage()) {
mOutputFormatHelper.Append(", "sv);
InsertArg(stmt->getMessage());
}
});
mOutputFormatHelper.AppendSemiNewLine();
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const TypedefDecl* stmt)
{
mOutputFormatHelper.AppendSemiNewLine(kwTypedefSpace, GetName(stmt->getUnderlyingType()), " "sv, GetName(*stmt));
mOutputFormatHelper.AppendNewLine();
}
//-----------------------------------------------------------------------------
static void ProcessFields(CXXRecordDecl* recordDecl, const CXXRecordDecl* rd)
{
RETURN_IF(not rd->hasDefinition())
auto AddField = [&](const FieldDecl* field) {
recordDecl->addDecl(mkFieldDecl(recordDecl, GetName(*field), field->getType()));
};
// Insert field from base classes
for(const auto& base : rd->bases()) {
// XXX: ignoring TemplateSpecializationType
if(const auto* rdBase = dyn_cast_or_null<CXXRecordDecl>(base.getType().getCanonicalType()->getAsRecordDecl())) {
ProcessFields(recordDecl, rdBase);
}
}
// insert vtable pointer if required
if(rd->isPolymorphic() and (rd->getNumBases() == 0)) {
recordDecl->addDecl(CfrontCodeGenerator::VtableData().VtblPtrField(rd));
}
// insert own fields
for(const auto* d : rd->fields()) {
AddField(d);
}
if(recordDecl->field_empty()) {
AddField(mkFieldDecl(recordDecl, "__dummy"sv, GetGlobalAST().CharTy));
}
}
//-----------------------------------------------------------------------------
static std::string GetFirstPolymorphicBaseName(const RecordDecl* decl, const RecordDecl* to)
{
std::string ret{GetName(*decl)};
if(const auto* rdecl = dyn_cast_or_null<CXXRecordDecl>(decl); rdecl->getNumBases() > 1) {
for(const auto& base : rdecl->bases()) {
if(const auto* rd = base.getType()->getAsRecordDecl(); rd == to) {
ret += GetFirstPolymorphicBaseName(rd, to);
break;
}
}
}
return ret;
}
//-----------------------------------------------------------------------------
void CfrontCodeGenerator::InsertArg(const CXXRecordDecl* stmt)
{
auto* recordDecl = Struct(GetName(*stmt));
if(stmt->hasDefinition() and stmt->isPolymorphic()) {
if(auto* itctx =
static_cast<ItaniumVTableContext*>(const_cast<ASTContext&>(GetGlobalAST()).getVTableContext())) {
#if 0
// Get mangled RTTI name
auto* mc = const_cast<ASTContext&>(GetGlobalAST()).createMangleContext(nullptr);
SmallString<256> rttiName{};
llvm::raw_svector_ostream out(rttiName);
mc->mangleCXXRTTI(QualType(stmt->getTypeForDecl(), 0), out);
DPrint("name: %s\n", rttiName.c_str());
#endif
SmallVector<Expr*, 16> mInitExprs{};
SmallVector<QualType, 5> baseList{};
if(stmt->getNumBases() == 0) {
baseList.push_back(GetRecordDeclType(stmt));
}
for(const auto& base : stmt->bases()) {
baseList.push_back(base.getType());
}
llvm::DenseMap<uint64_t, ThunkInfo> thunkMap{};
const VTableLayout& layout{itctx->getVTableLayout(stmt)};
for(const auto& [idx, thunk] : layout.vtable_thunks()) {
thunkMap[idx] = thunk;
}
unsigned clsIdx{};
unsigned funIdx{};
auto& vtblData = VtableData();
auto pushVtable = [&] {
if(funIdx) {
EnableGlobalInsert(GlobalInserts::FuncVtableStruct);
// struct __mptr __vtbl__A[] = {0, 0, 0, 0, 0, (__vptp)FunA, 0, 0, 0};
auto* thisRd = baseList[clsIdx - 1]->getAsCXXRecordDecl();
auto vtableName{StrCat("__vtbl_"sv, GetFirstPolymorphicBaseName(stmt, thisRd))};
auto* vtabl = Variable(vtableName, ContantArrayTy(vtblData.vtableRecordType, funIdx));
vtabl->setInit(InitList(mInitExprs, vtblData.vtableRecordType));
PushVtableEntry(stmt, thisRd, vtabl);
funIdx = 0;
}
mInitExprs.clear();
};
for(unsigned i = 0; const auto& vc : layout.vtable_components()) {
switch(vc.getKind()) {
case VTableComponent::CK_OffsetToTop: {
auto off = layout.getVTableOffset(clsIdx);
if(auto rem = (off % 4)) {
off += 4 - rem; // sometimes the value is misaligned. Align to 4 bytes
}
mThisPointerOffset[{stmt, baseList[clsIdx]->getAsCXXRecordDecl()}] = off * 4; // we need bytes
if(clsIdx >= 1) {
pushVtable();
}
++clsIdx;
} break;
case VTableComponent::CK_RTTI:
break;
// Source: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-components
// The entries for virtual destructors are actually pairs of entries. The first destructor,
// called the complete object destructor, performs the destruction without calling delete() on
// the object. The second destructor, called the deleting destructor, calls delete() after
// destroying the object.
case VTableComponent::CK_CompleteDtorPointer:
break; // vc.getKind() == VTableComponent::CK_CompleteDtorPointer
case VTableComponent::CK_DeletingDtorPointer:
case VTableComponent::CK_FunctionPointer: {
auto* thunkOffset = [&] {
if(ThunkInfo thunk = thunkMap.lookup(i); not thunk.isEmpty() and not thunk.This.isEmpty()) {
return Int32(thunk.This.NonVirtual);
}
return Int32(0);
}();
const auto* md = dyn_cast_or_null<FunctionDecl>(vc.getFunctionDecl());
std::string name{};
if(md->isPureVirtual()) {
EnableGlobalInsert(GlobalInserts::HeaderStdlib);
EnableGlobalInsert(GlobalInserts::FuncCxaPureVirtual);
md = Function("__cxa_pure_virtual"sv, VoidTy(), params_vector{{kwInternalThis, VoidTy()}});
name = GetName(*md);
} else {
name = GetSpecialMemberName(md);
}
auto* reicast = ReinterpretCast(vtblData.vptpTypedef, mkVarDeclRefExpr(name, md->getType()));
mInitExprs.push_back(InitList({thunkOffset, Int32(0), reicast}, vtblData.vtableRecordType));
++funIdx;
break;
}
default: break;
}
++i;
}
pushVtable();
}
}
if(stmt->hasDefinition()) {
ProcessFields(recordDecl, stmt);
recordDecl->completeDefinition();
mOutputFormatHelper.Append(kwTypedefSpace);
}
// use our freshly created recordDecl
CodeGenerator::InsertArg(recordDecl);
#if 0
// TypedefDecl above is not called
auto& ctx = GetGlobalAST();
auto et = ctx.getElaboratedType(ElaboratedTypeKeyword::ETK_Struct, nullptr, GetRecordDeclType(recordDecl), nullptr);
auto* typedefDecl = Typedef(GetName(*stmt),et);
CodeGenerator::InsertArg(typedefDecl);
#endif
// insert member functions except for the special member functions and classes defined inside this class
for(OnceTrue firstRecordDecl{}; const auto* d : stmt->decls()) {
if((isa<CXXRecordDecl>(d) and firstRecordDecl) // skip the first record decl which are ourselves
or (stmt->isLambda() and isa<CXXDestructorDecl>(d)) // skip dtor for lambdas
or isa<FieldDecl>(d) // skip fields
or isa<AccessSpecDecl>(d) // skip access specifiers
) {
continue;
}
// According to "Inside the C++ Object Model" a trivial and literal type has no ctor/dtor.
if((stmt->isTrivial() and isa<CXXConstructorDecl>(d)) or
(stmt->hasTrivialDestructor() and isa<CXXDestructorDecl>(d))) {