Lines Matching +full:llvm +full:- +full:builddir
1 //===--- ParsedAST.cpp -------------------------------------------*- C++-*-===//
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
7 //===----------------------------------------------------------------------===//
10 #include "../clang-tidy/ClangTidyCheck.h"
11 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
12 #include "../clang-tidy/ClangTidyModule.h"
13 #include "../clang-tidy/ClangTidyModuleRegistry.h"
14 #include "../clang-tidy/ClangTidyOptions.h"
28 #include "clang-include-cleaner/Record.h"
42 #include "clang/Basic/LLVM.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/DenseSet.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/STLFunctionalExtras.h"
65 #include "llvm/ADT/SmallVector.h"
66 #include "llvm/ADT/StringRef.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/MemoryBuffer.h"
79 // Force the linker to link in Clang-tidy modules.
83 #include "../clang-tidy/ClangTidyForceLinker.h"
101 auto &SM = D->getASTContext().getSourceManager();
102 if (!isInsideMainFile(D->getLocation(), SM))
108 // ObjCMethodDecl are not actually top-level decls.
127 CreateASTConsumer(CompilerInstance &CI, llvm::StringRef InFile) override {
137 // However this confuses clang-tidy checks: they don't see any #includes!
138 // So we replay the *non-transitive* #includes that appear in the main-file.
176 // <built-in>
178 // <command-line>
179 // ... macro definitions for args like -Dfoo=bar ...
187 // We insert them right after the built-in header, which still appears.
190 // It'd be nice if there was a better way to identify built-in headers...
192 SM.getBufferOrFake(PrevFID).getBufferIdentifier() == "<built-in>")
202 // Re-lex the #include directive to find its interesting parts.
204 auto HashTok = llvm::partition_point(MainFileTokens,
208 assert(HashTok != MainFileTokens.end() && HashTok->kind() == tok::hash);
220 SynthesizedIncludeTok.setLocation(IncludeTok->location());
221 SynthesizedIncludeTok.setLength(IncludeTok->length());
223 SynthesizedIncludeTok.setRawIdentifierData(IncludeTok->text(SM).data());
229 SynthesizedFilenameTok.setLocation(FileTok->location());
230 // Note that we can't make use of FileTok->length/text in here as in the
238 llvm::StringRef WrittenFilename =
239 llvm::StringRef(Inc.Written).drop_front().drop_back();
240 Delegate->InclusionDirective(
241 HashTok->location(), SynthesizedIncludeTok, WrittenFilename,
249 Delegate->FileSkipped(*File, SynthesizedFilenameTok, Inc.FileKind);
262 // These are check names like clang-diagnostics-unused.
263 // Note that unlike -Wunused, clang-diagnostics-unused does not imply
264 // subcategories like clang-diagnostics-unused-function.
267 // the clang-tidy configuration.
270 // True if we've seen clang-diagnostic-*.
273 // If Default is false, this is foo where we've seen clang-diagnostic-foo.
274 llvm::DenseSet<unsigned> Exceptions;
277 TidyDiagnosticGroups(llvm::StringRef Checks) {
278 constexpr llvm::StringLiteral CDPrefix = "clang-diagnostic-";
280 llvm::StringRef Check;
288 bool Enable = !Check.consume_front("-");
291 // Is this clang-diagnostic-*, or *, or so?
300 // In "*,clang-diagnostic-foo", the latter is a no-op.
303 // The only non-glob entries we care about are clang-diagnostic-foo.
318 // Find -W<group> and -Wno-<group> options in ExtraArgs and apply them to Diags.
320 // This is used to handle ExtraArgs in clang-tidy configuration.
322 // behavior (e.g. we want to exclude these from -Wno-error).
323 void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs,
324 llvm::function_ref<bool(diag::Group)> EnabledGroups,
326 for (llvm::StringRef Group : ExtraArgs) {
327 // Only handle args that are of the form -W[no-]<group>.
329 llvm::SmallVector<diag::kind> Members;
330 if (!Group.consume_front("-W") || Group.empty())
332 bool Enable = !Group.consume_front("no-");
333 if (Diags.getDiagnosticIDs()->getDiagnosticsInGroup(
338 // If -Werror is on, newly added warnings will be treated as errors.
345 auto Group = Diags.getDiagnosticIDs()->getGroupForDiag(ID);
357 // FIXME: there's no API to suppress -Werror for single diagnostics.
358 // In some cases with sub-groups, we may end up erroneously
359 // downgrading diagnostics that were -Werror in the compile command.
365 std::vector<Diag> getIncludeCleanerDiags(ParsedAST &AST, llvm::StringRef Code,
371 Cfg.Diagnostics.Suppress.contains("missing-includes") ||
374 Cfg.Diagnostics.Suppress.contains("unused-includes") ||
405 ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
407 llvm::ArrayRef<Diag> CompilerInvocationDiags,
413 auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
414 if (Preamble && Preamble->StatCache)
415 VFS = Preamble->StatCache->getConsumingFS(std::move(VFS));
419 if (CI->getFrontendOpts().Inputs.size() > 0) {
420 auto Lang = CI->getFrontendOpts().Inputs[0].getKind().getLanguage();
427 // Command-line parsing sets DisableFree to true by default, but we don't want
429 CI->getFrontendOpts().DisableFree = false;
431 Preamble ? &Preamble->Preamble : nullptr;
433 // This is on-by-default in windows to allow parsing SDK headers, but it
434 // breaks many features. Disable it for the main-file (not preamble).
435 CI->getLangOpts().DelayedTemplateParsing = false;
448 L->sawDiagnostic(D, Diag);
453 if (Preamble && Preamble->RequiredModules)
454 Preamble->RequiredModules->adjustHeaderSearchOptions(
455 CI->getHeaderSearchOpts());
464 Patch->apply(*CI);
468 llvm::MemoryBuffer::getMemBufferCopy(Inputs.Contents, Filename), VFS,
487 // If clang-tidy is configured to emit clang warnings, we should too.
489 // Such clang-tidy configuration consists of two parts:
490 // - ExtraArgs: ["-Wfoo"] causes clang to produce the warnings
491 // - Checks: "clang-diagnostic-foo" prevents clang-tidy filtering them out
493 // In clang-tidy, diagnostics are emitted if they pass both checks.
494 // When groups contain subgroups, -Wparent includes the child, but
495 // clang-diagnostic-parent does not.
499 // -- and -Werror, etc. Besides, we've already parsed the command.
500 // Instead we parse the -W<group> flags and handle them directly.
503 // they are generated, as this spreads clang-tidy emulation everywhere.
505 auto &Diags = Clang->getDiagnostics();
507 : llvm::StringRef());
515 const FrontendInputFile &MainInput = Clang->getFrontendOpts().Inputs[0];
516 if (!Action->BeginSourceFile(*Clang, MainInput)) {
522 // mark the main-file as include-guarded.
526 if (Preamble && Preamble->MainIsIncludeGuarded) {
527 const SourceManager &SM = Clang->getSourceManager();
529 Clang->getPreprocessor().getHeaderSearchInfo().MarkFileIncludeOnce(*MainFE);
533 // Clang-tidy has some limitations to ensure reasonable performance:
534 // - checks don't see all preprocessor events in the preamble
535 // - matchers run only over the main-file top-level decls (and can't see
542 auto BuildDir = VFS->getCurrentWorkingDirectory();
544 llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
545 // No need to run clang-tidy or IncludeFixerif we are not going to surface
552 E.instantiate()->addCheckFactories(*CTFactories);
559 CTContext->setDiagnosticsEngine(&Clang->getDiagnostics());
560 CTContext->setASTContext(&Clang->getASTContext());
561 CTContext->setCurrentFile(Filename);
562 CTContext->setSelfContainedDiags(true);
564 Preprocessor *PP = &Clang->getPreprocessor();
566 Check->registerPPCallbacks(Clang->getSourceManager(), PP, PP);
567 Check->registerMatchers(&CTFinder);
580 ID, Clang->getDiagnostics().getDiagnosticLevel(ID, SourceLocation()));
581 Clang->getDiagnostics().setSeverity(ID, diag::Severity::Error,
589 Clang->getLangOpts()))
594 DiagLevel = It->second;
597 std::string CheckName = CTContext->getCheckName(Info.getID());
606 // We let suppression comments take precedence over warning-as-error
607 // to match clang-tidy's behaviour.
612 if (IsInsideMainFile && CTContext->shouldSuppressDiagnostic(
620 if (!CTContext->getOptions().SystemHeaders.value_or(false) &&
625 // Check for warning-as-error.
627 CTContext->treatAsError(CheckName)) {
637 if (Inputs.Index && !BuildDir.getError()) {
641 Filename, Inputs.Contents, Style, BuildDir.get(),
642 &Clang->getPreprocessor().getHeaderSearchInfo(),
646 MainFileIncludes = Preamble->Includes.MainFileIncludes;
647 for (const auto &Inc : Preamble->Includes.MainFileIncludes)
648 Inserter->addExisting(Inc);
654 ? preferredIncludeDirective(Filename, Clang->getLangOpts(),
661 return FixIncludes->fix(DiagLevl, Info);
663 Clang->setExternalSemaSource(FixIncludes->unresolvedNameRecorder());
671 Includes = Preamble->Includes;
672 Includes.MainFileIncludes = Patch->preambleIncludes();
673 // Replay the preamble includes so that clang-tidy checks can see them.
674 ReplayPreamble::attach(Patch->preambleIncludes(), *Clang,
675 Patch->modifiedBounds());
676 PI = *Preamble->Pragmas;
682 // Same for pragma-includes, we're already inheriting preamble includes, so we
683 // should only receive callbacks for non-preamble mainfile includes.
686 // with non-preamble macros below.
690 Macros = Patch->mainFileMacros();
691 Marks = Patch->marks();
693 auto &PP = Clang->getPreprocessor();
699 collectPragmaMarksCallback(Clang->getSourceManager(), Marks));
711 L->beforeExecute(*Clang);
713 if (llvm::Error Err = Action->Execute())
718 // clang-tidy checkers.
719 MacroCollectorPtr->doneParse();
721 // We have to consume the tokens before running clang-tidy to avoid collecting
723 // modernize-use-trailing-return-type does that today).
727 std::vector<Decl *> ParsedDecls = Action->takeTopLevelDecls();
729 Clang->getASTContext().setTraversalScope(ParsedDecls);
731 // Run the AST-dependent part of the clang-tidy checks.
734 CTFinder.matchAST(Clang->getASTContext());
737 // XXX: This is messy: clang-tidy checks flush some diagnostics at EOF.
738 // However Action->EndSourceFile() would destroy the ASTContext!
743 Clang->getDiagnostics().setClient(new IgnoreDiagnostics);
752 llvm::append_range(Diags, Patch->patchedDiags());
762 llvm::move(getIncludeCleanerDiags(Result, Inputs.Contents, *Inputs.TFS),
773 // We already notified the PP of end-of-file earlier, so detach it first.
775 auto PP = Clang->getPreprocessorPtr(); // Keep PP alive for now.
776 Clang->setPreprocessor(nullptr); // Detach so we don't send EOF again.
777 Action->EndSourceFile(); // Destroy ASTContext and Sema.
782 ASTContext &ParsedAST::getASTContext() { return Clang->getASTContext(); }
785 return Clang->getASTContext();
788 Sema &ParsedAST::getSema() { return Clang->getSema(); }
790 Preprocessor &ParsedAST::getPreprocessor() { return Clang->getPreprocessor(); }
793 return Clang->getPreprocessorPtr();
797 return Clang->getPreprocessor();
800 llvm::ArrayRef<Decl *> ParsedAST::getLocalTopLevelDecls() {
804 llvm::ArrayRef<const Decl *> ParsedAST::getLocalTopLevelDecls() const {
818 // FIXME: the rest of the function is almost a direct copy-paste from
832 Total += Ext->getMemoryBufferSizes().malloc_bytes;
837 Total += PRec->getTotalMemory();
847 ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
863 assert(this->Clang);
864 assert(this->Action);
871 std::optional<llvm::StringRef> ParsedAST::preambleVersion() const {
874 return llvm::StringRef(Preamble->Version);
877 llvm::ArrayRef<Diag> ParsedAST::getDiagnostics() const { return Diags; }