[VectorCombine] Enable transform 'foldSingleElementStore' for scalable vector types
[llvm-project.git] / clang-tools-extra / clangd / IncludeCleaner.cpp
blob1fcb5c7228fb639c0c3171a7279eb8bd0c0877e4
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 //===----------------------------------------------------------------------===//
9 #include "IncludeCleaner.h"
10 #include "Diagnostics.h"
11 #include "Headers.h"
12 #include "ParsedAST.h"
13 #include "Preamble.h"
14 #include "Protocol.h"
15 #include "SourceCode.h"
16 #include "clang-include-cleaner/Analysis.h"
17 #include "clang-include-cleaner/IncludeSpeller.h"
18 #include "clang-include-cleaner/Record.h"
19 #include "clang-include-cleaner/Types.h"
20 #include "support/Logger.h"
21 #include "support/Path.h"
22 #include "support/Trace.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Format/Format.h"
29 #include "clang/Lex/DirectoryLookup.h"
30 #include "clang/Lex/HeaderSearch.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Tooling/Core/Replacement.h"
33 #include "clang/Tooling/Inclusions/HeaderIncludes.h"
34 #include "clang/Tooling/Inclusions/StandardLibrary.h"
35 #include "clang/Tooling/Syntax/Tokens.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/GenericUniformityImpl.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/Support/Error.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormatVariadic.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Regex.h"
48 #include <cassert>
49 #include <iterator>
50 #include <map>
51 #include <memory>
52 #include <optional>
53 #include <string>
54 #include <utility>
55 #include <vector>
57 namespace clang::clangd {
58 namespace {
60 bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter IgnoreHeaders) {
61 // Convert the path to Unix slashes and try to match against the filter.
62 llvm::SmallString<64> NormalizedPath(HeaderPath);
63 llvm::sys::path::native(NormalizedPath, llvm::sys::path::Style::posix);
64 for (auto &Filter : IgnoreHeaders) {
65 if (Filter(NormalizedPath))
66 return true;
68 return false;
71 bool mayConsiderUnused(const Inclusion &Inc, ParsedAST &AST,
72 const include_cleaner::PragmaIncludes *PI) {
73 assert(Inc.HeaderID);
74 auto HID = static_cast<IncludeStructure::HeaderID>(*Inc.HeaderID);
75 auto FE = AST.getSourceManager().getFileManager().getFileRef(
76 AST.getIncludeStructure().getRealPath(HID));
77 assert(FE);
78 if (PI && PI->shouldKeep(*FE))
79 return false;
80 // FIXME(kirillbobyrev): We currently do not support the umbrella headers.
81 // System headers are likely to be standard library headers.
82 // Until we have good support for umbrella headers, don't warn about them.
83 if (Inc.Written.front() == '<')
84 return tooling::stdlib::Header::named(Inc.Written).has_value();
85 if (PI) {
86 // Check if main file is the public interface for a private header. If so we
87 // shouldn't diagnose it as unused.
88 if (auto PHeader = PI->getPublic(*FE); !PHeader.empty()) {
89 PHeader = PHeader.trim("<>\"");
90 // Since most private -> public mappings happen in a verbatim way, we
91 // check textually here. This might go wrong in presence of symlinks or
92 // header mappings. But that's not different than rest of the places.
93 if (AST.tuPath().endswith(PHeader))
94 return false;
97 // Headers without include guards have side effects and are not
98 // self-contained, skip them.
99 if (!AST.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
100 &FE->getFileEntry())) {
101 dlog("{0} doesn't have header guard and will not be considered unused",
102 FE->getName());
103 return false;
105 return true;
108 std::vector<Diag> generateMissingIncludeDiagnostics(
109 ParsedAST &AST, llvm::ArrayRef<MissingIncludeDiagInfo> MissingIncludes,
110 llvm::StringRef Code, HeaderFilter IgnoreHeaders) {
111 std::vector<Diag> Result;
112 const SourceManager &SM = AST.getSourceManager();
113 const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
115 auto FileStyle = format::getStyle(
116 format::DefaultFormatStyle, AST.tuPath(), format::DefaultFallbackStyle,
117 Code, &SM.getFileManager().getVirtualFileSystem());
118 if (!FileStyle) {
119 elog("Couldn't infer style", FileStyle.takeError());
120 FileStyle = format::getLLVMStyle();
123 tooling::HeaderIncludes HeaderIncludes(AST.tuPath(), Code,
124 FileStyle->IncludeStyle);
125 for (const auto &SymbolWithMissingInclude : MissingIncludes) {
126 llvm::StringRef ResolvedPath =
127 SymbolWithMissingInclude.Providers.front().resolvedPath();
128 if (isIgnored(ResolvedPath, IgnoreHeaders)) {
129 dlog("IncludeCleaner: not diagnosing missing include {0}, filtered by "
130 "config",
131 ResolvedPath);
132 continue;
135 std::string Spelling = include_cleaner::spellHeader(
136 {SymbolWithMissingInclude.Providers.front(),
137 AST.getPreprocessor().getHeaderSearchInfo(), MainFile});
139 llvm::StringRef HeaderRef{Spelling};
140 bool Angled = HeaderRef.starts_with("<");
141 // We might suggest insertion of an existing include in edge cases, e.g.,
142 // include is present in a PP-disabled region, or spelling of the header
143 // turns out to be the same as one of the unresolved includes in the
144 // main file.
145 std::optional<tooling::Replacement> Replacement = HeaderIncludes.insert(
146 HeaderRef.trim("\"<>"), Angled, tooling::IncludeDirective::Include);
147 if (!Replacement.has_value())
148 continue;
150 Diag &D = Result.emplace_back();
151 D.Message =
152 llvm::formatv("No header providing \"{0}\" is directly included",
153 SymbolWithMissingInclude.Symbol.name());
154 D.Name = "missing-includes";
155 D.Source = Diag::DiagSource::Clangd;
156 D.File = AST.tuPath();
157 D.InsideMainFile = true;
158 // We avoid the "warning" severity here in favor of LSP's "information".
160 // Users treat most warnings on code being edited as high-priority.
161 // They don't think of include cleanups the same way: they want to edit
162 // lines with existing violations without fixing them.
163 // Diagnostics at the same level tend to be visually indistinguishable,
164 // and a few missing includes can cause many diagnostics.
165 // Marking these as "information" leaves them visible, but less intrusive.
167 // (These concerns don't apply to unused #include warnings: these are fewer,
168 // they appear on infrequently-edited lines with few other warnings, and
169 // the 'Unneccesary' tag often result in a different rendering)
171 // Usually clang's "note" severity usually has special semantics, being
172 // translated into LSP RelatedInformation of a parent diagnostic.
173 // But not here: these aren't processed by clangd's DiagnosticConsumer.
174 D.Severity = DiagnosticsEngine::Note;
175 D.Range = clangd::Range{
176 offsetToPosition(Code,
177 SymbolWithMissingInclude.SymRefRange.beginOffset()),
178 offsetToPosition(Code,
179 SymbolWithMissingInclude.SymRefRange.endOffset())};
180 auto &F = D.Fixes.emplace_back();
181 F.Message = "#include " + Spelling;
182 TextEdit Edit = replacementToEdit(Code, *Replacement);
183 F.Edits.emplace_back(std::move(Edit));
185 return Result;
188 std::vector<Diag> generateUnusedIncludeDiagnostics(
189 PathRef FileName, llvm::ArrayRef<const Inclusion *> UnusedIncludes,
190 llvm::StringRef Code, HeaderFilter IgnoreHeaders) {
191 std::vector<Diag> Result;
192 for (const auto *Inc : UnusedIncludes) {
193 if (isIgnored(Inc->Resolved, IgnoreHeaders))
194 continue;
195 Diag &D = Result.emplace_back();
196 D.Message =
197 llvm::formatv("included header {0} is not used directly",
198 llvm::sys::path::filename(
199 Inc->Written.substr(1, Inc->Written.size() - 2),
200 llvm::sys::path::Style::posix));
201 D.Name = "unused-includes";
202 D.Source = Diag::DiagSource::Clangd;
203 D.File = FileName;
204 D.InsideMainFile = true;
205 D.Severity = DiagnosticsEngine::Warning;
206 D.Tags.push_back(Unnecessary);
207 D.Range = rangeTillEOL(Code, Inc->HashOffset);
208 // FIXME(kirillbobyrev): Removing inclusion might break the code if the
209 // used headers are only reachable transitively through this one. Suggest
210 // including them directly instead.
211 // FIXME(kirillbobyrev): Add fix suggestion for adding IWYU pragmas
212 // (keep/export) remove the warning once we support IWYU pragmas.
213 auto &F = D.Fixes.emplace_back();
214 F.Message = "remove #include directive";
215 F.Edits.emplace_back();
216 F.Edits.back().range.start.line = Inc->HashLine;
217 F.Edits.back().range.end.line = Inc->HashLine + 1;
219 return Result;
222 std::optional<Fix>
223 removeAllUnusedIncludes(llvm::ArrayRef<Diag> UnusedIncludes) {
224 if (UnusedIncludes.empty())
225 return std::nullopt;
227 Fix RemoveAll;
228 RemoveAll.Message = "remove all unused includes";
229 for (const auto &Diag : UnusedIncludes) {
230 assert(Diag.Fixes.size() == 1 && "Expected exactly one fix.");
231 RemoveAll.Edits.insert(RemoveAll.Edits.end(),
232 Diag.Fixes.front().Edits.begin(),
233 Diag.Fixes.front().Edits.end());
236 // TODO(hokein): emit a suitable text for the label.
237 ChangeAnnotation Annotation = {/*label=*/"",
238 /*needsConfirmation=*/true,
239 /*description=*/""};
240 static const ChangeAnnotationIdentifier RemoveAllUnusedID =
241 "RemoveAllUnusedIncludes";
242 for (unsigned I = 0; I < RemoveAll.Edits.size(); ++I) {
243 ChangeAnnotationIdentifier ID = RemoveAllUnusedID + std::to_string(I);
244 RemoveAll.Edits[I].annotationId = ID;
245 RemoveAll.Annotations.push_back({ID, Annotation});
247 return RemoveAll;
250 std::optional<Fix>
251 addAllMissingIncludes(llvm::ArrayRef<Diag> MissingIncludeDiags) {
252 if (MissingIncludeDiags.empty())
253 return std::nullopt;
255 Fix AddAllMissing;
256 AddAllMissing.Message = "add all missing includes";
257 // A map to deduplicate the edits with the same new text.
258 // newText (#include "my_missing_header.h") -> TextEdit.
259 std::map<std::string, TextEdit> Edits;
260 for (const auto &Diag : MissingIncludeDiags) {
261 assert(Diag.Fixes.size() == 1 && "Expected exactly one fix.");
262 for (const auto &Edit : Diag.Fixes.front().Edits) {
263 Edits.try_emplace(Edit.newText, Edit);
266 // FIXME(hokein): emit used symbol reference in the annotation.
267 ChangeAnnotation Annotation = {/*label=*/"",
268 /*needsConfirmation=*/true,
269 /*description=*/""};
270 static const ChangeAnnotationIdentifier AddAllMissingID =
271 "AddAllMissingIncludes";
272 unsigned I = 0;
273 for (auto &It : Edits) {
274 ChangeAnnotationIdentifier ID = AddAllMissingID + std::to_string(I++);
275 AddAllMissing.Edits.push_back(std::move(It.second));
276 AddAllMissing.Edits.back().annotationId = ID;
278 AddAllMissing.Annotations.push_back({ID, Annotation});
280 return AddAllMissing;
282 Fix fixAll(const Fix &RemoveAllUnused, const Fix &AddAllMissing) {
283 Fix FixAll;
284 FixAll.Message = "fix all includes";
286 for (const auto &F : RemoveAllUnused.Edits)
287 FixAll.Edits.push_back(F);
288 for (const auto &F : AddAllMissing.Edits)
289 FixAll.Edits.push_back(F);
291 for (const auto &A : RemoveAllUnused.Annotations)
292 FixAll.Annotations.push_back(A);
293 for (const auto &A : AddAllMissing.Annotations)
294 FixAll.Annotations.push_back(A);
295 return FixAll;
298 std::vector<const Inclusion *>
299 getUnused(ParsedAST &AST,
300 const llvm::DenseSet<IncludeStructure::HeaderID> &ReferencedFiles) {
301 trace::Span Tracer("IncludeCleaner::getUnused");
302 std::vector<const Inclusion *> Unused;
303 for (const Inclusion &MFI : AST.getIncludeStructure().MainFileIncludes) {
304 if (!MFI.HeaderID)
305 continue;
306 auto IncludeID = static_cast<IncludeStructure::HeaderID>(*MFI.HeaderID);
307 if (ReferencedFiles.contains(IncludeID))
308 continue;
309 if (!mayConsiderUnused(MFI, AST, AST.getPragmaIncludes().get())) {
310 dlog("{0} was not used, but is not eligible to be diagnosed as unused",
311 MFI.Written);
312 continue;
314 Unused.push_back(&MFI);
316 return Unused;
319 } // namespace
321 std::vector<include_cleaner::SymbolReference>
322 collectMacroReferences(ParsedAST &AST) {
323 const auto &SM = AST.getSourceManager();
324 auto &PP = AST.getPreprocessor();
325 std::vector<include_cleaner::SymbolReference> Macros;
326 for (const auto &[_, Refs] : AST.getMacros().MacroRefs) {
327 for (const auto &Ref : Refs) {
328 auto Loc = SM.getComposedLoc(SM.getMainFileID(), Ref.StartOffset);
329 const auto *Tok = AST.getTokens().spelledTokenAt(Loc);
330 if (!Tok)
331 continue;
332 auto Macro = locateMacroAt(*Tok, PP);
333 if (!Macro)
334 continue;
335 auto DefLoc = Macro->NameLoc;
336 if (!DefLoc.isValid())
337 continue;
338 Macros.push_back(
339 {include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok->text(SM)),
340 DefLoc},
341 Tok->location(),
342 Ref.InConditionalDirective ? include_cleaner::RefType::Ambiguous
343 : include_cleaner::RefType::Explicit});
347 return Macros;
350 include_cleaner::Includes convertIncludes(const ParsedAST &AST) {
351 auto &SM = AST.getSourceManager();
353 include_cleaner::Includes ConvertedIncludes;
354 // We satisfy Includes's contract that search dirs and included files have
355 // matching path styles: both ultimately use FileManager::getCanonicalName().
356 for (const auto &Dir : AST.getIncludeStructure().SearchPathsCanonical)
357 ConvertedIncludes.addSearchDirectory(Dir);
359 for (const Inclusion &Inc : AST.getIncludeStructure().MainFileIncludes) {
360 include_cleaner::Include TransformedInc;
361 llvm::StringRef WrittenRef = llvm::StringRef(Inc.Written);
362 TransformedInc.Spelled = WrittenRef.trim("\"<>");
363 TransformedInc.HashLocation =
364 SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
365 TransformedInc.Line = Inc.HashLine + 1;
366 TransformedInc.Angled = WrittenRef.starts_with("<");
367 // Inc.Resolved is canonicalized with clangd::getCanonicalPath(),
368 // which is based on FileManager::getCanonicalName(ParentDir).
369 auto FE = SM.getFileManager().getFileRef(Inc.Resolved);
370 if (!FE) {
371 elog("IncludeCleaner: Failed to get an entry for resolved path {0}: {1}",
372 Inc.Resolved, FE.takeError());
373 continue;
375 TransformedInc.Resolved = *FE;
376 ConvertedIncludes.add(std::move(TransformedInc));
378 return ConvertedIncludes;
381 IncludeCleanerFindings computeIncludeCleanerFindings(ParsedAST &AST) {
382 // Interaction is only polished for C/CPP.
383 if (AST.getLangOpts().ObjC)
384 return {};
385 const auto &SM = AST.getSourceManager();
386 include_cleaner::Includes ConvertedIncludes = convertIncludes(AST);
387 const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
388 auto *PreamblePatch = PreamblePatch::getPatchEntry(AST.tuPath(), SM);
390 std::vector<include_cleaner::SymbolReference> Macros =
391 collectMacroReferences(AST);
392 std::vector<MissingIncludeDiagInfo> MissingIncludes;
393 llvm::DenseSet<IncludeStructure::HeaderID> Used;
394 trace::Span Tracer("include_cleaner::walkUsed");
395 include_cleaner::walkUsed(
396 AST.getLocalTopLevelDecls(), /*MacroRefs=*/Macros,
397 AST.getPragmaIncludes().get(), AST.getPreprocessor(),
398 [&](const include_cleaner::SymbolReference &Ref,
399 llvm::ArrayRef<include_cleaner::Header> Providers) {
400 bool Satisfied = false;
401 for (const auto &H : Providers) {
402 if (H.kind() == include_cleaner::Header::Physical &&
403 (H.physical() == MainFile || H.physical() == PreamblePatch)) {
404 Satisfied = true;
405 continue;
407 for (auto *Inc : ConvertedIncludes.match(H)) {
408 Satisfied = true;
409 auto HeaderID =
410 AST.getIncludeStructure().getID(&Inc->Resolved->getFileEntry());
411 assert(HeaderID.has_value() &&
412 "ConvertedIncludes only contains resolved includes.");
413 Used.insert(*HeaderID);
417 if (Satisfied || Providers.empty() ||
418 Ref.RT != include_cleaner::RefType::Explicit)
419 return;
421 // We actually always want to map usages to their spellings, but
422 // spelling locations can point into preamble section. Using these
423 // offsets could lead into crashes in presence of stale preambles. Hence
424 // we use "getFileLoc" instead to make sure it always points into main
425 // file.
426 // FIXME: Use presumed locations to map such usages back to patched
427 // locations safely.
428 auto Loc = SM.getFileLoc(Ref.RefLocation);
429 // File locations can be outside of the main file if macro is expanded
430 // through an #include.
431 while (SM.getFileID(Loc) != SM.getMainFileID())
432 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
433 auto TouchingTokens =
434 syntax::spelledTokensTouching(Loc, AST.getTokens());
435 assert(!TouchingTokens.empty());
436 // Loc points to the start offset of the ref token, here we use the last
437 // element of the TouchingTokens, e.g. avoid getting the "::" for
438 // "ns::^abc".
439 MissingIncludeDiagInfo DiagInfo{
440 Ref.Target, TouchingTokens.back().range(SM), Providers};
441 MissingIncludes.push_back(std::move(DiagInfo));
443 // Put possibly equal diagnostics together for deduplication.
444 // The duplicates might be from macro arguments that get expanded multiple
445 // times.
446 llvm::stable_sort(MissingIncludes, [](const MissingIncludeDiagInfo &LHS,
447 const MissingIncludeDiagInfo &RHS) {
448 // First sort by reference location.
449 if (LHS.SymRefRange != RHS.SymRefRange) {
450 // We can get away just by comparing the offsets as all the ranges are in
451 // main file.
452 return LHS.SymRefRange.beginOffset() < RHS.SymRefRange.beginOffset();
454 // For the same location, break ties using the symbol. Note that this won't
455 // be stable across runs.
456 using MapInfo = llvm::DenseMapInfo<include_cleaner::Symbol>;
457 return MapInfo::getHashValue(LHS.Symbol) <
458 MapInfo::getHashValue(RHS.Symbol);
460 MissingIncludes.erase(llvm::unique(MissingIncludes), MissingIncludes.end());
461 std::vector<const Inclusion *> UnusedIncludes = getUnused(AST, Used);
462 return {std::move(UnusedIncludes), std::move(MissingIncludes)};
465 bool isPreferredProvider(const Inclusion &Inc,
466 const include_cleaner::Includes &Includes,
467 llvm::ArrayRef<include_cleaner::Header> Providers) {
468 for (const auto &H : Providers) {
469 auto Matches = Includes.match(H);
470 for (const include_cleaner::Include *Match : Matches)
471 if (Match->Line == unsigned(Inc.HashLine + 1))
472 return true; // this header is (equal) best
473 if (!Matches.empty())
474 return false; // another header is better
476 return false; // no header provides the symbol
479 std::vector<Diag>
480 issueIncludeCleanerDiagnostics(ParsedAST &AST, llvm::StringRef Code,
481 const IncludeCleanerFindings &Findings,
482 HeaderFilter IgnoreHeaders) {
483 trace::Span Tracer("IncludeCleaner::issueIncludeCleanerDiagnostics");
484 std::vector<Diag> UnusedIncludes = generateUnusedIncludeDiagnostics(
485 AST.tuPath(), Findings.UnusedIncludes, Code, IgnoreHeaders);
486 std::optional<Fix> RemoveAllUnused = removeAllUnusedIncludes(UnusedIncludes);
488 std::vector<Diag> MissingIncludeDiags = generateMissingIncludeDiagnostics(
489 AST, Findings.MissingIncludes, Code, IgnoreHeaders);
490 std::optional<Fix> AddAllMissing = addAllMissingIncludes(MissingIncludeDiags);
492 std::optional<Fix> FixAll;
493 if (RemoveAllUnused && AddAllMissing)
494 FixAll = fixAll(*RemoveAllUnused, *AddAllMissing);
496 auto AddBatchFix = [](const std::optional<Fix> &F, clang::clangd::Diag *Out) {
497 if (!F)
498 return;
499 Out->Fixes.push_back(*F);
501 for (auto &Diag : MissingIncludeDiags) {
502 AddBatchFix(MissingIncludeDiags.size() > 1 ? AddAllMissing : std::nullopt,
503 &Diag);
504 AddBatchFix(FixAll, &Diag);
506 for (auto &Diag : UnusedIncludes) {
507 AddBatchFix(UnusedIncludes.size() > 1 ? RemoveAllUnused : std::nullopt,
508 &Diag);
509 AddBatchFix(FixAll, &Diag);
512 auto Result = std::move(MissingIncludeDiags);
513 llvm::move(UnusedIncludes, std::back_inserter(Result));
514 return Result;
517 } // namespace clang::clangd