forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAST.cpp
More file actions
1777 lines (1595 loc) · 67.2 KB
/
Copy pathAST.cpp
File metadata and controls
1777 lines (1595 loc) · 67.2 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
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
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Utils/AST.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/Lookup.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "clang/AST/Mangle.h"
#include <memory>
#include <stdio.h>
using namespace clang;
namespace {
template<typename D>
static D* LookupResult2Decl(clang::LookupResult& R)
{
if (R.empty())
return nullptr;
R.resolveKind();
if (R.isSingleResult())
return dyn_cast<D>(R.getFoundDecl());
return (D*)-1;
}
}
namespace cling {
namespace utils {
static
QualType GetPartiallyDesugaredTypeImpl(const ASTContext& Ctx,
QualType QT,
const Transform::Config& TypeConfig,
bool fullyQualifyType,
bool fullyQualifyTmpltArg);
static
NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx,
NestedNameSpecifier* scope,
const Transform::Config& TypeConfig);
static NestedNameSpecifier*
CreateNestedNameSpecifierForScopeOf(const ASTContext& Ctx,
const Decl *decl,
bool FullyQualified);
static
NestedNameSpecifier* GetFullyQualifiedNameSpecifier(const ASTContext& Ctx,
NestedNameSpecifier* scope);
bool Analyze::IsWrapper(const FunctionDecl* ND) {
if (!ND)
return false;
if (!ND->getDeclName().isIdentifier())
return false;
return ND->getName().starts_with(Synthesize::UniquePrefix);
}
void Analyze::maybeMangleDeclName(const GlobalDecl& GD,
std::string& mangledName) {
// copied and adapted from CodeGen::CodeGenModule::getMangledName
NamedDecl* D
= cast<NamedDecl>(const_cast<Decl*>(GD.getDecl()));
std::unique_ptr<MangleContext> mangleCtx;
mangleCtx.reset(D->getASTContext().createMangleContext());
if (!mangleCtx->shouldMangleDeclName(D)) {
IdentifierInfo *II = D->getIdentifier();
assert(II && "Attempt to mangle unnamed decl.");
mangledName = II->getName().str();
return;
}
llvm::raw_string_ostream RawStr(mangledName);
#if defined(_WIN32)
// MicrosoftMangle.cpp:954 calls llvm_unreachable when mangling Dtor_Comdat
if (isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() == Dtor_Comdat) {
if (const IdentifierInfo* II = D->getIdentifier())
RawStr << II->getName();
} else
#endif
mangleCtx->mangleName(GD, RawStr);
RawStr.flush();
}
Expr* Analyze::GetOrCreateLastExpr(FunctionDecl* FD,
int* FoundAt /*=0*/,
bool omitDeclStmts /*=true*/,
Sema* S /*=0*/) {
assert(FD && "We need a function declaration!");
assert((omitDeclStmts || S)
&& "Sema needs to be set when omitDeclStmts is false");
if (FoundAt)
*FoundAt = -1;
Expr* result = nullptr;
if (CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody())) {
ArrayRef<Stmt*> Stmts(CS->body_begin(), CS->size());
int indexOfLastExpr = Stmts.size();
while(indexOfLastExpr--) {
if (!isa<NullStmt>(Stmts[indexOfLastExpr]))
break;
}
if (FoundAt)
*FoundAt = indexOfLastExpr;
if (indexOfLastExpr < 0)
return nullptr;
if ( (result = dyn_cast<Expr>(Stmts[indexOfLastExpr])) )
return result;
if (!omitDeclStmts)
if (DeclStmt* DS = dyn_cast<DeclStmt>(Stmts[indexOfLastExpr])) {
std::vector<Stmt*> newBody = Stmts.vec();
for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
E = DS->decl_rend(); I != E; ++I) {
if (VarDecl* VD = dyn_cast<VarDecl>(*I)) {
// Change the void function's return type
// We can't PushDeclContext, because we don't have scope.
Sema::ContextRAII pushedDC(*S, FD);
QualType VDTy = VD->getType().getNonReferenceType();
// Get the location of the place we will insert.
SourceLocation Loc
= newBody[indexOfLastExpr]->getEndLoc().getLocWithOffset(1);
DeclRefExpr* DRE = S->BuildDeclRefExpr(VD, VDTy,VK_LValue, Loc);
assert(DRE && "Cannot be null");
indexOfLastExpr++;
newBody.insert(newBody.begin() + indexOfLastExpr, DRE);
// Attach a new body.
FPOptionsOverride FPFeatures;
if (CS->hasStoredFPFeatures()) {
FPFeatures = CS->getStoredFPFeatures();
}
auto newCS = CompoundStmt::Create(S->getASTContext(), newBody,
FPFeatures, CS->getLBracLoc(),
CS->getRBracLoc());
FD->setBody(newCS);
if (FoundAt)
*FoundAt = indexOfLastExpr;
return DRE;
}
}
}
return result;
}
return result;
}
const char* const Synthesize::UniquePrefix = "__cling_Un1Qu3";
IntegerLiteral* Synthesize::IntegerLiteralExpr(ASTContext& C, uintptr_t Ptr) {
const llvm::APInt Addr(8 * sizeof(void*), Ptr);
return IntegerLiteral::Create(C, Addr, C.getUIntPtrType(),
SourceLocation());
}
Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uintptr_t Ptr) {
ASTContext& Ctx = S->getASTContext();
return CStyleCastPtrExpr(S, Ty, Synthesize::IntegerLiteralExpr(Ctx, Ptr));
}
Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, Expr* E) {
ASTContext& Ctx = S->getASTContext();
if (!Ty->isPointerType())
Ty = Ctx.getPointerType(Ty);
TypeSourceInfo* TSI = Ctx.getTrivialTypeSourceInfo(Ty, SourceLocation());
Expr* Result
= S->BuildCStyleCastExpr(SourceLocation(), TSI,SourceLocation(),E).get();
assert(Result && "Cannot create CStyleCastPtrExpr");
return Result;
}
static bool
GetFullyQualifiedTemplateName(const ASTContext& Ctx, TemplateName &tname) {
bool changed = false;
NestedNameSpecifier *NNS = nullptr;
TemplateDecl *argtdecl = tname.getAsTemplateDecl();
QualifiedTemplateName *qtname = tname.getAsQualifiedTemplateName();
if (qtname && !qtname->hasTemplateKeyword()) {
NNS = qtname->getQualifier();
NestedNameSpecifier *qNNS = GetFullyQualifiedNameSpecifier(Ctx,NNS);
if (qNNS != NNS) {
changed = true;
NNS = qNNS;
} else {
NNS = nullptr;
}
} else {
NNS = CreateNestedNameSpecifierForScopeOf(Ctx, argtdecl, true);
}
if (NNS) {
TemplateName UnderlyingTN(argtdecl);
if (UsingShadowDecl *USD = tname.getAsUsingShadowDecl())
UnderlyingTN = TemplateName(USD);
tname = Ctx.getQualifiedTemplateName(NNS,
/*TemplateKeyword=*/ false,
UnderlyingTN);
changed = true;
}
return changed;
}
static bool
GetFullyQualifiedTemplateArgument(const ASTContext& Ctx,
TemplateArgument &arg) {
bool changed = false;
// Note: we do not handle TemplateArgument::Expression, to replace it
// we need the information for the template instance decl.
// See GetPartiallyDesugaredTypeImpl
if (arg.getKind() == TemplateArgument::Template) {
TemplateName tname = arg.getAsTemplate();
changed = GetFullyQualifiedTemplateName(Ctx, tname);
if (changed) {
arg = TemplateArgument(tname);
}
} else if (arg.getKind() == TemplateArgument::Type) {
QualType SubTy = arg.getAsType();
// Check if the type needs more desugaring and recurse.
QualType QTFQ = TypeName::GetFullyQualifiedType(SubTy, Ctx);
if (QTFQ != SubTy) {
arg = TemplateArgument(QTFQ);
changed = true;
}
} else if (arg.getKind() == TemplateArgument::Pack) {
SmallVector<TemplateArgument, 2> desArgs;
for (auto I = arg.pack_begin(), E = arg.pack_end(); I != E; ++I) {
TemplateArgument pack_arg(*I);
changed = GetFullyQualifiedTemplateArgument(Ctx,pack_arg);
desArgs.push_back(pack_arg);
}
if (changed) {
// The allocator in ASTContext is mutable ...
// Keep the argument const to be inline will all the other interfaces
// like: NestedNameSpecifier::Create
ASTContext &mutableCtx( const_cast<ASTContext&>(Ctx) );
arg = TemplateArgument::CreatePackCopy(mutableCtx, desArgs);
}
}
return changed;
}
static const Type*
GetFullyQualifiedLocalType(const ASTContext& Ctx,
const Type *typeptr) {
// We really just want to handle the template parameter if any ....
// In case of template specializations iterate over the arguments and
// fully qualify them as well.
if (const TemplateSpecializationType* TST
= llvm::dyn_cast<const TemplateSpecializationType>(typeptr)) {
bool mightHaveChanged = false;
llvm::SmallVector<TemplateArgument, 4> desArgs;
for (const TemplateArgument& Arg : TST->template_arguments()) {
// cheap to copy and potentially modified by
// GetFullyQualifedTemplateArgument
TemplateArgument CopiedArg = Arg;
mightHaveChanged |= GetFullyQualifiedTemplateArgument(Ctx, CopiedArg);
desArgs.push_back(CopiedArg);
}
// If desugaring happened allocate new type in the AST.
if (mightHaveChanged) {
QualType QT
= Ctx.getTemplateSpecializationType(TST->getTemplateName(),
desArgs,
TST->getCanonicalTypeInternal());
return QT.getTypePtr();
}
} else if (const RecordType *TSTRecord
= llvm::dyn_cast<const RecordType>(typeptr)) {
// We are asked to fully qualify and we have a Record Type,
// which can point to a template instantiation with no sugar in any of
// its template argument, however we still need to fully qualify them.
if (const ClassTemplateSpecializationDecl* TSTdecl =
llvm::dyn_cast<ClassTemplateSpecializationDecl>(TSTRecord->getDecl()))
{
const TemplateArgumentList& templateArgs
= TSTdecl->getTemplateArgs();
bool mightHaveChanged = false;
llvm::SmallVector<TemplateArgument, 4> desArgs;
for(unsigned int I = 0, E = templateArgs.size();
I != E; ++I) {
// cheap to copy and potentially modified by
// GetFullyQualifedTemplateArgument
TemplateArgument arg(templateArgs[I]);
mightHaveChanged |= GetFullyQualifiedTemplateArgument(Ctx,arg);
desArgs.push_back(arg);
}
// If desugaring happened allocate new type in the AST.
if (mightHaveChanged) {
TemplateName TN(TSTdecl->getSpecializedTemplate());
QualType QT
= Ctx.getTemplateSpecializationType(TN, desArgs,
TSTRecord->getCanonicalTypeInternal());
return QT.getTypePtr();
}
}
}
return typeptr;
}
static NestedNameSpecifier* CreateOuterNNS(const ASTContext& Ctx,
const Decl* D,
bool FullyQualify) {
const DeclContext* DC = D->getDeclContext();
if (const NamespaceDecl* NS = dyn_cast<NamespaceDecl>(DC)) {
while (NS && NS->isInline()) {
// Ignore inline namespace;
NS = dyn_cast_or_null<NamespaceDecl>(NS->getDeclContext());
}
if (NS && NS->getDeclName())
return TypeName::CreateNestedNameSpecifier(Ctx, NS);
return nullptr; // no starting '::', no anonymous
} else if (const TagDecl* TD = dyn_cast<TagDecl>(DC)) {
return TypeName::CreateNestedNameSpecifier(Ctx, TD, FullyQualify);
} else if (const TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(DC)) {
return TypeName::CreateNestedNameSpecifier(Ctx, TDD, FullyQualify);
}
return nullptr; // no starting '::'
}
static
NestedNameSpecifier* GetFullyQualifiedNameSpecifier(const ASTContext& Ctx,
NestedNameSpecifier* scope) {
if (!scope)
return nullptr;
// Return a fully qualified version of this name specifier
if (scope->getKind() == NestedNameSpecifier::Global) {
// Already fully qualified.
return scope;
}
if (const Type *type = scope->getAsType()) {
// Find decl context.
const TagDecl* TD = nullptr;
if (const TagType* tagdecltype = dyn_cast<TagType>(type)) {
TD = tagdecltype->getDecl();
} else {
TD = type->getAsCXXRecordDecl();
}
if (TD) {
return TypeName::CreateNestedNameSpecifier(Ctx, TD,
true /*FullyQualified*/);
} else if (const TypedefType* TDD = dyn_cast<TypedefType>(type)) {
return TypeName::CreateNestedNameSpecifier(Ctx, TDD->getDecl(),
true /*FullyQualified*/);
} else if (const UsingType* UT = dyn_cast<UsingType>(type)) {
return TypeName::CreateNestedNameSpecifier(Ctx, UT->getFoundDecl(),
true /*FullyQualified*/);
}
} else if (const NamespaceDecl* NS = scope->getAsNamespace()) {
return TypeName::CreateNestedNameSpecifier(Ctx, NS);
} else if (const NamespaceAliasDecl* alias = scope->getAsNamespaceAlias()) {
const NamespaceDecl* CanonNS = alias->getNamespace()->getCanonicalDecl();
return TypeName::CreateNestedNameSpecifier(Ctx, CanonNS);
}
return scope;
}
static
NestedNameSpecifier* SelectPrefix(const ASTContext& Ctx,
const DeclContext *declContext,
NestedNameSpecifier *original_prefix,
const Transform::Config& TypeConfig) {
// We have to also desugar the prefix.
NestedNameSpecifier* prefix = nullptr;
if (declContext) {
// We had a scope prefix as input, let see if it is still
// the same as the scope of the result and if it is, then
// we use it.
if (declContext->isNamespace()) {
// Deal with namespace. This is mostly about dealing with
// namespace aliases (i.e. keeping the one the user used).
const NamespaceDecl *new_ns =dyn_cast<NamespaceDecl>(declContext);
if (new_ns) {
new_ns = new_ns->getCanonicalDecl();
NamespaceDecl *old_ns = nullptr;
if (original_prefix) {
original_prefix->getAsNamespace();
if (NamespaceAliasDecl *alias =
original_prefix->getAsNamespaceAlias())
{
old_ns = alias->getNamespace()->getCanonicalDecl();
}
}
if (old_ns == new_ns) {
// This is the same namespace, use the original prefix
// as a starting point.
prefix = GetFullyQualifiedNameSpecifier(Ctx,original_prefix);
} else {
prefix = TypeName::CreateNestedNameSpecifier(Ctx,
dyn_cast<NamespaceDecl>(new_ns));
}
}
} else {
const CXXRecordDecl* newtype=dyn_cast<CXXRecordDecl>(declContext);
if (newtype && original_prefix) {
// Deal with a class
const Type *oldtype = original_prefix->getAsType();
if (oldtype &&
// NOTE: Should we compare the RecordDecl instead?
oldtype->getAsCXXRecordDecl() == newtype)
{
// This is the same type, use the original prefix as a starting
// point.
prefix = GetPartiallyDesugaredNNS(Ctx,original_prefix,TypeConfig);
} else {
const TagDecl *tdecl = dyn_cast<TagDecl>(declContext);
if (tdecl) {
prefix = TypeName::CreateNestedNameSpecifier(Ctx, tdecl,
false /*FullyQualified*/);
}
}
} else {
// We should only create the nested name specifier
// if the outer scope is really a TagDecl.
// It could also be a CXXMethod for example.
const TagDecl *tdecl = dyn_cast<TagDecl>(declContext);
if (tdecl) {
prefix = TypeName::CreateNestedNameSpecifier(Ctx,tdecl,
false /*FullyQualified*/);
}
}
}
} else {
prefix = GetFullyQualifiedNameSpecifier(Ctx,original_prefix);
}
return prefix;
}
static
NestedNameSpecifier* SelectPrefix(const ASTContext& Ctx,
const ElaboratedType *etype,
NestedNameSpecifier *original_prefix,
const Transform::Config& TypeConfig) {
// We have to also desugar the prefix.
NestedNameSpecifier* prefix = etype->getQualifier();
if (original_prefix && prefix) {
// We had a scope prefix as input, let see if it is still
// the same as the scope of the result and if it is, then
// we use it.
const Type *newtype = prefix->getAsType();
if (newtype) {
// Deal with a class
const Type *oldtype = original_prefix->getAsType();
if (oldtype &&
// NOTE: Should we compare the RecordDecl instead?
oldtype->getAsCXXRecordDecl() == newtype->getAsCXXRecordDecl())
{
// This is the same type, use the original prefix as a starting
// point.
prefix = GetPartiallyDesugaredNNS(Ctx,original_prefix,TypeConfig);
} else {
prefix = GetPartiallyDesugaredNNS(Ctx,prefix,TypeConfig);
}
} else {
// Deal with namespace. This is mostly about dealing with
// namespace aliases (i.e. keeping the one the user used).
const NamespaceDecl *new_ns = prefix->getAsNamespace();
if (new_ns) {
new_ns = new_ns->getCanonicalDecl();
}
else if (NamespaceAliasDecl *alias = prefix->getAsNamespaceAlias() )
{
new_ns = alias->getNamespace()->getCanonicalDecl();
}
if (new_ns) {
const NamespaceDecl *old_ns = original_prefix->getAsNamespace();
if (old_ns) {
old_ns = old_ns->getCanonicalDecl();
}
else if (NamespaceAliasDecl *alias =
original_prefix->getAsNamespaceAlias())
{
old_ns = alias->getNamespace()->getCanonicalDecl();
}
if (old_ns == new_ns) {
// This is the same namespace, use the original prefix
// as a starting point.
prefix = GetFullyQualifiedNameSpecifier(Ctx,original_prefix);
} else {
prefix = GetFullyQualifiedNameSpecifier(Ctx,prefix);
}
} else {
prefix = GetFullyQualifiedNameSpecifier(Ctx,prefix);
}
}
}
return prefix;
}
static
NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx,
NestedNameSpecifier* scope,
const Transform::Config& TypeConfig) {
// Desugar the scope qualifier if needed.
if (const Type* scope_type = scope->getAsType()) {
// this is not a namespace, so we might need to desugar
QualType desugared = GetPartiallyDesugaredTypeImpl(Ctx,
QualType(scope_type,0),
TypeConfig,
/*qualifyType=*/false,
/*qualifyTmpltArg=*/true);
NestedNameSpecifier* outer_scope = scope->getPrefix();
const ElaboratedType* etype
= dyn_cast<ElaboratedType>(desugared.getTypePtr());
if (etype) {
// The desugarding returned an elaborated type even-though we
// did not request it (/*fullyQualify=*/false), so we must have been
// looking a typedef pointing at a (or another) scope.
if (outer_scope) {
outer_scope = SelectPrefix(Ctx,etype,outer_scope,TypeConfig);
} else {
outer_scope = GetPartiallyDesugaredNNS(Ctx,etype->getQualifier(),
TypeConfig);
}
desugared = etype->getNamedType();
} else {
Decl* decl = nullptr;
if (!desugared.isNull()) {
const Type* desugaredTy = desugared.getTypePtr();
switch (desugaredTy->getTypeClass()) {
case Type::Typedef:
decl = cast<TypedefType>(desugaredTy)->getDecl();
break;
case Type::Using:
decl = cast<UsingType>(desugaredTy)->getFoundDecl();
break;
case Type::Record:
case Type::Enum:
decl = cast<TagType>(desugaredTy)->getDecl();
break;
default: decl = desugared->getAsCXXRecordDecl(); break;
}
}
if (decl) {
NamedDecl* outer
= dyn_cast_or_null<NamedDecl>(decl->getDeclContext());
NamespaceDecl* outer_ns
= dyn_cast_or_null<NamespaceDecl>(decl->getDeclContext());
if (outer
&& !(outer_ns && outer_ns->isAnonymousNamespace())
&& outer->getName().size() ) {
outer_scope = SelectPrefix(Ctx,decl->getDeclContext(),
outer_scope,TypeConfig);
} else {
outer_scope = nullptr;
}
} else if (outer_scope) {
outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypeConfig);
}
}
return NestedNameSpecifier::Create(Ctx,outer_scope,
false /* template keyword wanted */,
desugared.getTypePtr());
} else {
return GetFullyQualifiedNameSpecifier(Ctx,scope);
}
}
bool Analyze::IsStdOrCompilerDetails(const NamedDecl &decl)
{
// Return true if the TagType is a 'details' of the std implementation
// or declared within std.
// Details means (For now) declared in __gnu_cxx or starting with
// underscore.
IdentifierInfo *info = decl.getDeclName().getAsIdentifierInfo();
if (info && info->getNameStart()[0] == '_') {
// We have a name starting by _, this is reserve for compiler
// implementation, so let's not desugar to it.
return true;
}
// And let's check if it is in one of the know compiler implementation
// namespace.
const NamedDecl *outer =dyn_cast_or_null<NamedDecl>(decl.getDeclContext());
while (outer && outer->getName().size() ) {
if (outer->getName().compare("std") == 0 ||
outer->getName().compare("__gnu_cxx") == 0) {
return true;
}
outer = dyn_cast_or_null<NamedDecl>(outer->getDeclContext());
}
return false;
}
bool Analyze::IsStdClass(const clang::NamedDecl &cl)
{
// Return true if the class or template is declared directly in the
// std namespace (modulo inline namespace).
return cl.getDeclContext()->isStdNamespace();
}
// See Sema::PushOnScopeChains
bool Analyze::isOnScopeChains(const NamedDecl* ND, Sema& SemaR) {
// Named decls without name shouldn't be in. Eg: struct {int a};
if (!ND->getDeclName())
return false;
// Out-of-line definitions shouldn't be pushed into scope in C++.
// Out-of-line variable and function definitions shouldn't even in C.
if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
!ND->getDeclContext()->getRedeclContext()->Equals(
ND->getLexicalDeclContext()->getRedeclContext()))
return false;
// Template instantiations should also not be pushed into scope.
if (isa<FunctionDecl>(ND) &&
cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
return false;
// Using directives are not registered onto the scope chain
if (isa<UsingDirectiveDecl>(ND))
return false;
IdentifierResolver::iterator
IDRi = SemaR.IdResolver.begin(ND->getDeclName()),
IDRiEnd = SemaR.IdResolver.end();
for (; IDRi != IDRiEnd; ++IDRi) {
if (ND == *IDRi)
return true;
}
// Check if the declaration is template instantiation, which is not in
// any DeclContext yet, because it came from
// Sema::PerformPendingInstantiations
// if (isa<FunctionDecl>(D) &&
// cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
// return false;
return false;
}
unsigned int
Transform::Config::DropDefaultArg(clang::TemplateDecl &Template) const
{
/// Return the number of default argument to drop.
if (Analyze::IsStdClass(Template)) {
static const char *stls[] = //container names
{"vector","list","deque","map","multimap","set","multiset",nullptr};
static unsigned int values[] = //number of default arg.
{1,1,1,2,2,2,2};
StringRef name = Template.getName();
for(int k=0;stls[k];k++) {
if (name == stls[k])
return values[k];
}
}
// Check in some struct if the Template decl is registered something like
/*
DefaultCollection::const_iterator iter;
iter = m_defaultArgs.find(&Template);
if (iter != m_defaultArgs.end()) {
return iter->second;
}
*/
return 0;
}
static bool ShouldKeepTypedef(const TypedefType* TT,
const llvm::SmallSet<const Decl*, 4>& ToSkip)
{
// Return true, if we should keep this typedef rather than desugaring it.
return 0 != ToSkip.count(TT->getDecl()->getCanonicalDecl());
}
static bool SingleStepPartiallyDesugarTypeImpl(QualType& QT)
{
// WARNING:
//
// The large blocks of commented-out code in this routine
// are there to support doing more desugaring in the future,
// we will probably have to.
//
// Do not delete until we are completely sure we will
// not be changing this routine again!
//
const Type* QTy = QT.getTypePtr();
Type::TypeClass TC = QTy->getTypeClass();
switch (TC) {
//
// Unconditionally sugared types.
//
case Type::Paren: {
return false;
//const ParenType* Ty = llvm::cast<ParenType>(QTy);
//QT = Ty->desugar();
//return true;
}
case Type::Typedef: {
const TypedefType* Ty = llvm::cast<TypedefType>(QTy);
QT = Ty->desugar();
return true;
}
case Type::Using: {
const UsingType* Ty = llvm::cast<UsingType>(QTy);
QT = Ty->desugar();
return true;
}
case Type::TypeOf: {
const TypeOfType* Ty = llvm::cast<TypeOfType>(QTy);
QT = Ty->desugar();
return true;
}
case Type::Attributed: {
return false;
//const AttributedType* Ty = llvm::cast<AttributedType>(QTy);
//QT = Ty->desugar();
//return true;
}
case Type::SubstTemplateTypeParm: {
const SubstTemplateTypeParmType* Ty =
llvm::cast<SubstTemplateTypeParmType>(QTy);
QT = Ty->desugar();
return true;
}
case Type::Elaborated: {
const ElaboratedType* Ty = llvm::cast<ElaboratedType>(QTy);
QT = Ty->desugar();
return true;
}
//
// Conditionally sugared types.
//
case Type::TypeOfExpr: {
const TypeOfExprType* Ty = llvm::cast<TypeOfExprType>(QTy);
if (Ty->isSugared()) {
QT = Ty->desugar();
return true;
}
return false;
}
case Type::Decltype: {
const DecltypeType* Ty = llvm::cast<DecltypeType>(QTy);
if (Ty->isSugared()) {
QT = Ty->desugar();
return true;
}
return false;
}
case Type::UnaryTransform: {
const UnaryTransformType* Ty = llvm::cast<UnaryTransformType>(QTy);
if (Ty->isSugared()) {
QT = Ty->desugar();
return true;
}
return false;
}
case Type::Auto: {
return false;
//const AutoType* Ty = llvm::cast<AutoType>(QTy);
//if (Ty->isSugared()) {
// QT = Ty->desugar();
// return true;
//}
//return false;
}
case Type::TemplateSpecialization: {
//const TemplateSpecializationType* Ty =
// llvm::cast<TemplateSpecializationType>(QTy);
// Too broad, this returns a the target template but with
// canonical argument types.
//if (Ty->isTypeAlias()) {
// QT = Ty->getAliasedType();
// return true;
//}
// Too broad, this returns the canonical type
//if (Ty->isSugared()) {
// QT = Ty->desugar();
// return true;
//}
return false;
}
// Not a sugared type.
default: {
break;
}
}
return false;
}
bool Transform::SingleStepPartiallyDesugarType(QualType &QT,
const ASTContext &Context) {
Qualifiers quals = QT.getQualifiers();
bool desugared = SingleStepPartiallyDesugarTypeImpl( QT );
if (desugared) {
// If the types has been desugared it also lost its qualifiers.
QT = Context.getQualifiedType(QT, quals);
}
return desugared;
}
static bool GetPartiallyDesugaredTypeImpl(const ASTContext& Ctx,
TemplateArgument &arg,
const Transform::Config& TypeConfig,
bool fullyQualifyTmpltArg) {
bool changed = false;
if (arg.getKind() == TemplateArgument::Template) {
TemplateName tname = arg.getAsTemplate();
// Desugar before fully qualifying.
if (std::optional<TemplateName> UnderlyingOrNone = tname.desugar(/*IgnoreDeduced=*/false)) {
if (*UnderlyingOrNone != tname) {
tname = *UnderlyingOrNone;
changed = true;
}
}
changed = GetFullyQualifiedTemplateName(Ctx, tname);
if (changed) {
arg = TemplateArgument(tname);
}
} else if (arg.getKind() == TemplateArgument::Type) {
QualType SubTy = arg.getAsType();
// Check if the type needs more desugaring and recurse.
if (isa<TypedefType>(SubTy)
|| isa<UsingType>(SubTy)
|| isa<TemplateSpecializationType>(SubTy)
|| isa<ElaboratedType>(SubTy)
|| fullyQualifyTmpltArg) {
changed = true;
QualType PDQT
= GetPartiallyDesugaredTypeImpl(Ctx, SubTy, TypeConfig,
/*fullyQualifyType=*/true,
/*fullyQualifyTmpltArg=*/true);
arg = TemplateArgument(PDQT);
}
} else if (arg.getKind() == TemplateArgument::Pack) {
SmallVector<TemplateArgument, 2> desArgs;
for (auto I = arg.pack_begin(), E = arg.pack_end(); I != E; ++I) {
TemplateArgument pack_arg(*I);
changed = GetPartiallyDesugaredTypeImpl(Ctx,pack_arg,
TypeConfig,
fullyQualifyTmpltArg);
desArgs.push_back(pack_arg);
}
if (changed) {
// The allocator in ASTContext is mutable ...
// Keep the argument const to be inline will all the other interfaces
// like: NestedNameSpecifier::Create
ASTContext &mutableCtx( const_cast<ASTContext&>(Ctx) );
arg = TemplateArgument::CreatePackCopy(mutableCtx, desArgs);
}
}
return changed;
}
static const TemplateArgument*
GetTmpltArgDeepFirstIndexPack(size_t &cur,
const TemplateArgument& arg,
size_t idx) {
SmallVector<TemplateArgument, 2> desArgs;
for (auto I = arg.pack_begin(), E = arg.pack_end();
cur < idx && I != E; ++cur,++I) {
if ((*I).getKind() == TemplateArgument::Pack) {
auto p_arg = GetTmpltArgDeepFirstIndexPack(cur,(*I),idx);
if (cur == idx) return p_arg;
} else if (cur == idx) {
return I;
}
}
return nullptr;
}
// Return the template argument corresponding to the index (idx)
// when the composite list of arguement is seen flattened out deep
// first (where depth is provided by template argument packs)
static const TemplateArgument*
GetTmpltArgDeepFirstIndex(const TemplateArgumentList& templateArgs,
size_t idx) {
for (size_t cur = 0, I = 0, E = templateArgs.size();
cur <= idx && I < E; ++I, ++cur) {
auto &arg = templateArgs[I];
if (arg.getKind() == TemplateArgument::Pack) {
// Need to recurse.
auto p_arg = GetTmpltArgDeepFirstIndexPack(cur,arg,idx);
if (cur == idx) return p_arg;
} else if (cur == idx) {
return &arg;
}
}
return nullptr;
}
static QualType GetPartiallyDesugaredTypeImpl(const ASTContext& Ctx,
QualType QT, const Transform::Config& TypeConfig,
bool fullyQualifyType, bool fullyQualifyTmpltArg)
{
if (QT.isNull())
return QT;
// If there are no constraints, then use the standard desugaring.
if (TypeConfig.empty() && !fullyQualifyType && !fullyQualifyTmpltArg)
return QT.getDesugaredType(Ctx);
// In case of Int_t* we need to strip the pointer first, desugar and attach
// the pointer once again.
if (isa<PointerType>(QT.getTypePtr())) {
// Get the qualifiers.
Qualifiers quals = QT.getQualifiers();
QualType nQT;
nQT = GetPartiallyDesugaredTypeImpl(Ctx, QT->getPointeeType(), TypeConfig,
fullyQualifyType,fullyQualifyTmpltArg);
if (nQT == QT->getPointeeType()) return QT;
QT = Ctx.getPointerType(nQT);
// Add back the qualifiers.
QT = Ctx.getQualifiedType(QT, quals);
return QT;
}
while (isa<SubstTemplateTypeParmType>(QT.getTypePtr())) {
// Get the qualifiers.
Qualifiers quals = QT.getQualifiers();
QT = dyn_cast<SubstTemplateTypeParmType>(QT.getTypePtr())->desugar();
// Add back the qualifiers.
QT = Ctx.getQualifiedType(QT, quals);
}
// In case of Int_t& we need to strip the pointer first, desugar and attach
// the reference once again.
if (isa<ReferenceType>(QT.getTypePtr())) {
// Get the qualifiers.
bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());
Qualifiers quals = QT.getQualifiers();
QualType nQT;
nQT = GetPartiallyDesugaredTypeImpl(Ctx, QT->getPointeeType(), TypeConfig,
fullyQualifyType,fullyQualifyTmpltArg);
if (nQT == QT->getPointeeType()) return QT;
// Add the r- or l-value reference type back to the desugared one.
if (isLValueRefTy)
QT = Ctx.getLValueReferenceType(nQT);
else
QT = Ctx.getRValueReferenceType(nQT);
// Add back the qualifiers.
QT = Ctx.getQualifiedType(QT, quals);
return QT;
}
// In case of Int_t[2] we need to strip the array first, desugar and attach
// the array once again.
if (isa<ArrayType>(QT.getTypePtr())) {
// Get the qualifiers.
Qualifiers quals = QT.getQualifiers();
if (isa<ConstantArrayType>(QT.getTypePtr())) {
const ConstantArrayType *arr