1 //===--- IncludeCleaner.cpp - Unused/Missing Headers Analysis ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "IncludeCleaner.h" 10 #include "Config.h" 11 #include "Protocol.h" 12 #include "SourceCode.h" 13 #include "support/Logger.h" 14 #include "support/Trace.h" 15 #include "clang/AST/RecursiveASTVisitor.h" 16 #include "clang/Basic/SourceLocation.h" 17 #include "clang/Tooling/Syntax/Tokens.h" 18 #include "llvm/Support/FormatVariadic.h" 19 #include "llvm/Support/Path.h" 20 21 namespace clang { 22 namespace clangd { 23 namespace { 24 25 /// Crawler traverses the AST and feeds in the locations of (sometimes 26 /// implicitly) used symbols into \p Result. 27 class ReferencedLocationCrawler 28 : public RecursiveASTVisitor<ReferencedLocationCrawler> { 29 public: 30 ReferencedLocationCrawler(ReferencedLocations &Result) : Result(Result) {} 31 32 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 33 add(DRE->getDecl()); 34 add(DRE->getFoundDecl()); 35 return true; 36 } 37 38 bool VisitMemberExpr(MemberExpr *ME) { 39 add(ME->getMemberDecl()); 40 add(ME->getFoundDecl().getDecl()); 41 return true; 42 } 43 44 bool VisitTagType(TagType *TT) { 45 add(TT->getDecl()); 46 return true; 47 } 48 49 bool VisitFunctionDecl(FunctionDecl *FD) { 50 // Function definition will require redeclarations to be included. 51 if (FD == FD->getDefinition()) 52 add(FD); 53 return true; 54 } 55 56 bool VisitCXXConstructExpr(CXXConstructExpr *CCE) { 57 add(CCE->getConstructor()); 58 return true; 59 } 60 61 bool VisitTemplateSpecializationType(TemplateSpecializationType *TST) { 62 if (isNew(TST)) { 63 add(TST->getTemplateName().getAsTemplateDecl()); // Primary template. 64 add(TST->getAsCXXRecordDecl()); // Specialization 65 } 66 return true; 67 } 68 69 bool VisitTypedefType(TypedefType *TT) { 70 add(TT->getDecl()); 71 return true; 72 } 73 74 // Consider types of any subexpression used, even if the type is not named. 75 // This is helpful in getFoo().bar(), where Foo must be complete. 76 // FIXME(kirillbobyrev): Should we tweak this? It may not be desirable to 77 // consider types "used" when they are not directly spelled in code. 78 bool VisitExpr(Expr *E) { 79 TraverseType(E->getType()); 80 return true; 81 } 82 83 bool TraverseType(QualType T) { 84 if (isNew(T.getTypePtrOrNull())) // don't care about quals 85 Base::TraverseType(T); 86 return true; 87 } 88 89 bool VisitUsingDecl(UsingDecl *D) { 90 for (const auto *Shadow : D->shadows()) 91 add(Shadow->getTargetDecl()); 92 return true; 93 } 94 95 // Enums may be usefully forward-declared as *complete* types by specifying 96 // an underlying type. In this case, the definition should see the declaration 97 // so they can be checked for compatibility. 98 bool VisitEnumDecl(EnumDecl *D) { 99 if (D->isThisDeclarationADefinition() && D->getIntegerTypeSourceInfo()) 100 add(D); 101 return true; 102 } 103 104 private: 105 using Base = RecursiveASTVisitor<ReferencedLocationCrawler>; 106 107 void add(const Decl *D) { 108 if (!D || !isNew(D->getCanonicalDecl())) 109 return; 110 for (const Decl *Redecl : D->redecls()) 111 Result.insert(Redecl->getLocation()); 112 } 113 114 bool isNew(const void *P) { return P && Visited.insert(P).second; } 115 116 ReferencedLocations &Result; 117 llvm::DenseSet<const void *> Visited; 118 }; 119 120 // Given a set of referenced FileIDs, determines all the potentially-referenced 121 // files and macros by traversing expansion/spelling locations of macro IDs. 122 // This is used to map the referenced SourceLocations onto real files. 123 struct ReferencedFiles { 124 ReferencedFiles(const SourceManager &SM) : SM(SM) {} 125 llvm::DenseSet<FileID> Files; 126 llvm::DenseSet<FileID> Macros; 127 const SourceManager &SM; 128 129 void add(SourceLocation Loc) { add(SM.getFileID(Loc), Loc); } 130 131 void add(FileID FID, SourceLocation Loc) { 132 if (FID.isInvalid()) 133 return; 134 assert(SM.isInFileID(Loc, FID)); 135 if (Loc.isFileID()) { 136 Files.insert(FID); 137 return; 138 } 139 // Don't process the same macro FID twice. 140 if (!Macros.insert(FID).second) 141 return; 142 const auto &Exp = SM.getSLocEntry(FID).getExpansion(); 143 // For token pasting operator in macros, spelling and expansion locations 144 // can be within a temporary buffer that Clang creates (scratch space or 145 // ScratchBuffer). That is not a real file we can include. 146 if (!SM.isWrittenInScratchSpace(Exp.getSpellingLoc())) 147 add(Exp.getSpellingLoc()); 148 if (!SM.isWrittenInScratchSpace(Exp.getExpansionLocStart())) 149 add(Exp.getExpansionLocStart()); 150 if (!SM.isWrittenInScratchSpace(Exp.getExpansionLocEnd())) 151 add(Exp.getExpansionLocEnd()); 152 } 153 }; 154 155 // Returns the range starting at '#' and ending at EOL. Escaped newlines are not 156 // handled. 157 clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) { 158 clangd::Range Result; 159 Result.end = Result.start = offsetToPosition(Code, HashOffset); 160 161 // Span the warning until the EOL or EOF. 162 Result.end.character += 163 lspLength(Code.drop_front(HashOffset).take_until([](char C) { 164 return C == '\n' || C == '\r'; 165 })); 166 return Result; 167 } 168 169 // Finds locations of macros referenced from within the main file. That includes 170 // references that were not yet expanded, e.g `BAR` in `#define FOO BAR`. 171 void findReferencedMacros(ParsedAST &AST, ReferencedLocations &Result) { 172 trace::Span Tracer("IncludeCleaner::findReferencedMacros"); 173 auto &SM = AST.getSourceManager(); 174 auto &PP = AST.getPreprocessor(); 175 // FIXME(kirillbobyrev): The macros from the main file are collected in 176 // ParsedAST's MainFileMacros. However, we can't use it here because it 177 // doesn't handle macro references that were not expanded, e.g. in macro 178 // definitions or preprocessor-disabled sections. 179 // 180 // Extending MainFileMacros to collect missing references and switching to 181 // this mechanism (as opposed to iterating through all tokens) will improve 182 // the performance of findReferencedMacros and also improve other features 183 // relying on MainFileMacros. 184 for (const syntax::Token &Tok : 185 AST.getTokens().spelledTokens(SM.getMainFileID())) { 186 auto Macro = locateMacroAt(Tok, PP); 187 if (!Macro) 188 continue; 189 auto Loc = Macro->Info->getDefinitionLoc(); 190 if (Loc.isValid()) 191 Result.insert(Loc); 192 } 193 } 194 195 // FIXME(kirillbobyrev): We currently do not support the umbrella headers. 196 // Standard Library headers are typically umbrella headers, and system headers 197 // are likely to be the Standard Library headers. Until we have a good support 198 // for umbrella headers and Standard Library headers, don't warn about them. 199 bool mayConsiderUnused(const Inclusion *Inc) { 200 return Inc->Written.front() != '<'; 201 } 202 203 } // namespace 204 205 ReferencedLocations findReferencedLocations(ParsedAST &AST) { 206 ReferencedLocations Result; 207 ReferencedLocationCrawler Crawler(Result); 208 Crawler.TraverseAST(AST.getASTContext()); 209 findReferencedMacros(AST, Result); 210 return Result; 211 } 212 213 llvm::DenseSet<FileID> 214 findReferencedFiles(const llvm::DenseSet<SourceLocation> &Locs, 215 const SourceManager &SM) { 216 std::vector<SourceLocation> Sorted{Locs.begin(), Locs.end()}; 217 llvm::sort(Sorted); // Group by FileID. 218 ReferencedFiles Result(SM); 219 for (auto It = Sorted.begin(); It < Sorted.end();) { 220 FileID FID = SM.getFileID(*It); 221 Result.add(FID, *It); 222 // Cheaply skip over all the other locations from the same FileID. 223 // This avoids lots of redundant Loc->File lookups for the same file. 224 do 225 ++It; 226 while (It != Sorted.end() && SM.isInFileID(*It, FID)); 227 } 228 return std::move(Result.Files); 229 } 230 231 std::vector<const Inclusion *> 232 getUnused(const IncludeStructure &Structure, 233 const llvm::DenseSet<IncludeStructure::HeaderID> &ReferencedFiles) { 234 std::vector<const Inclusion *> Unused; 235 for (const Inclusion &MFI : Structure.MainFileIncludes) { 236 // FIXME: Skip includes that are not self-contained. 237 if (!MFI.HeaderID) { 238 elog("File {0} not found.", MFI.Written); 239 continue; 240 } 241 auto IncludeID = static_cast<IncludeStructure::HeaderID>(*MFI.HeaderID); 242 if (!ReferencedFiles.contains(IncludeID)) 243 Unused.push_back(&MFI); 244 dlog("{0} is {1}", MFI.Written, 245 ReferencedFiles.contains(IncludeID) ? "USED" : "UNUSED"); 246 } 247 return Unused; 248 } 249 250 llvm::DenseSet<IncludeStructure::HeaderID> 251 translateToHeaderIDs(const llvm::DenseSet<FileID> &Files, 252 const IncludeStructure &Includes, 253 const SourceManager &SM) { 254 llvm::DenseSet<IncludeStructure::HeaderID> TranslatedHeaderIDs; 255 TranslatedHeaderIDs.reserve(Files.size()); 256 for (FileID FID : Files) { 257 const FileEntry *FE = SM.getFileEntryForID(FID); 258 assert(FE); 259 const auto File = Includes.getID(FE); 260 assert(File); 261 TranslatedHeaderIDs.insert(*File); 262 } 263 return TranslatedHeaderIDs; 264 } 265 266 std::vector<const Inclusion *> computeUnusedIncludes(ParsedAST &AST) { 267 const auto &SM = AST.getSourceManager(); 268 269 auto Refs = findReferencedLocations(AST); 270 auto ReferencedFiles = translateToHeaderIDs(findReferencedFiles(Refs, SM), 271 AST.getIncludeStructure(), SM); 272 return getUnused(AST.getIncludeStructure(), ReferencedFiles); 273 } 274 275 std::vector<Diag> issueUnusedIncludesDiagnostics(ParsedAST &AST, 276 llvm::StringRef Code) { 277 const Config &Cfg = Config::current(); 278 if (Cfg.Diagnostics.UnusedIncludes != Config::UnusedIncludesPolicy::Strict || 279 Cfg.Diagnostics.SuppressAll || 280 Cfg.Diagnostics.Suppress.contains("unused-includes")) 281 return {}; 282 std::vector<Diag> Result; 283 std::string FileName = 284 AST.getSourceManager() 285 .getFileEntryForID(AST.getSourceManager().getMainFileID()) 286 ->getName() 287 .str(); 288 for (const auto *Inc : computeUnusedIncludes(AST)) { 289 if (!mayConsiderUnused(Inc)) 290 continue; 291 Diag D; 292 D.Message = 293 llvm::formatv("included header {0} is not used", 294 llvm::sys::path::filename( 295 Inc->Written.substr(1, Inc->Written.size() - 2), 296 llvm::sys::path::Style::posix)); 297 D.Name = "unused-includes"; 298 D.Source = Diag::DiagSource::Clangd; 299 D.File = FileName; 300 D.Severity = DiagnosticsEngine::Warning; 301 D.Tags.push_back(Unnecessary); 302 D.Range = getDiagnosticRange(Code, Inc->HashOffset); 303 // FIXME(kirillbobyrev): Removing inclusion might break the code if the 304 // used headers are only reachable transitively through this one. Suggest 305 // including them directly instead. 306 // FIXME(kirillbobyrev): Add fix suggestion for adding IWYU pragmas 307 // (keep/export) remove the warning once we support IWYU pragmas. 308 D.Fixes.emplace_back(); 309 D.Fixes.back().Message = "remove #include directive"; 310 D.Fixes.back().Edits.emplace_back(); 311 D.Fixes.back().Edits.back().range.start.line = Inc->HashLine; 312 D.Fixes.back().Edits.back().range.end.line = Inc->HashLine + 1; 313 D.InsideMainFile = true; 314 Result.push_back(std::move(D)); 315 } 316 return Result; 317 } 318 319 } // namespace clangd 320 } // namespace clang 321