Debian Codegraph @

clang_delta/RemoveUnusedFunction.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "RemoveUnusedFunction.h"
16
17 #include <cctype>
18 #include <algorithm>
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/AST/Attr.h"
23
24 #include "TransformationManager.h"
25
26 using namespace clang;
27
28 static const char *DescriptionMsg =
29 "Remove unused function declarations. \n";
30
31 static RegisterTransformation<RemoveUnusedFunction>
32 Trans("remove-unused-function", DescriptionMsg);
33
34 class RUFAnalysisVisitor : public RecursiveASTVisitor<RUFAnalysisVisitor> {
35 public:
36
37 explicit RUFAnalysisVisitor(RemoveUnusedFunction *Instance)
38 : ConsumerInstance(Instance)
39 { }
40
41 bool VisitFunctionDecl(FunctionDecl *FD);
42
43 private:
44
45 RemoveUnusedFunction *ConsumerInstance;
46 };
47
48 typedef llvm::DenseMap<const clang::UsingDecl *,
49 const clang::FunctionDecl *>
50 UsingFunctionDeclsMap;
51
52 typedef llvm::SmallPtrSet<const clang::FunctionDecl *, 32>
53 FunctionDeclsSet;
54
55 typedef llvm::SmallPtrSet<const clang::FunctionDecl *, 5>
56 MemberSpecializationSet;
57
58 namespace {
59
60 class UsingDeclVisitor : public
61 RecursiveASTVisitor<UsingDeclVisitor> {
62 public:
63 UsingDeclVisitor(const FunctionDecl *FD,
64 RemoveUnusedFunction *Instance)
65 : CurrentFD(FD),
66 ConsumerInstance(Instance)
67 { }
68
69 bool VisitUsingDecl(UsingDecl *D);
70
71 private:
72 const FunctionDecl *CurrentFD;
73
74 RemoveUnusedFunction *ConsumerInstance;
75 };
76
77 bool UsingDeclVisitor::VisitUsingDecl(UsingDecl *D)
78 {
79 ConsumerInstance->handleOneUsingDecl(CurrentFD, D);
80 return true;
81 }
82 // end of UsingDeclVisitor
83
84 class SpecializationVisitor : public
85 RecursiveASTVisitor<SpecializationVisitor> {
86 public:
87 explicit SpecializationVisitor(RemoveUnusedFunction *Instance)
88 : ConsumerInstance(Instance)
89 { }
90
91 bool VisitFunctionDecl(FunctionDecl *FD);
92
93 bool VisitMemberExpr(MemberExpr *E);
94
95 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
96
97 bool VisitCallExpr(CallExpr *E);
98
99 bool shouldVisitTemplateInstantiations() {
100 return true;
101 }
102
103 private:
104
105 RemoveUnusedFunction *ConsumerInstance;
106 };
107
108 bool SpecializationVisitor::VisitFunctionDecl(FunctionDecl *FD)
109 {
110 ConsumerInstance->handleOneFunctionDecl(FD);
111 return true;
112 }
113
114 bool SpecializationVisitor::VisitMemberExpr(MemberExpr *E)
115 {
116 ConsumerInstance->handleOneMemberExpr(E);
117 return true;
118 }
119
120 bool SpecializationVisitor::VisitCXXOperatorCallExpr(
121 CXXOperatorCallExpr *E)
122 {
123 // ConsumerInstance->handleOneCXXOperatorCallExpr(E);
124 return true;
125 }
126
127 bool SpecializationVisitor::VisitCallExpr(
128 CallExpr *E)
129 {
130 ConsumerInstance->handleOneCallExpr(E);
131 return true;
132 }
133
134
135 // end of SpecializationVisitor
136
137 class ReferencedFunctionDeclVisitor : public
138 RecursiveASTVisitor<ReferencedFunctionDeclVisitor> {
139 public:
140 ReferencedFunctionDeclVisitor(const FunctionDecl *FD,
141 RemoveUnusedFunction *Instance)
142 : CurrentFD(FD),
143 ConsumerInstance(Instance)
144 { }
145
146 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
147
148 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
149
150 private:
151 const FunctionDecl *CurrentFD;
152
153 RemoveUnusedFunction *ConsumerInstance;
154 };
155
156 bool ReferencedFunctionDeclVisitor::VisitUnresolvedLookupExpr(
157 UnresolvedLookupExpr *E)
158 {
159 ConsumerInstance->handleOneUnresolvedLookupExpr(CurrentFD, E);
160 return true;
161 }
162
163 bool ReferencedFunctionDeclVisitor::VisitCXXDependentScopeMemberExpr(
164 CXXDependentScopeMemberExpr *E)
165 {
166 ConsumerInstance->handleOneCXXDependentScopeMemberExpr(CurrentFD, E);
167 return true;
168 }
169
170 } // end of anon namespace
171
172 class ExtraReferenceVisitorWrapper : public
173 RecursiveASTVisitor<ExtraReferenceVisitorWrapper> {
174 public:
175 explicit ExtraReferenceVisitorWrapper(RemoveUnusedFunction *Instance)
176 : ConsumerInstance(Instance)
177 { }
178
179 bool VisitFunctionDecl(FunctionDecl *FD);
180
181 private:
182
183 RemoveUnusedFunction *ConsumerInstance;
184 };
185
186 bool ExtraReferenceVisitorWrapper::VisitFunctionDecl(FunctionDecl *FD)
187 {
188 if (!FD->isThisDeclarationADefinition())
189 return true;
190 UsingDeclVisitor Visitor(FD, ConsumerInstance);
191 Visitor.TraverseDecl(FD);
192 ReferencedFunctionDeclVisitor FuncVisitor(FD, ConsumerInstance);
193 FuncVisitor.TraverseDecl(FD);
194 ConsumerInstance->setInlinedSystemFunctions(FD);
195 return true;
196 }
197
198 bool RUFAnalysisVisitor::VisitFunctionDecl(FunctionDecl *FD)
199 {
200 if (ConsumerInstance->isInIncludedFile(FD))
201 return true;
202 const FunctionDecl *CanonicalFD = FD->getCanonicalDecl();
203 if (ConsumerInstance->VisitedFDs.count(CanonicalFD))
204 return true;
205 ConsumerInstance->VisitedFDs.insert(CanonicalFD);
206
207 FunctionDecl::TemplatedKind TK = FD->getTemplatedKind();
208 if (TK == FunctionDecl::TK_MemberSpecialization) {
209 const FunctionDecl *Member = FD->getInstantiatedFromMemberFunction();
210 ConsumerInstance->addOneMemberSpecialization(FD, Member);
211 return true;
212 }
213 else if (TK == FunctionDecl::TK_DependentFunctionTemplateSpecialization) {
214 const DependentFunctionTemplateSpecializationInfo *Info =
215 FD->getDependentSpecializationInfo();
216 // don't need to track all specs, just associate FD with one
217 // of those
218 const FunctionDecl *Member = nullptr;
219
220 #if LLVM_VERSION_MAJOR >= 18
221 ArrayRef<FunctionTemplateDecl *> members = Info->getCandidates();
222 if (!members.empty()) {
223 Member = members[0]->getTemplatedDecl();
224 }
225 #else
226 if (Info->getNumTemplates() > 0) {
227 Member =
228 Info->getTemplate(0)->getTemplatedDecl();
229 }
230 #endif
231
232 if (Member != nullptr)
233 ConsumerInstance->addOneMemberSpecialization(FD, Member);
234
235 return true;
236 }
237
238 TemplateSpecializationKind K = FD->getTemplateSpecializationKind();
239 if (K == TSK_ExplicitSpecialization) {
240 ConsumerInstance->addFuncToExplicitSpecs(FD);
241 return true;
242 }
243 // Why implicit instantiation would appear here? e.g.:
244 // template<typename T> void foo(T &);
245 // struct S { friend void foo<>(bool&); };
246 // OK, just add it into MemberSpec set.
247 if (K == TSK_ImplicitInstantiation) {
248 const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
249 TransAssert(FTD && "NULL FunctionTemplateDecl!");
250 const FunctionDecl *Member = FTD->getTemplatedDecl();
251 ConsumerInstance->addOneMemberSpecialization(FD, Member);
252 return true;
253 }
254
255 if (FD->isReferenced() ||
256 FD->isMain() ||
257 FD->hasAttr<OpenCLKernelAttr>() ||
258 ConsumerInstance->hasReferencedSpecialization(CanonicalFD) ||
259 ConsumerInstance->isInlinedSystemFunction(CanonicalFD) ||
260 ConsumerInstance->isInReferencedSet(CanonicalFD) ||
261 !ConsumerInstance->hasAtLeastOneValidLocation(CanonicalFD))
262 return true;
263
264 ConsumerInstance->addOneFunctionDecl(CanonicalFD);
265 return true;
266 }
267
268 void RemoveUnusedFunction::Initialize(ASTContext &context)
269 {
270 Transformation::Initialize(context);
271 AnalysisVisitor = new RUFAnalysisVisitor(this);
272 VisitorWrapper = new ExtraReferenceVisitorWrapper(this);
273 initializeInlinedSystemFunctions();
274 }
275
276 void RemoveUnusedFunction::HandleTranslationUnit(ASTContext &Ctx)
277 {
278 VisitorWrapper->TraverseDecl(Ctx.getTranslationUnitDecl());
279 // visit using decls declared outsided function-scope
280 UsingDeclVisitor Visitor(NULL, this);
281 Visitor.TraverseDecl(Ctx.getTranslationUnitDecl());
282 SpecializationVisitor SpecVisitor(this);
283 SpecVisitor.TraverseDecl(Ctx.getTranslationUnitDecl());
284 AnalysisVisitor->TraverseDecl(Ctx.getTranslationUnitDecl());
285
286 if (QueryInstanceOnly)
287 return;
288
289 if (TransformationCounter > ValidInstanceNum) {
290 TransError = TransMaxInstanceError;
291 return;
292 }
293 if (ToCounter > ValidInstanceNum) {
294 TransError = TransToCounterTooBigError;
295 return;
296 }
297
298 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
299
300 doRewriting();
301
302 if (Ctx.getDiagnostics().hasErrorOccurred() ||
303 Ctx.getDiagnostics().hasFatalErrorOccurred())
304 TransError = TransInternalError;
305 }
306
307 // Each "key" function is inlined into the corresponding "value"
308 // function, and its isReferenced flag is false...
309 void RemoveUnusedFunction::initializeInlinedSystemFunctions()
310 {
311 InlinedSystemFunctions["__fprintf_chk"] = "fprintf";
312 InlinedSystemFunctions["__printf_chk"] = "printf";
313 InlinedSystemFunctions["__dprintf_chk"] = "dprintf";
314 InlinedSystemFunctions["__asprintf_chk"] = "asprintf";
315 InlinedSystemFunctions["__obstack_printf_chk"] = "obstack_printf";
316 InlinedSystemFunctions["__swprintf_chk"] = "swprintf";
317 InlinedSystemFunctions["__swprintf_alias"] = "swprintf";
318 InlinedSystemFunctions["__fwprintf_chk"] = "fwprintf";
319 InlinedSystemFunctions["__wprintf_chk"] = "wprintf";
320 }
321
322 void RemoveUnusedFunction::doRewriting()
323 {
324 if (ToCounter <= 0) {
325 TransAssert(TheFunctionDecl && "NULL TheFunctionDecl!");
326 // add FD under removal first in order to avoid recursion, e.g.
327 // void foo() { using ::foo; }
328 RemovedFDs.insert(TheFunctionDecl);
329 removeOneFunctionDeclGroup(TheFunctionDecl);
330 return;
331 }
332
333 TransAssert((TransformationCounter <=
334 static_cast<int>(AllValidFunctionDecls.size())) &&
335 "TransformationCounter is larger than the number of defs!");
336 TransAssert((ToCounter <= static_cast<int>(AllValidFunctionDecls.size())) &&
337 "ToCounter is larger than the number of defs!");
338 for (int I = ToCounter; I >= TransformationCounter; --I) {
339 TransAssert((I >= 1) && "Invalid Index!");
340 const FunctionDecl *FD = AllValidFunctionDecls[I-1];
341 TransAssert(FD && "NULL FunctionDecl!");
342 RemovedFDs.insert(FD);
343 removeOneFunctionDeclGroup(FD);
344 }
345 }
346
347 SourceLocation RemoveUnusedFunction::getExtensionLocStart(
348 SourceLocation Loc)
349 {
350 SourceLocation StartLoc = Loc;
351 FileID FID = SrcManager->getMainFileID();
352 SourceLocation FileStartLoc = SrcManager->getLocForStartOfFile(FID);
353 const char * const FileStartBuf = SrcManager->getCharacterData(FileStartLoc);
354 const char *StartBuf = SrcManager->getCharacterData(StartLoc);
355 const char *MatchedPos = NULL;
356 bool Out = false;
357 std::string Ext = "__noisnetxe__";
358 while (true) {
359 do {
360 StartBuf--;
361 if (StartBuf < FileStartBuf)
362 break;
363 } while (isspace(*StartBuf));
364
365 int Len = static_cast<int>(Ext.length());
366 for (int I = 0; I < Len; I++) {
367 if (StartBuf < FileStartBuf || *StartBuf != Ext[I]) {
368 Out = true;
369 break;
370 }
371 StartBuf--;
372 }
373 if (Out)
374 break;
375 StartBuf++;
376 MatchedPos = StartBuf;
377 }
378 // no __extension__ in front
379 if (MatchedPos == NULL)
380 return Loc;
381
382 TransAssert((MatchedPos >= FileStartBuf) && "Invalid MatchedPos!");
383 std::string ExtStr(MatchedPos, Ext.length());
384 TransAssert((ExtStr == "__extension__") && "Invalid ExtStr!"); (void)ExtStr;
385 int Offset = MatchedPos - (SrcManager->getCharacterData(StartLoc));
386 return StartLoc.getLocWithOffset(Offset);
387 }
388
389 bool RemoveUnusedFunction::hasValidOuterLocStart(
390 const FunctionTemplateDecl *FTD, const FunctionDecl *FD)
391 {
392 SourceLocation FTDLocStart = FTD->getSourceRange().getBegin();
393 SourceLocation FDLocStart = FD->getSourceRange().getBegin();
394 const char *FTDStartPos = SrcManager->getCharacterData(FTDLocStart);
395 const char *FDStartPos = SrcManager->getCharacterData(FDLocStart);
396 return (FTDStartPos < FDStartPos);
397 }
398
399 SourceLocation RemoveUnusedFunction::getFunctionOuterLocStart(
400 const FunctionDecl *FD)
401 {
402 SourceLocation LocStart = FD->getBeginLoc();
403 bool RecordLoc = false;
404
405 // check if FD is from a function template
406 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
407 // get FTD->getBeginLoc() only if it is less than FD->getBeginLoc,
408 // for example, in the code below:
409 // template <typename T> struct S {template <typename T1> void foo();};
410 // template<typename T> template<typename T1> void S<T>::foo() { }
411 // where
412 // FTD->getBeginLoc() points to the begining of "template<typename T1>"
413 if (hasValidOuterLocStart(FTD, FD)) {
414 LocStart = FTD->getBeginLoc();
415 RecordLoc = true;
416 }
417 }
418
419 if (LocStart.isMacroID())
420 LocStart = SrcManager->getExpansionLoc(LocStart);
421
422 // this is ugly, but how do we get the location of __extension__? e.g.:
423 // __extension__ void foo();
424 LocStart = getExtensionLocStart(LocStart);
425
426 // In some cases where the given input is not well-formed, we may
427 // end up with duplicate locations for the FunctionTemplateDecl
428 // case. In such cases, we simply return an invalid SourceLocation,
429 // which will ben skipped by the caller of getFunctionOuterLocStart.
430 if (RecordLoc) {
431 if (VisitedLocations.count(LocStart))
432 return SourceLocation();
433 VisitedLocations.insert(LocStart);
434 }
435
436 return LocStart;
437 }
438
439 bool RemoveUnusedFunction::isTokenOperator(SourceLocation Loc)
440 {
441 const char * Buf = SrcManager->getCharacterData(Loc);
442 std::string OStr = "operator";
443 std::string S(Buf, OStr.length());
444 return (S == OStr);
445 }
446
447 // this is ugly, but seems clang gives "bad" location for the code below:
448 // template<typename T> void foo(T *);
449 // template <typename T> struct S {
450 // template<typename T1> friend void foo(T1 *);
451 // ^ FD.end_loc points here
452 // };
453 // template struct S<char>;
454 SourceLocation RemoveUnusedFunction::getFunctionLocEnd(
455 SourceLocation LocStart,
456 SourceLocation LocEnd,
457 const FunctionDecl *FD)
458 {
459 if (!FD->getDescribedFunctionTemplate()) {
460 // Remove trailing ; if function has no body
461 if (!FD->hasBody()) {
462 return RewriteHelper->getLocationUntil(LocEnd, ';');
463 }
464 else {
465 return LocEnd;
466 }
467 }
468
469 SourceLocation FDLoc = FD->getLocation();
470 if (FDLoc.isMacroID())
471 FDLoc = SrcManager->getExpansionLoc(FDLoc);
472 const char * const FDBuf = SrcManager->getCharacterData(FDLoc);
473 const char * LocEndBuf = SrcManager->getCharacterData(LocEnd);
474 if ((FDBuf < LocEndBuf) && !isTokenOperator(FDLoc) &&
475 !FD->isDeleted() && !FD->isDefaulted())
476 return LocEnd;
477 int Offset = 0;
478 while (*LocEndBuf != ';') {
479 LocEndBuf++;
480 Offset++;
481 }
482 return LocEnd.getLocWithOffset(Offset-1);
483 }
484
485 void RemoveUnusedFunction::removeOneFunctionDecl(const FunctionDecl *FD)
486 {
487 SourceRange FuncRange = FD->getSourceRange();
488 SourceLocation LocEnd = FuncRange.getEnd();
489 if (LocEnd.isMacroID())
490 LocEnd = SrcManager->getExpansionLoc(LocEnd);
491 if (!FD->isInExternCContext() && !FD->isInExternCXXContext()) {
492 SourceLocation FuncLocStart = getFunctionOuterLocStart(FD);
493
494 if (FuncLocStart.isInvalid())
495 return;
496 // This is a workaround to cases where we have function declaration
497 // groups, e.g.
498 // void *foo(), bar();
499 // It's very tricky to remove a single decl in such a case.
500 // Let's just remove all decls for now. To avoid removing text that
501 // has been removed, we keep track the start loc for each group so that
502 // we only remove each group once.
503 if (!FD->hasBody()) {
504 if (FDGroupLocations.count(FuncLocStart)) {
505 return;
506 } else {
507 FDGroupLocations.insert(FuncLocStart);
508 }
509 }
510
511 LocEnd = getFunctionLocEnd(FuncLocStart, LocEnd, FD);
512 if (SrcManager->isWrittenInMainFile(FuncLocStart) &&
513 SrcManager->isWrittenInMainFile(LocEnd))
514 TheRewriter.RemoveText(SourceRange(FuncLocStart, LocEnd));
515 return;
516 }
517
518 const DeclContext *Ctx = FD->getLookupParent();
519 const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(Ctx);
520 if (!Linkage) {
521 SourceLocation FuncLocStart = getFunctionOuterLocStart(FD);
522 if (FuncLocStart.isInvalid())
523 return;
524 LocEnd = getFunctionLocEnd(FuncLocStart, LocEnd, FD);
525 TheRewriter.RemoveText(SourceRange(FuncLocStart, LocEnd));
526 return;
527 }
528 // cases like:
529 // extern "C++" { void foo(); }
530 // namespace { using ::foo; }
531 if (Linkage->hasBraces()) {
532 SourceLocation FuncLocStart = getFunctionOuterLocStart(FD);
533 if (FuncLocStart.isInvalid())
534 return;
535 TheRewriter.RemoveText(SourceRange(FuncLocStart, LocEnd));
536 return;
537 }
538 // cases like:
539 // extern "C++" void foo();
540 // it also handles cases such as extern "C++" template<typename T> ...
541 SourceLocation LocStart = Linkage->getExternLoc();
542 if (LocStart.isMacroID())
543 LocStart = SrcManager->getExpansionLoc(LocStart);
544 LocStart = getExtensionLocStart(LocStart);
545 TheRewriter.RemoveText(SourceRange(LocStart, LocEnd));
546 }
547
548 void RemoveUnusedFunction::removeOneExplicitInstantiation(
549 const FunctionDecl *Spec)
550 {
551 FileID FID = SrcManager->getMainFileID();
552 SourceLocation FileStartLoc = SrcManager->getLocForStartOfFile(FID);
553 const char * const FileStartBuf = SrcManager->getCharacterData(FileStartLoc);
554
555 SourceLocation Loc = Spec->getPointOfInstantiation();
556 if (Loc.isInvalid()) {
557 TheRewriter.RemoveText(Spec->getSourceRange());
558 return;
559 }
560 const char *OrigStartBuf = SrcManager->getCharacterData(Loc);
561 const char *StartBuf = OrigStartBuf;
562 int Offset = 0;
563 while ((*StartBuf != ';') && (*StartBuf != '{') && (*StartBuf != '}') &&
564 (StartBuf >= FileStartBuf)) {
565 StartBuf--;
566 Offset--;
567 }
568 SourceLocation LocStart = Loc.getLocWithOffset(Offset + 1);
569 Offset = 0;
570 StartBuf = OrigStartBuf;
571 while (*StartBuf != ';') {
572 StartBuf++;
573 Offset++;
574 }
575 SourceLocation LocEnd = Loc.getLocWithOffset(Offset - 1);
576 TheRewriter.RemoveText(SourceRange(LocStart, LocEnd));
577 }
578
579 void RemoveUnusedFunction::removeRemainingExplicitSpecs(
580 MemberSpecializationSet *ExplicitSpecs)
581 {
582 if (!ExplicitSpecs)
583 return;
584 for (MemberSpecializationSet::iterator I = ExplicitSpecs->begin(),
585 E = ExplicitSpecs->end(); I != E; ++I) {
586 removeOneFunctionDecl(*I);
587 }
588 }
589
590 // We can't handle function template explicit instantiation because
591 // I am not sure how to analyze its source location.
592 // For example, in the code below:
593 // template<typename T> bool foo(const int&) {return true;}
594 // template bool foo<char>(const int&);
595 // ^ point of instantiation
596 // What I could get is the point of the instantiation, but I
597 // don't know the source range for the entire instantiation declaration.
598 void RemoveUnusedFunction::removeFunctionExplicitInstantiations(
599 const FunctionDecl *FD)
600 {
601 const FunctionTemplateDecl *FTD = getTopDescribedTemplate(FD);
602 if (!FTD)
603 return;
604
605 const FunctionDecl *CanonicalFD = FD->getCanonicalDecl();
606 MemberSpecializationSet *S = MemberToInstantiations[CanonicalFD];
607 MemberSpecializationSet *ExplicitSpecs =
608 FuncToExplicitSpecs[CanonicalFD];
609
610 for (FunctionTemplateDecl::spec_iterator I = FTD->spec_begin(),
611 E = FTD->spec_end(); I != E; ++I) {
612 FunctionDecl *Spec = (*I);
613 TemplateSpecializationKind K = Spec->getTemplateSpecializationKind();
614 if (K == TSK_ExplicitSpecialization) {
615 // check if the explicit spec points to any dependent specs,
616 // skip it if yes
617 if (!ExplicitSpecs) {
618 removeOneFunctionDecl(Spec);
619 }
620 else if (ExplicitSpecs->count(Spec)) {
621 removeOneFunctionDecl(Spec);
622 ExplicitSpecs->erase(Spec);
623 }
624 continue;
625 }
626 if (K != TSK_ExplicitInstantiationDeclaration &&
627 K != TSK_ExplicitInstantiationDefinition)
628 continue;
629 TransAssert(!Spec->isReferenced() && "Referenced Instantiation!");
630 removeOneExplicitInstantiation(Spec);
631 if (S && S->count(Spec)) {
632 S->erase(Spec);
633 }
634 }
635
636 removeRemainingExplicitSpecs(ExplicitSpecs);
637
638 if (!S)
639 return;
640 for (MemberSpecializationSet::iterator I = S->begin(), E = S->end();
641 I != E; ++I) {
642 const FunctionDecl *Spec = (*I);
643 TemplateSpecializationKind K = Spec->getTemplateSpecializationKind();
644 TransAssert(((K == TSK_ExplicitInstantiationDeclaration) ||
645 (K == TSK_ExplicitInstantiationDefinition)) &&
646 "Bad Instantiation!"); (void)K;
647 removeOneExplicitInstantiation(Spec);
648 }
649 }
650
651 void RemoveUnusedFunction::removeMemberSpecializations(const FunctionDecl *FD)
652 {
653 MemberSpecializationSet *S = MemberToSpecs[FD->getCanonicalDecl()];
654 if (!S)
655 return;
656 for (MemberSpecializationSet::iterator I = S->begin(), E = S->end();
657 I != E; ++I) {
658 const FunctionDecl *Spec = (*I);
659 removeOneFunctionDecl(Spec);
660 }
661 }
662
663 void RemoveUnusedFunction::removeOneFunctionDeclGroup(const FunctionDecl *FD)
664 {
665 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
666 RE = FD->redecls_end(); RI != RE; ++RI) {
667 const FunctionDecl *FD = (*RI);
668 if (!FD->hasBody() && !FD->getTypeSourceInfo()) {
669 continue;
670 }
671 removeOneFunctionDecl(FD);
672 }
673
674 removeMemberSpecializations(FD);
675 removeFunctionExplicitInstantiations(FD);
676
677 for (UsingFunctionDeclsMap::const_iterator I = UsingFDs.begin(),
678 E = UsingFDs.end(); I != E; ++I) {
679 if ((*I).second != FD)
680 continue;
681 const FunctionDecl *ParentFD = UsingParentFDs[(*I).first];
682 if (ParentFD && RemovedFDs.count(ParentFD->getCanonicalDecl()))
683 continue;
684 const UsingDecl *UD = (*I).first;
685 SourceRange Range = UD->getSourceRange();
686 if (Range.getBegin().isMacroID()) {
687 TheRewriter.RemoveText(SrcManager->getExpansionRange(Range));
688 } else {
689 RewriteHelper->removeDecl((*I).first);
690 }
691 }
692 }
693
694 bool RemoveUnusedFunction::hasAtLeastOneValidLocation(const FunctionDecl *FD)
695 {
696 for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
697 RE = FD->redecls_end(); RI != RE; ++RI) {
698 SourceRange FuncRange = FD->getSourceRange();
699 SourceLocation StartLoc = FuncRange.getBegin();
700 if (StartLoc.isMacroID())
701 StartLoc = SrcManager->getExpansionLoc(StartLoc);
702 SourceLocation EndLoc = FuncRange.getEnd();
703 if (EndLoc.isMacroID())
704 EndLoc = SrcManager->getExpansionLoc(EndLoc);
705 if (SrcManager->isWrittenInMainFile(StartLoc) &&
706 SrcManager->isWrittenInMainFile(EndLoc))
707 return true;
708 }
709 return false;
710 }
711
712 bool RemoveUnusedFunction::isInReferencedSet(const FunctionDecl *CanonicalFD)
713 {
714 TransAssert(CanonicalFD && "NULL FunctionDecl!");
715 return ReferencedFDs.count(CanonicalFD);
716 }
717
718 const FunctionDecl *
719 RemoveUnusedFunction::lookupFunctionDeclShallow(const DeclarationName &DName,
720 const DeclContext *Ctx)
721 {
722 if (dyn_cast<LinkageSpecDecl>(Ctx))
723 return NULL;
724 DeclContext::lookup_result Result = Ctx->lookup(DName);
725 for (auto I = Result.begin(), E = Result.end();
726 I != E; ++I) {
727 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
728 return FD;
729 if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(*I)) {
730 const NamedDecl *ND = USD->getTargetDecl();
731 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
732 return FD;
733 }
734 if (const FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(*I)) {
735 return TD->getTemplatedDecl();
736 }
737 }
738
739 bool InNamespace = Ctx->isNamespace();
740 for (auto *I : Ctx->using_directives()) {
741 const NamespaceDecl *ND = I->getNominatedNamespace();
742 // avoid infinite recursion
743 if ((InNamespace && dyn_cast<NamespaceDecl>(Ctx) == ND) ||
744 ND->getLookupParent() == Ctx) {
745 return NULL;
746 }
747 if (const FunctionDecl *FD = lookupFunctionDeclShallow(DName, ND))
748 return FD;
749 }
750 return NULL;
751 }
752
753 const FunctionDecl *RemoveUnusedFunction::getFunctionDeclFromSpecifier(
754 const DeclarationName &Name, const NestedNameSpecifier *NNS)
755 {
756 const FunctionDecl *FD = NULL;
757 switch (NNS->getKind()) {
758 case NestedNameSpecifier::Namespace:
759 FD = lookupFunctionDeclShallow(Name,
760 NNS->getAsNamespace());
761 break;
762 case NestedNameSpecifier::NamespaceAlias:
763 FD = lookupFunctionDeclShallow(Name,
764 NNS->getAsNamespaceAlias()->getNamespace());
765 break;
766 case NestedNameSpecifier::Global:
767 FD = lookupFunctionDeclShallow(Name,
768 Context->getTranslationUnitDecl());
769 break;
770 default:
771 return NULL;
772 }
773 return FD;
774 }
775
776 void RemoveUnusedFunction::handleOneUsingDecl(const FunctionDecl *CurrentFD,
777 const UsingDecl *UD)
778 {
779 if (VisitedUsingDecls.count(UD))
780 return;
781
782 VisitedUsingDecls.insert(UD);
783 const NestedNameSpecifier *NNS = UD->getQualifier();
784 if (!NNS)
785 return;
786 DeclarationName Name = UD->getUnderlyingDecl()->getDeclName();
787 const FunctionDecl *FD = getFunctionDeclFromSpecifier(Name, NNS);
788 if (!FD || FD->isReferenced())
789 return;
790
791 // we don't put FD into ReferencedFD because we will
792 // delete both the FD and the UsingDecl if FD is only referenced
793 // by UsingDecl[s].
794 const FunctionDecl *CanonicalFD = FD->getCanonicalDecl();
795 TransAssert((UsingFDs.find(UD) == UsingFDs.end()) &&
796 "Duplicate UsingDecl to FD map!");
797 UsingFDs[UD] = CanonicalFD;
798 if (CurrentFD) {
799 TransAssert(CurrentFD->isThisDeclarationADefinition() &&
800 "CurrentFD is not a definition!");
801 TransAssert((UsingParentFDs.find(UD) == UsingParentFDs.end()) &&
802 "Duplicate UsingDecl to ParentFD map!");
803 UsingParentFDs[UD] = CurrentFD;
804 }
805 }
806
807 void RemoveUnusedFunction::handleOneCXXDependentScopeMemberExpr(
808 const FunctionDecl *CurrentFD,
809 const CXXDependentScopeMemberExpr *E)
810 {
811 if (E->isImplicitAccess())
812 return;
813 DeclarationName DName = E->getMember();
814 DeclarationName::NameKind K = DName.getNameKind();
815 if ((K != DeclarationName::CXXOperatorName) &&
816 (K != DeclarationName::Identifier))
817 return;
818 const Expr *Base = E->getBase()->IgnoreParenCasts();
819 const FunctionDecl *FD = NULL;
820 if (dyn_cast<CXXThisExpr>(Base)) {
821 TransAssert(CurrentFD && "NULL CurrentFD");
822 const DeclContext *Ctx = CurrentFD->getLookupParent();
823 TransAssert(Ctx && "Bad DeclContext!");
824 DeclContextSet VisitedCtxs;
825 FD = lookupFunctionDecl(DName, Ctx, VisitedCtxs);
826 // we may not get FD in cases where we have this->m_field
827 if (FD)
828 addOneReferencedFunction(FD);
829 return;
830 }
831 }
832
833 void RemoveUnusedFunction::handleOneUnresolvedLookupExpr(
834 const FunctionDecl *CurrentFD,
835 const UnresolvedLookupExpr *E)
836 {
837 DeclarationName DName = E->getName();
838 DeclarationName::NameKind K = DName.getNameKind();
839 if ((K != DeclarationName::CXXOperatorName) &&
840 (K != DeclarationName::Identifier))
841 return;
842 const NestedNameSpecifier *NNS = E->getQualifier();
843 // we fail only if UE is invoked with some qualifier or
844 // instantiation, e.g.:
845 // namespace NS { template<typename T> void foo(T&) { } }
846 // template<typename T> void bar(T p) { NS::foo(p); }
847 // removing foo would fail.
848 //
849 // template <typename T> void foo() { }
850 // template <typename T> void bar() { foo<T>(); }
851 // removing foo would faill, too
852 //
853 // On the other handle, the following code is ok:
854 // template<typename T> void foo(T&) { }
855 // template<typename T> void bar(T p) { foo(p); }
856 const FunctionDecl *FD = NULL;
857 if (NNS) {
858 FD = getFunctionDeclFromSpecifier(DName, NNS);
859 }
860 else {
861 const DeclContext *Ctx = CurrentFD->getLookupParent();
862 FD = lookupFunctionDeclShallow(DName, Ctx);
863 }
864
865 if (!FD || FD->isReferenced())
866 return;
867 addOneReferencedFunction(FD);
868 }
869
870 void RemoveUnusedFunction::handleOneMemberExpr(
871 const MemberExpr *ME)
872 {
873 const ValueDecl *VD = ME->getMemberDecl();
874 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
875 if (!MD)
876 return;
877 if (const FunctionDecl *FD = MD->getInstantiatedFromMemberFunction())
878 addOneReferencedFunction(FD);
879 }
880
881 const FunctionDecl *RemoveUnusedFunction::getSourceFunctionDecl(
882 const FunctionDecl *TheFD)
883 {
884 if (FunctionTemplateDecl *FTD = TheFD->getPrimaryTemplate()) {
885 if (const FunctionTemplateDecl *D =
886 FTD->getInstantiatedFromMemberTemplate())
887 return D->getTemplatedDecl();
888 else
889 return FTD->getTemplatedDecl();
890 }
891 if (const FunctionDecl *FD = TheFD->getInstantiatedFromMemberFunction())
892 return FD;
893 return TheFD;
894 }
895
896 // we can't handle cases like below:
897 // template<typename T> struct S;
898 // template<typename T> void foo(S<T>);
899 // template<> void foo(S<char>);
900 // template void foo(S<char>);
901 // the second instantiation will refer to the specialization, and thus
902 // we lose the source range of it... in fact, it points to the
903 // original template declaration.
904 void RemoveUnusedFunction::handleOneFunctionDecl(const FunctionDecl *TheFD)
905 {
906 const FunctionDecl *FD = getSourceFunctionDecl(TheFD);
907 if (TheFD->isReferenced()) {
908 addOneReferencedFunction(FD);
909 return;
910 }
911
912 FunctionDecl::TemplatedKind TK = TheFD->getTemplatedKind();
913 // Now it's another ugly part, with dependent function template spec,
914 // we lose the explicit specialization in Member's spec_iterator, e.g.:
915 // template <class T> void foo(T); // line 1
916 // template <class T1, class T2> class A { // line 2
917 // friend void foo<>(T1); // line 3
918 // }; // line 4
919 // template <> void foo(char); // line 5
920 // template class A<char, bool>; // line 6
921 // In the code above, foo's spec_iterator has an explicit spec,
922 // but this spec's source range points to the dependent_spec at line 3,
923 // and then we will be in trouble...
924 if (TK == FunctionDecl::TK_DependentFunctionTemplateSpecialization) {
925 const DependentFunctionTemplateSpecializationInfo *Info =
926 TheFD->getDependentSpecializationInfo();
927 // don't need to track all specs, just associate FD with one
928 // of those
929 const FunctionDecl *Member = nullptr;
930
931 #if LLVM_VERSION_MAJOR >= 18
932 ArrayRef<FunctionTemplateDecl *> members = Info->getCandidates();
933 if (!members.empty()) {
934 Member = members[0]->getTemplatedDecl();
935 }
936 #else
937 if (Info->getNumTemplates() > 0) {
938 Member = Info->getTemplate(0)->getTemplatedDecl();
939 }
940 #endif
941
942 if (Member != nullptr)
943 createFuncToExplicitSpecs(Member);
944 return;
945 }
946
947 // keep explicit instantiations that are not recored by original
948 // template's spec_iterator, e.g.:
949 // template<typename T> class S {
950 // public:
951 // template<typename V> void foo(V& v) {};
952 // };
953 // typedef S<char> SS;
954 // template void SS::foo(unsigned short&);
955 FunctionTemplateDecl *FTD = TheFD->getPrimaryTemplate();
956 if (!FTD)
957 return;
958
959 const FunctionTemplateDecl *D = FTD->getInstantiatedFromMemberTemplate();
960 if (!D)
961 return;
962 const FunctionDecl *OrigFD = D->getTemplatedDecl();
963 TemplateSpecializationKind K = TheFD->getTemplateSpecializationKind();
964 if (K != TSK_ExplicitInstantiationDeclaration &&
965 K != TSK_ExplicitInstantiationDefinition)
966 return;
967
968 MemberSpecializationSet *S =
969 MemberToInstantiations[OrigFD->getCanonicalDecl()];
970 if (S == NULL) {
971 S = new MemberSpecializationSet();
972 MemberToInstantiations[OrigFD->getCanonicalDecl()] = S;
973 }
974 S->insert(TheFD);
975 }
976
977 void RemoveUnusedFunction::handleOneCallExpr(const CallExpr *E)
978 {
979 const FunctionDecl *FD = E->getDirectCallee();
980 if (!FD)
981 return;
982 const FunctionDecl *TheFD = getSourceFunctionDecl(FD);
983 addOneReferencedFunction(TheFD);
984 }
985
986 void RemoveUnusedFunction::handleOneCXXOperatorCallExpr(
987 const CXXOperatorCallExpr *E)
988 {
989 const FunctionDecl *FD = E->getDirectCallee();
990 if (!FD)
991 return;
992 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
993 if (!MD)
994 return;
995 if (const FunctionDecl *OrigFD = MD->getInstantiatedFromMemberFunction())
996 addOneReferencedFunction(OrigFD);
997 }
998
999 void RemoveUnusedFunction::addOneFunctionDecl(const FunctionDecl *CanonicalFD)
1000 {
1001 ValidInstanceNum++;
1002 if (ToCounter > 0) {
1003 AllValidFunctionDecls.push_back(CanonicalFD);
1004 return;
1005 }
1006 if (ValidInstanceNum == TransformationCounter) {
1007 TheFunctionDecl = CanonicalFD;
1008 }
1009 }
1010
1011 void RemoveUnusedFunction::addOneReferencedFunction(
1012 const FunctionDecl *FD)
1013 {
1014 ReferencedFDs.insert(FD->getCanonicalDecl());
1015 }
1016
1017 const FunctionTemplateDecl *RemoveUnusedFunction::getTopDescribedTemplate(
1018 const FunctionDecl *FD)
1019 {
1020 FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate();
1021 if (!FTD)
1022 return NULL;
1023 if (const FunctionTemplateDecl *D = FTD->getInstantiatedFromMemberTemplate())
1024 return D;
1025 else
1026 return FTD;
1027 }
1028
1029 bool RemoveUnusedFunction::hasReferencedSpecialization(const FunctionDecl *FD)
1030 {
1031 if (const FunctionTemplateDecl *FTD = getTopDescribedTemplate(FD)) {
1032 for (FunctionTemplateDecl::spec_iterator I = FTD->spec_begin(),
1033 E = FTD->spec_end(); I != E; ++I) {
1034 if ((*I)->isReferenced())
1035 return true;
1036 }
1037 }
1038 return false;
1039 }
1040
1041 void RemoveUnusedFunction::setInlinedSystemFunctions(const FunctionDecl *FD)
1042 {
1043 if (!FD->isInlined())
1044 return;
1045
1046 std::string FDNameStr = FD->getNameAsString();
1047 for (InlinedSystemFunctionsMap::iterator I = InlinedSystemFunctions.begin(),
1048 E = InlinedSystemFunctions.end(); I != E; ++I) {
1049 if (FDNameStr == (*I).second) {
1050 ExistingSystemFunctions.insert(FDNameStr);
1051 return;
1052 }
1053 }
1054 }
1055
1056 bool RemoveUnusedFunction::isInlinedSystemFunction(const FunctionDecl *FD)
1057 {
1058 std::string FDNameStr = FD->getNameAsString();
1059 InlinedSystemFunctionsMap::iterator I =
1060 InlinedSystemFunctions.find(FDNameStr);
1061 if (I == InlinedSystemFunctions.end())
1062 return false;
1063 return ExistingSystemFunctions.count((*I).second);
1064 }
1065
1066 void RemoveUnusedFunction::addOneMemberSpecialization(
1067 const FunctionDecl *FD, const FunctionDecl *Member)
1068 {
1069 MemberSpecializationSet *S =
1070 MemberToSpecs[Member->getCanonicalDecl()];
1071 if (S == NULL) {
1072 S = new MemberSpecializationSet();
1073 MemberToSpecs[Member->getCanonicalDecl()] = S;
1074 }
1075 S->insert(FD);
1076 }
1077
1078 void RemoveUnusedFunction::createFuncToExplicitSpecs(const FunctionDecl *FD)
1079 {
1080 MemberSpecializationSet *S =
1081 FuncToExplicitSpecs[FD->getCanonicalDecl()];
1082 if (S == NULL) {
1083 S = new MemberSpecializationSet();
1084 FuncToExplicitSpecs[FD->getCanonicalDecl()] = S;
1085 }
1086 }
1087
1088 void RemoveUnusedFunction::addFuncToExplicitSpecs(const FunctionDecl *FD)
1089 {
1090 TransAssert((FD->getTemplateSpecializationKind()
1091 == TSK_ExplicitSpecialization) &&
1092 "Invalid template specialization kind!");
1093 const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
1094 TransAssert(FTD && "NULL FunctionTemplateDecl!");
1095 const FunctionDecl *TemplatedFD = FTD->getTemplatedDecl();
1096 MemberSpecializationSet *S =
1097 FuncToExplicitSpecs[TemplatedFD->getCanonicalDecl()];
1098 if (S != NULL) {
1099 S->insert(FD);
1100 }
1101 }
1102
1103 RemoveUnusedFunction::~RemoveUnusedFunction()
1104 {
1105 for (MemberToSpecializationMap::iterator I = MemberToSpecs.begin(),
1106 E = MemberToSpecs.end(); I != E; ++I) {
1107 delete ((*I).second);
1108 }
1109 for (MemberToSpecializationMap::iterator I = MemberToInstantiations.begin(),
1110 E = MemberToInstantiations.end(); I != E; ++I) {
1111 delete ((*I).second);
1112 }
1113 delete AnalysisVisitor;
1114 delete VisitorWrapper;
1115 }
1116