forked from include-what-you-use/include-what-you-use
-
Notifications
You must be signed in to change notification settings - Fork 5
/
iwyu.cc
4345 lines (3842 loc) · 178 KB
/
iwyu.cc
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
//===--- iwyu.cc - main logic and driver for include-what-you-use ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// A Clang-based tool that catches Include-What-You-Use violations:
//
// The analysis enforces the following rule:
//
// - For every symbol (variable, function, constant, type, and macro)
// X in C++ file CU.cc, X must be declared in CU.cc or in a header
// file directly included by itself, CU.h, or CU-inl.h. Likewise
// for CU.h and CU-inl.h.
//
// The rule has a few slight wrinkles:
// 1) CU_test.cc can also 'inherit' #includes from CU.h and CU-inl.h.
// Likewise for CU_unittest.cc, CU_regtest.cc, etc.
// 2) CU.cc can inherit #includes from ../public/CU.h in addition to
// ./CU.h (likewise for -inl.h).
// 3) For system #includes, and a few google #includes, we hard-code
// in knowledge of which #include files are public and which are not.
// (For instance, <vector> is public, <bits/stl_vector.h> is not.)
// We force CU.cc, CU.h, and CU-inl.h to #include the public version.
//
// iwyu.cc checks if a symbol can be forward-declared instead of fully
// declared. If so, it will enforce the rule that the symbol is
// forward-declared in the file that references it. We only forward-
// declare classes and structs (possibly templatized). We will not
// try to forward-declare variables or functions.
//
// Checking iwyu violations for variables, functions, constants, and
// macros is easy. Types can be trickier. Obviously, if you declare
// a variable of type Foo in cu.cc, it's straightforward to check
// whether it's an iwyu violation. But what if you call a function
// that returns a type, e.g. 'if (FnReturningSomeSTLType()->empty())'?
// Is it an iwyu violation if you don't #include the header for that
// STL type? We say no: whatever file provided the function
// FnReturningSomeSTLType is also responsible for providing whatever
// the STL type is, so we don't have to. Otherwise, we get into an
// un-fun propagation problem if we change the signature of
// FnReturningSomeSTLType to return a different type of STL type. So
// in general, types are only iwyu-checked if they appear explicitly
// in the source code.
//
// It can likewise be difficult to say whether a template arg is
// forward-declable: set<Foo*> x does not require the full type info
// for Foo, but remove_pointer<Foo*>::type does. And f<Foo>() doesn't
// require full type info for Foo if f doesn't actually use Foo in it.
// For now we do the simple heuristic that if the template arg is a
// pointer, it's ok if it's forward-declared, and if not, it's not.
//
// We use the following terminology:
//
// - A *symbol* is the name of a function, variable, constant, type,
// macro, etc.
//
// - A *quoted include path* is an include path with the surrounding <>
// or "", e.g. <stdio.h> or "ads/util.h".
//
// - Any #include falls into exactly one of three (non-overlapping)
// categories:
//
// * it's said to be *necessary* if it's a compiler or IWYU error to
// omit the #include;
//
// * it's said to be *optional* if the #include is unnecessary but
// having it is not an IWYU error either (e.g. if bar.h is a
// necessary #include of foo.h, and foo.cc uses symbols from
// bar.h, it's optional for foo.cc to #include bar.h.);
//
// * it's said to be *undesired* if it's an IWYU error to have the
// #include.
//
// Therefore, when we say a #include is *desired*, we mean that it's
// either necessary or optional.
//
// - We also say that a #include is *recommended* if the IWYU tool
// recommends to have it in the C++ source file. Obviously, any
// necessary #include must be recommended, and no undesired
// #include can be recommended. An optional #include can be
// either recommended or not -- the IWYU tool can decide which
// case it is. For example, if foo.cc desires bar.h, but can
// already get it via foo.h, IWYU won't recommend foo.cc to
// #include bar.h, unless it already does so.
#include <algorithm> // for swap, find, make_pair
#include <cstddef> // for size_t
#include <cstdlib> // for atoi, exit
#include <cstring>
#include <deque> // for swap
#include <iterator> // for find
#include <list> // for swap
#include <map> // for map, swap, etc
#include <memory> // for unique_ptr
#include <set> // for set, set<>::iterator, swap
#include <string> // for string, operator+, etc
#include <utility> // for pair, make_pair
#include <vector> // for vector, swap
#include "iwyu_ast_util.h"
#include "iwyu_cache.h"
#include "iwyu_globals.h"
#include "iwyu_lexer_utils.h"
#include "iwyu_location_util.h"
#include "iwyu_output.h"
#include "iwyu_path_util.h"
#include "iwyu_port.h" // for CHECK_
#include "iwyu_preprocessor.h"
#include "iwyu_stl_util.h"
#include "iwyu_string_util.h"
#include "iwyu_use_flags.h"
#include "iwyu_verrs.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/Sema.h"
namespace clang {
class FileEntry;
class PPCallbacks;
} // namespace clang
namespace include_what_you_use {
// I occasionally clean up this list by running:
// $ grep "using clang":: iwyu.cc | cut -b14- | tr -d ";" | while read t; do grep -q "[^:]$t" iwyu.cc || echo $t; done
using clang::ASTConsumer;
using clang::ASTContext;
using clang::ASTFrontendAction;
using clang::Attr;
using clang::CXXConstructExpr;
using clang::CXXConstructorDecl;
using clang::CXXDeleteExpr;
using clang::CXXDestructorDecl;
using clang::CXXMethodDecl;
using clang::CXXNewExpr;
using clang::CXXOperatorCallExpr;
using clang::CXXRecordDecl;
using clang::CallExpr;
using clang::ClassTemplateDecl;
using clang::ClassTemplateSpecializationDecl;
using clang::CompilerInstance;
using clang::ConceptSpecializationExpr;
using clang::ConstructorUsingShadowDecl;
using clang::Decl;
using clang::DeclContext;
using clang::DeclRefExpr;
using clang::DeducedTemplateSpecializationType;
using clang::EnumConstantDecl;
using clang::EnumDecl;
using clang::EnumType;
using clang::Expr;
using clang::FileEntry;
using clang::FriendDecl;
using clang::FriendTemplateDecl;
using clang::FunctionDecl;
using clang::FunctionProtoType;
using clang::FunctionTemplateDecl;
using clang::FunctionType;
using clang::LValueReferenceType;
using clang::LinkageSpecDecl;
using clang::MemberExpr;
using clang::NamedDecl;
using clang::NestedNameSpecifier;
using clang::NestedNameSpecifierLoc;
using clang::OverloadExpr;
using clang::ParmVarDecl;
using clang::PPCallbacks;
using clang::PointerType;
using clang::QualType;
using clang::QualifiedTypeLoc;
using clang::RecordDecl;
using clang::RecursiveASTVisitor;
using clang::ReferenceType;
using clang::Sema;
using clang::SourceLocation;
using clang::Stmt;
using clang::SubstTemplateTypeParmType;
using clang::TagDecl;
using clang::TagType;
using clang::TemplateArgument;
using clang::TemplateArgumentList;
using clang::TemplateArgumentLoc;
using clang::TemplateDecl;
using clang::TemplateName;
using clang::TemplateSpecializationType;
using clang::TemplateSpecializationTypeLoc;
using clang::TranslationUnitDecl;
using clang::Type;
using clang::TypeDecl;
using clang::TypeLoc;
using clang::TypedefDecl;
using clang::TypedefNameDecl;
using clang::TypedefType;
using clang::UnaryExprOrTypeTraitExpr;
using clang::UsingDecl;
using clang::UsingDirectiveDecl;
using clang::UsingShadowDecl;
using clang::ValueDecl;
using clang::VarDecl;
using llvm::cast;
using llvm::dyn_cast;
using llvm::dyn_cast_or_null;
using llvm::errs;
using llvm::isa;
using std::make_pair;
using std::map;
using std::set;
using std::string;
using std::swap;
using std::vector;
namespace {
bool CanIgnoreLocation(SourceLocation loc) {
// If we're in a macro expansion, we always want to treat this as
// being in the expansion location, never the as-written location,
// since that's what the compiler does. CanIgnoreCurrentASTNode()
// is an optimization, so we want to be conservative about what we
// ignore.
const FileEntry* file_entry = GetFileEntry(loc);
const FileEntry* file_entry_after_macro_expansion =
GetFileEntry(GetInstantiationLoc(loc));
// ignore symbols used outside foo.{h,cc} + check_also
return (!ShouldReportIWYUViolationsFor(file_entry) &&
!ShouldReportIWYUViolationsFor(file_entry_after_macro_expansion));
}
} // anonymous namespace
// ----------------------------------------------------------------------
// --- BaseAstVisitor
// ----------------------------------------------------------------------
//
// We have a hierarchy of AST visitor classes, to keep the logic
// as clear as possible. The top level, BaseAstVisitor, has some
// basic, not particularly iwyu-related, functionality:
//
// 1) Maintain current_ast_node_, the current chain in the AST tree.
// 2) Provide functions related to the current location.
// 3) Print each node we're visiting, depending on --verbose settings.
// 4) Add appropriate implicit text. iwyu acts as if all constructor
// initializers were explicitly written, all default constructors
// were explicitly written, etc, even if they're not. We traverse
// the implicit stuff as if it were explicit.
// 5) Add two callbacks that subclasses can override (just like any
// other AST callback): TraverseImplicitDestructorCall and
// HandleFunctionCall. TraverseImplicitDestructorCall is a
// callback for a "pseudo-AST" node that covers destruction not
// specified in source, such as a destructor destroying one of the
// fields in its class. HandleFunctionCall is a convenience
// callback that bundles callbacks from many different kinds of
// function-calling callbacks (CallExpr, CXXConstructExpr, etc)
// into one place.
//
// To maintain current_ast_node_ properly, this class also implements
// VisitNestedNameSpecifier, VisitTemplateName, VisitTemplateArg, and
// VisitTemplateArgLoc, which are parallel to the Visit*Decl()/etc
// visitors. Subclasses should override these Visit routines, and not
// the Traverse routine directly.
template <class Derived>
class BaseAstVisitor : public RecursiveASTVisitor<Derived> {
public:
typedef RecursiveASTVisitor<Derived> Base;
// We need to create implicit ctor/dtor nodes, which requires
// non-const methods on CompilerInstance, so the var can't be const.
explicit BaseAstVisitor(CompilerInstance* compiler)
: compiler_(compiler),
current_ast_node_(nullptr) {}
virtual ~BaseAstVisitor() = default;
//------------------------------------------------------------
// Pure virtual methods that a subclass must implement.
// Returns true if we are not interested in the current ast node for
// any reason (for instance, it lives in a file we're not
// analyzing).
virtual bool CanIgnoreCurrentASTNode() const = 0;
// Returns true if we should print the information for the
// current AST node, given what file it's in. For instance,
// except at very high verbosity levels, we don't print AST
// nodes from system header files.
virtual bool ShouldPrintSymbolFromCurrentFile() const = 0;
// A string to add to the information we print for each symbol.
// Each subclass can thus annotate if it's handling a node.
// The return value, if not empty, should start with a space!
virtual string GetSymbolAnnotation() const = 0;
//------------------------------------------------------------
// (1) Maintain current_ast_node_
// How subclasses can access current_ast_node_;
const ASTNode* current_ast_node() const {
return current_ast_node_;
}
ASTNode* current_ast_node() {
return current_ast_node_;
}
void set_current_ast_node(ASTNode* an) { current_ast_node_ = an; }
bool TraverseDecl(Decl* decl) {
if (current_ast_node_ && current_ast_node_->StackContainsContent(decl))
return true; // avoid recursion
ASTNode node(decl);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
return Base::TraverseDecl(decl);
}
bool TraverseStmt(Stmt* stmt) {
if (current_ast_node_ && current_ast_node_->StackContainsContent(stmt))
return true; // avoid recursion
ASTNode node(stmt);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
return Base::TraverseStmt(stmt);
}
bool TraverseType(QualType qualtype) {
if (qualtype.isNull())
return Base::TraverseType(qualtype);
const Type* type = qualtype.getTypePtr();
if (current_ast_node_ && current_ast_node_->StackContainsContent(type))
return true; // avoid recursion
ASTNode node(type);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
return Base::TraverseType(qualtype);
}
// RecursiveASTVisitor has a hybrid type-visiting system: it will
// call TraverseTypeLoc when it can, but will call TraverseType
// otherwise. For instance, if we see a FunctionDecl, and it
// exposes the return type via a TypeLoc, it will recurse via
// TraverseTypeLoc. If it exposes the return type only via a
// QualType, though, it will recurse via TraverseType. The upshot
// is we need two versions of all the Traverse*Type routines. (We
// don't need two versions the Visit*Type routines, since the
// default behavior of Visit*TypeLoc is to just call Visit*Type.)
bool TraverseTypeLoc(TypeLoc typeloc) {
// QualifiedTypeLoc is a bit of a special case in the typeloc
// system, off to the side. We don't care about qualifier
// positions, so avoid the need for special-casing by just
// traversing the unqualified version instead.
if (typeloc.getAs<QualifiedTypeLoc>()) {
typeloc = typeloc.getUnqualifiedLoc();
}
if (current_ast_node_ && current_ast_node_->StackContainsContent(&typeloc))
return true; // avoid recursion
ASTNode node(&typeloc);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
return Base::TraverseTypeLoc(typeloc);
}
bool TraverseNestedNameSpecifier(NestedNameSpecifier* nns) {
if (nns == nullptr)
return true;
ASTNode node(nns);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
if (!this->getDerived().VisitNestedNameSpecifier(nns))
return false;
return Base::TraverseNestedNameSpecifier(nns);
}
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc nns_loc) {
if (!nns_loc) // using NNSLoc::operator bool()
return true;
ASTNode node(&nns_loc);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
// TODO(csilvers): have VisitNestedNameSpecifierLoc instead.
if (!this->getDerived().VisitNestedNameSpecifier(
nns_loc.getNestedNameSpecifier()))
return false;
return Base::TraverseNestedNameSpecifierLoc(nns_loc);
}
bool TraverseTemplateName(TemplateName template_name) {
ASTNode node(&template_name);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
if (!this->getDerived().VisitTemplateName(template_name))
return false;
return Base::TraverseTemplateName(template_name);
}
bool TraverseTemplateArgument(const TemplateArgument& arg) {
ASTNode node(&arg);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
if (!this->getDerived().VisitTemplateArgument(arg))
return false;
return Base::TraverseTemplateArgument(arg);
}
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
ASTNode node(&argloc);
CurrentASTNodeUpdater canu(¤t_ast_node_, &node);
if (!this->getDerived().VisitTemplateArgumentLoc(argloc))
return false;
return Base::TraverseTemplateArgumentLoc(argloc);
}
//------------------------------------------------------------
// (2) Provide functions related to the current location.
SourceLocation CurrentLoc() const {
CHECK_(current_ast_node_ && "Call CurrentLoc within Visit* or Traverse*");
return current_ast_node_->GetLocation();
}
string CurrentFilePath() const {
return GetFilePath(CurrentLoc());
}
const FileEntry* CurrentFileEntry() const {
return GetFileEntry(CurrentLoc());
}
string PrintableCurrentLoc() const {
return PrintableLoc(CurrentLoc());
}
//------------------------------------------------------------
// (3) Print each node we're visiting.
// The current file location, the class or decl or type name in
// brackets, along with annotations such as the indentation depth,
// etc.
string AnnotatedName(const string& name) const {
return (PrintableCurrentLoc() + ": (" +
std::to_string(current_ast_node_->depth()) + GetSymbolAnnotation() +
(current_ast_node_->in_forward_declare_context() ?
", fwd decl" : "") +
") [ " + name + " ] ");
}
// At verbose level 7 and above, returns a printable version of
// the pointer, suitable for being emitted after AnnotatedName.
// At lower verbose levels, returns the empty string.
string PrintablePtr(const void* ptr) const {
if (ShouldPrint(7)) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "%p ", ptr);
return buffer;
}
return "";
}
// The top-level Decl class. All Decls call this visitor (in
// addition to any more-specific visitors that apply for a
// particular decl).
bool VisitDecl(clang::Decl* decl) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName(GetKindName(decl)) << PrintablePtr(decl)
<< PrintableDecl(decl) << "\n";
}
return true;
}
bool VisitStmt(clang::Stmt* stmt) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName(GetKindName(stmt)) << PrintablePtr(stmt)
<< PrintableStmt(stmt) << "\n";
}
return true;
}
bool VisitType(clang::Type* type) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName(GetKindName(type)) << PrintablePtr(type)
<< PrintableType(type) << "\n";
}
return true;
}
// Make sure our logging message shows we're in the TypeLoc hierarchy.
bool VisitTypeLoc(clang::TypeLoc typeloc) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName(GetKindName(typeloc)) << PrintableTypeLoc(typeloc)
<< "\n";
}
return true;
}
bool VisitNestedNameSpecifier(NestedNameSpecifier* nns) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("NestedNameSpecifier")
<< PrintablePtr(nns) << PrintableNestedNameSpecifier(nns) << "\n";
}
return true;
}
bool VisitTemplateName(TemplateName template_name) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("TemplateName")
<< PrintableTemplateName(template_name) << "\n";
}
return true;
}
bool VisitTemplateArgument(const TemplateArgument& arg) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("TemplateArgument")
<< PrintablePtr(&arg) << PrintableTemplateArgument(arg) << "\n";
}
return true;
}
bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("TemplateArgumentLoc")
<< PrintablePtr(&argloc) << PrintableTemplateArgumentLoc(argloc)
<< "\n";
}
return true;
}
//------------------------------------------------------------
// (4) Add implicit text.
//
// This simulates a call to the destructor of every non-POD field and base
// class in all classes with destructors, to mark them as used by virtue of
// being class members.
bool TraverseCXXDestructorDecl(clang::CXXDestructorDecl* decl) {
if (!Base::TraverseCXXDestructorDecl(decl))
return false;
if (CanIgnoreCurrentASTNode())
return true;
// We only care about calls that are actually defined.
if (!decl || !decl->isThisDeclarationADefinition())
return true;
// Collect all the fields (and bases) we destroy, and call the dtor.
set<const Type*> member_types;
const CXXRecordDecl* record = decl->getParent();
for (RecordDecl::field_iterator it = record->field_begin();
it != record->field_end(); ++it) {
member_types.insert(it->getType().getTypePtr());
}
for (CXXRecordDecl::base_class_const_iterator it = record->bases_begin();
it != record->bases_end(); ++it) {
member_types.insert(it->getType().getTypePtr());
}
for (const Type* type : member_types) {
const NamedDecl* member_decl = TypeToDeclAsWritten(type);
// We only want those fields that are c++ classes.
if (const CXXRecordDecl* cxx_field_decl = DynCastFrom(member_decl)) {
if (const CXXDestructorDecl* field_dtor =
cxx_field_decl->getDestructor()) {
if (!this->getDerived().TraverseImplicitDestructorCall(
const_cast<CXXDestructorDecl*>(field_dtor), type))
return false;
}
}
}
return true;
}
// Class template specialization are similar to regular C++ classes,
// particularly they need the same custom handling of implicit destructors.
bool TraverseClassTemplateSpecializationDecl(
clang::ClassTemplateSpecializationDecl* decl) {
if (!Base::TraverseClassTemplateSpecializationDecl(decl))
return false;
return Base::TraverseCXXRecordDecl(decl);
}
//------------------------------------------------------------
// (5) Add TraverseImplicitDestructorCall and HandleFunctionCall.
// TraverseImplicitDestructorCall: This is a callback this class
// introduces that is a first-class callback just like any AST-node
// callback. It is used to cover two places where the compiler
// destroys objects, but there's no written indication of that in
// the text: (1) when a local variable or a temporary goes out of
// scope (NOTE: in this case, we attribute the destruction to the
// same line as the corresponding construction, not to where the
// scope ends). (2) When a destructor destroys one of the fields of
// a class. For instance: 'class Foo { MyClass b; }': In addition
// to executing its body, Foo::~Foo calls MyClass::~Myclass on b.
// Note we only call this if an actual destructor is being executed:
// we don't call it when an int goes out of scope!
//
// HandleFunctionCall: A convenience callback that 'bundles'
// the following Expr's, each of which causes one or more
// function calls when evaluated (though most of them are
// not a child of CallExpr):
// * CallExpr (obviously)
// * CXXMemberCallExpr
// * CXXOperatorCallExpr -- a call to operatorXX()
// * CXXConstructExpr -- calls a constructor to create an object,
// and maybe a destructor when the object goes out of scope.
// * CXXTemporaryObjectExpr -- subclass of CXXConstructExpr
// * CXXNewExpr -- calls operator new and a constructor
// * CXXDeleteExpr -- calls operator delete and a destructor
// * DeclRefExpr -- if the declref is a function pointer, we
// treat it as a function call, since it can act like one
// in the future
// * ImplicitDestructorCall -- calls a destructor
// Each of these calls HandleFunctionCall for the function calls
// it does. A subclass interested only in function calls, and
// not exactly what expression caused them, can override
// HandleFunctionCall. Note: subclasses should expect that
// the first argument to HandleFunctionCall may be nullptr (e.g. when
// constructing a built-in type), in which case the handler should
// immediately return.
// If the function being called is a member of a class, parent_type
// is the type of the method's owner (parent), as it is written in
// the source. (We need the type-as-written so we can distinguish
// explicitly-written template args from default template args.) We
// also pass in the CallExpr (or CXXConstructExpr, etc). This may
// be nullptr if the function call is implicit.
bool HandleFunctionCall(clang::FunctionDecl* callee,
const clang::Type* parent_type,
const clang::Expr* calling_expr) {
if (!callee)
return true;
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("FunctionCall")
<< PrintablePtr(callee) << PrintableDecl(callee) << "\n";
}
return true;
}
bool TraverseImplicitDestructorCall(clang::CXXDestructorDecl* decl,
const Type* type_being_destroyed) {
if (CanIgnoreCurrentASTNode())
return true;
if (!decl)
return true;
if (ShouldPrintSymbolFromCurrentFile()) {
errs() << AnnotatedName("Destruction")
<< PrintableType(type_being_destroyed) << "\n";
}
return this->getDerived().HandleFunctionCall(decl, type_being_destroyed,
static_cast<Expr*>(nullptr));
}
bool TraverseCallExpr(clang::CallExpr* expr) {
if (!Base::TraverseCallExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
TypeOfParentIfMethod(expr),
expr);
}
bool TraverseCXXMemberCallExpr(clang::CXXMemberCallExpr* expr) {
if (!Base::TraverseCXXMemberCallExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
TypeOfParentIfMethod(expr),
expr);
}
bool TraverseCXXOperatorCallExpr(clang::CXXOperatorCallExpr* expr) {
if (!Base::TraverseCXXOperatorCallExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
const Type* parent_type = TypeOfParentIfMethod(expr);
// If we're a free function -- bool operator==(MyClass a, MyClass b) --
// we still want to have a parent_type, as if we were defined as
// MyClass::operator==. So we go through the arguments and take the
// first one that's a class, and associate the function with that.
if (!parent_type) {
if (const Expr* first_argument = GetFirstClassArgument(expr))
parent_type = GetTypeOf(first_argument);
}
return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
parent_type, expr);
}
bool TraverseCXXConstructExpr(clang::CXXConstructExpr* expr) {
if (!Base::TraverseCXXConstructExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
if (!this->getDerived().HandleFunctionCall(expr->getConstructor(),
GetTypeOf(expr),
expr))
return false;
// When creating a local variable or a temporary, but not a pointer, the
// constructor is also responsible for destruction (which happens
// implicitly when the variable goes out of scope). Only when initializing
// a field of a class does the constructor not have to worry
// about destruction. It turns out it's easier to check for that.
bool will_call_implicit_destructor_on_leaving_scope =
!IsCXXConstructExprInInitializer(current_ast_node()) &&
!IsCXXConstructExprInNewExpr(current_ast_node());
if (will_call_implicit_destructor_on_leaving_scope) {
if (const CXXDestructorDecl* dtor_decl = GetSiblingDestructorFor(expr)) {
if (!this->getDerived().TraverseImplicitDestructorCall(
const_cast<CXXDestructorDecl*>(dtor_decl), GetTypeOf(expr)))
return false;
}
}
return true;
}
bool TraverseCXXTemporaryObjectExpr(clang::CXXTemporaryObjectExpr* expr) {
if (!Base::TraverseCXXTemporaryObjectExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
// In this case, we *know* we're responsible for destruction as well.
CXXConstructorDecl* ctor_decl = expr->getConstructor();
CXXDestructorDecl* dtor_decl =
const_cast<CXXDestructorDecl*>(GetSiblingDestructorFor(expr));
const Type* type = GetTypeOf(expr);
return (this->getDerived().HandleFunctionCall(ctor_decl, type, expr) &&
this->getDerived().HandleFunctionCall(dtor_decl, type, expr));
}
bool TraverseCXXNewExpr(clang::CXXNewExpr* expr) {
if (!Base::TraverseCXXNewExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
const Type* parent_type = expr->getAllocatedType().getTypePtrOrNull();
// 'new' calls operator new in addition to the ctor of the new-ed type.
if (FunctionDecl* operator_new = expr->getOperatorNew()) {
// If operator new is a method, it must (by the semantics of
// per-class operator new) be a method on the class we're newing.
const Type* op_parent = nullptr;
if (isa<CXXMethodDecl>(operator_new))
op_parent = parent_type;
if (!this->getDerived().HandleFunctionCall(operator_new, op_parent, expr))
return false;
}
return true;
}
bool TraverseCXXDeleteExpr(clang::CXXDeleteExpr* expr) {
if (!Base::TraverseCXXDeleteExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
const Type* parent_type = expr->getDestroyedType().getTypePtrOrNull();
// We call operator delete in addition to the dtor of the deleted type.
if (FunctionDecl* operator_delete = expr->getOperatorDelete()) {
// If operator delete is a method, it must (by the semantics of per-
// class operator delete) be a method on the class we're deleting.
const Type* op_parent = nullptr;
if (isa<CXXMethodDecl>(operator_delete))
op_parent = parent_type;
if (!this->getDerived().HandleFunctionCall(operator_delete, op_parent,
expr))
return false;
}
const CXXDestructorDecl* dtor = GetDestructorForDeleteExpr(expr);
return this->getDerived().HandleFunctionCall(
const_cast<CXXDestructorDecl*>(dtor), parent_type, expr);
}
// This is to catch function pointers to templates.
// For instance, 'MyFunctionPtr p = &TplFn<MyClass*>;': we need to
// expand TplFn to see if it needs full type info for MyClass.
bool TraverseDeclRefExpr(clang::DeclRefExpr* expr) {
if (!Base::TraverseDeclRefExpr(expr))
return false;
if (CanIgnoreCurrentASTNode())
return true;
if (FunctionDecl* fn_decl = DynCastFrom(expr->getDecl())) {
// If fn_decl has a class-name before it -- 'MyClass::method' --
// it's a method pointer.
const Type* parent_type = nullptr;
if (expr->getQualifier() && expr->getQualifier()->getAsType())
parent_type = expr->getQualifier()->getAsType();
if (!this->getDerived().HandleFunctionCall(fn_decl, parent_type, expr))
return false;
}
return true;
}
/// Return whether this visitor should recurse into implicit
/// code, e.g., implicit constructors and destructors.
bool shouldVisitImplicitCode() const {
return true;
}
protected:
CompilerInstance* compiler() {
return compiler_;
}
private:
template <typename T> friend class BaseAstVisitor;
CompilerInstance* const compiler_;
// The currently active decl/stmt/type/etc -- that is, the node
// being currently visited in a Visit*() or Traverse*() method. The
// advantage of ASTNode over the object passed in to Visit*() and
// Traverse*() is ASTNode knows its parent.
ASTNode* current_ast_node_;
};
// ----------------------------------------------------------------------
// --- AstTreeFlattenerVisitor
// ----------------------------------------------------------------------
//
// This simple visitor just creates a set of all AST nodes (stored as
// void*'s) seen while traversing via BaseAstVisitor.
class AstFlattenerVisitor : public BaseAstVisitor<AstFlattenerVisitor> {
public:
typedef BaseAstVisitor<AstFlattenerVisitor> Base;
// We divide our set of nodes into category by type. For most AST
// nodes, we can store just a pointer to the node. However, for
// some AST nodes we don't get a pointer into the AST, we get a
// temporary (stack-allocated) object, and have to store the full
// object ourselves and use its operator== to test for equality.
// These types each get their own set (or, usually, vector, since
// the objects tend not to support operator< or hash<>()).
class NodeSet {
public:
// We could add more versions, but these are the only useful ones so far.
bool Contains(const Type* type) const {
return ContainsKey(others, type);
}
bool Contains(const Decl* decl) const {
return ContainsKey(others, decl);
}
bool Contains(const ASTNode& node) const {
if (const TypeLoc* tl = node.GetAs<TypeLoc>()) {
return ContainsValue(typelocs, *tl);
} else if (const NestedNameSpecifierLoc* nl =
node.GetAs<NestedNameSpecifierLoc>()) {
return ContainsValue(nnslocs, *nl);
} else if (const TemplateName* tn = node.GetAs<TemplateName>()) {
// The best we can do is to compare the associated decl
if (tn->getAsTemplateDecl() == nullptr)
return false; // be conservative if we can't compare decls
for (const TemplateName& tpl_name : tpl_names) {
if (tpl_name.getAsTemplateDecl() == tn->getAsTemplateDecl())
return true;
}
return false;
} else if (const TemplateArgument* ta = node.GetAs<TemplateArgument>()) {
// TODO(csilvers): figure out how to compare template arguments
(void)ta;
return false;
} else if (const TemplateArgumentLoc* tal =
node.GetAs<TemplateArgumentLoc>()) {
// TODO(csilvers): figure out how to compare template argument-locs
(void)tal;
return false;
} else {
return ContainsKey(others, node.GetAs<void>());
}
}
void AddAll(const NodeSet& that) {
Extend(&typelocs, that.typelocs);
Extend(&nnslocs, that.nnslocs);
Extend(&tpl_names, that.tpl_names);
Extend(&tpl_args, that.tpl_args);
Extend(&tpl_arglocs, that.tpl_arglocs);
InsertAllInto(that.others, &others);
}
// Needed since we're treated like an stl-like object.
bool empty() const {
return (typelocs.empty() && nnslocs.empty() &&
tpl_names.empty() && tpl_args.empty() &&
tpl_arglocs.empty() && others.empty());
}
void clear() {
typelocs.clear();
nnslocs.clear();
tpl_names.clear();
tpl_args.clear();
tpl_arglocs.clear();
others.clear();
}
private:
friend class AstFlattenerVisitor;
// It's ok not to check for duplicates; we're just traversing the tree.
void Add(TypeLoc tl) { typelocs.push_back(tl); }
void Add(NestedNameSpecifierLoc nl) { nnslocs.push_back(nl); }
void Add(TemplateName tn) { tpl_names.push_back(tn); }
void Add(TemplateArgument ta) { tpl_args.push_back(ta); }
void Add(TemplateArgumentLoc tal) { tpl_arglocs.push_back(tal); }
void Add(const void* o) { others.insert(o); }
vector<TypeLoc> typelocs;
vector<NestedNameSpecifierLoc> nnslocs;
vector<TemplateName> tpl_names;
vector<TemplateArgument> tpl_args;
vector<TemplateArgumentLoc> tpl_arglocs;
set<const void*> others;
};
//------------------------------------------------------------
// Public interface:
explicit AstFlattenerVisitor(CompilerInstance* compiler) : Base(compiler) { }
const NodeSet& GetNodesBelow(Decl* decl) {
CHECK_(seen_nodes_.empty() && "Nodes should be clear before GetNodesBelow");
NodeSet* node_set = &nodeset_decl_cache_[decl];
if (node_set->empty()) {
TraverseDecl(decl);
swap(*node_set, seen_nodes_); // move the seen_nodes_ into the cache
}
return *node_set; // returns the cache entry
}
//------------------------------------------------------------
// Pure virtual methods that the base class requires.
bool CanIgnoreCurrentASTNode() const override {
return false;
}
bool ShouldPrintSymbolFromCurrentFile() const override {
return false;
}
string GetSymbolAnnotation() const override {
return "[Uninstantiated template AST-node] ";
}
//------------------------------------------------------------
// Top-level handlers that construct the tree.
bool VisitDecl(Decl*) {
AddCurrentAstNodeAsPointer();
return true;
}
bool VisitStmt(Stmt*) {
AddCurrentAstNodeAsPointer();
return true;
}
bool VisitType(Type*) {
AddCurrentAstNodeAsPointer();
return true;
}
bool VisitTypeLoc(TypeLoc typeloc) {
VERRS(7) << GetSymbolAnnotation() << PrintableTypeLoc(typeloc) << "\n";
seen_nodes_.Add(typeloc);
return true;
}
bool VisitNestedNameSpecifier(NestedNameSpecifier*) {
AddCurrentAstNodeAsPointer();
return true;
}
bool VisitTemplateName(TemplateName tpl_name) {
VERRS(7) << GetSymbolAnnotation()
<< PrintableTemplateName(tpl_name) << "\n";
seen_nodes_.Add(tpl_name);
return true;
}
bool VisitTemplateArgument(const TemplateArgument& tpl_arg) {
VERRS(7) << GetSymbolAnnotation()
<< PrintableTemplateArgument(tpl_arg) << "\n";