diff --git a/clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp b/clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp index 062e236d3e51f..76de8bd877d03 100644 --- a/clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp +++ b/clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp @@ -97,8 +97,7 @@ int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts); // Determine a formatting style from options. auto FormatStyleOrError = format::getStyle(FormatStyleOpt, FormatStyleConfig, diff --git a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp index 2a8fe2d06d185..2efdd9223dfba 100644 --- a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp +++ b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp @@ -128,9 +128,8 @@ int main(int argc, const char **argv) { LangOptions DefaultLangOptions; DiagnosticOptions DiagOpts; clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), DiagOpts); - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &DiagnosticPrinter, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, + &DiagnosticPrinter, false); auto &FileMgr = Tool.getFiles(); SourceManager Sources(Diagnostics, FileMgr); Rewriter Rewrite(Sources, DefaultLangOptions); diff --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp index 2f2fbe0eba472..799e02ffaf3af 100644 --- a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp +++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp @@ -53,7 +53,7 @@ class Action : public clang::ASTFrontendAction { Compiler->createSema(getTranslationUnitKind(), CompletionConsumer); SemaSource->setCompilerInstance(Compiler); - Compiler->getSema().addExternalSource(SemaSource.get()); + Compiler->getSema().addExternalSource(SemaSource); clang::ParseAST(Compiler->getSema(), Compiler->getFrontendOpts().ShowStats, Compiler->getFrontendOpts().SkipFunctionBodies); diff --git a/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp b/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp index 9f73f47998056..568cb2b83d79a 100644 --- a/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp +++ b/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp @@ -454,7 +454,7 @@ int includeFixerMain(int argc, const char **argv) { // Set up a new source manager for applying the resulting replacements. DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics(new DiagnosticIDs, DiagOpts); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts); TextDiagnosticPrinter DiagnosticPrinter(outs(), DiagOpts); SourceManager SM(Diagnostics, tool.getFiles()); Diagnostics.setClient(&DiagnosticPrinter, false); diff --git a/clang-tools-extra/clang-move/tool/ClangMove.cpp b/clang-tools-extra/clang-move/tool/ClangMove.cpp index 750eb952714f7..1be3cb1e3b9ca 100644 --- a/clang-tools-extra/clang-move/tool/ClangMove.cpp +++ b/clang-tools-extra/clang-move/tool/ClangMove.cpp @@ -178,9 +178,8 @@ int main(int argc, const char **argv) { DiagnosticOptions DiagOpts; clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), DiagOpts); - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &DiagnosticPrinter, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, + &DiagnosticPrinter, false); auto &FileMgr = Tool.getFiles(); SourceManager SM(Diagnostics, FileMgr); Rewriter Rewrite(SM, LangOptions()); diff --git a/clang-tools-extra/clang-reorder-fields/tool/ClangReorderFields.cpp b/clang-tools-extra/clang-reorder-fields/tool/ClangReorderFields.cpp index 03502525417b2..fbfce07bb7512 100644 --- a/clang-tools-extra/clang-reorder-fields/tool/ClangReorderFields.cpp +++ b/clang-tools-extra/clang-reorder-fields/tool/ClangReorderFields.cpp @@ -74,9 +74,8 @@ int main(int argc, const char **argv) { LangOptions DefaultLangOptions; DiagnosticOptions DiagOpts; TextDiagnosticPrinter DiagnosticPrinter(errs(), DiagOpts); - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &DiagnosticPrinter, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, + &DiagnosticPrinter, false); auto &FileMgr = Tool.getFiles(); SourceManager Sources(Diagnostics, FileMgr); diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp b/clang-tools-extra/clang-tidy/ClangTidy.cpp index e84be0461f280..4ae2864d310d0 100644 --- a/clang-tools-extra/clang-tidy/ClangTidy.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp @@ -96,8 +96,7 @@ class ErrorReporter { llvm::IntrusiveRefCntPtr BaseFS) : Files(FileSystemOptions(), std::move(BaseFS)), DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), DiagOpts)), - Diags(IntrusiveRefCntPtr(new DiagnosticIDs), DiagOpts, - DiagPrinter), + Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter), SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes) { DiagOpts.ShowColors = Context.getOptions().UseColor.value_or( llvm::sys::Process::StandardOutHasColors()); @@ -570,7 +569,7 @@ runClangTidy(clang::tidy::ClangTidyContext &Context, ClangTidyDiagnosticConsumer DiagConsumer(Context, nullptr, true, ApplyAnyFix); auto DiagOpts = std::make_unique(); - DiagnosticsEngine DE(new DiagnosticIDs(), *DiagOpts, &DiagConsumer, + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, /*ShouldOwnClient=*/false); Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); Tool.setDiagnosticConsumer(&DiagConsumer); diff --git a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp index dd3b80510169b..1e4849cdfd2ae 100644 --- a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp +++ b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp @@ -71,7 +71,7 @@ ExpandModularHeadersPPCallbacks::ExpandModularHeadersPPCallbacks( InMemoryFs(new llvm::vfs::InMemoryFileSystem), Sources(Compiler.getSourceManager()), // Forward the new diagnostics to the original DiagnosticConsumer. - Diags(new DiagnosticIDs, DiagOpts, + Diags(DiagnosticIDs::create(), DiagOpts, new ForwardingDiagnosticConsumer(Compiler.getDiagnosticClient())), LangOpts(Compiler.getLangOpts()), HSOpts(Compiler.getHeaderSearchOpts()) { // Add a FileSystem containing the extra files needed in place of modular diff --git a/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp b/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp index 651a63b3aa972..195418d2e2ca2 100644 --- a/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp +++ b/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp @@ -41,7 +41,7 @@ class ClangTidyPluginAction : public PluginASTAction { new ClangTidyDiagnosticConsumer(*Context, &Compiler.getDiagnostics()); auto DiagOpts = std::make_unique(); auto DiagEngine = std::make_unique( - new DiagnosticIDs, *DiagOpts, DiagConsumer); + DiagnosticIDs::create(), *DiagOpts, DiagConsumer); Context->setDiagnosticsEngine(std::move(DiagOpts), DiagEngine.get()); // Create the AST consumer. diff --git a/clang-tools-extra/clangd/Preamble.cpp b/clang-tools-extra/clangd/Preamble.cpp index 7b4d63ff197e7..8af9e4649218d 100644 --- a/clang-tools-extra/clangd/Preamble.cpp +++ b/clang-tools-extra/clangd/Preamble.cpp @@ -659,7 +659,7 @@ buildPreamble(PathRef FileName, CompilerInvocation CI, WallTimer PreambleTimer; PreambleTimer.startTimer(); auto BuiltPreamble = PrecompiledPreamble::Build( - CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine, + CI, ContentsBuffer.get(), Bounds, PreambleDiagsEngine, Stats ? TimedFS : StatCacheFS, std::make_shared(), StoreInMemory, /*StoragePath=*/"", CapturedInfo); diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp index b4f0c4f765c2f..4a5cd3bb78b2f 100644 --- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp +++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp @@ -254,7 +254,7 @@ bool isValidTarget(llvm::StringRef Triple) { std::shared_ptr TargetOpts(new TargetOptions); TargetOpts->Triple = Triple.str(); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer); llvm::IntrusiveRefCntPtr Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); diff --git a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp index 75d0ff244038d..0e411b2034178 100644 --- a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp +++ b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp @@ -299,7 +299,7 @@ TEST_F(ConfigCompileTests, DiagnosticSuppression) { "typecheck_bool_condition", "unexpected_friend", "warn_alloca")); clang::DiagnosticOptions DiagOpts; - clang::DiagnosticsEngine DiagEngine(new DiagnosticIDs, DiagOpts, + clang::DiagnosticsEngine DiagEngine(DiagnosticIDs::create(), DiagOpts, new clang::IgnoringDiagConsumer); using Diag = clang::Diagnostic; diff --git a/clang-tools-extra/clangd/unittests/tweaks/TweakTests.cpp b/clang-tools-extra/clangd/unittests/tweaks/TweakTests.cpp index e39b70224d97c..b6607e940a62f 100644 --- a/clang-tools-extra/clangd/unittests/tweaks/TweakTests.cpp +++ b/clang-tools-extra/clangd/unittests/tweaks/TweakTests.cpp @@ -45,7 +45,7 @@ TEST(FileEdits, AbsolutePath) { MemFS->addFile(Path, 0, llvm::MemoryBuffer::getMemBuffer("", Path)); FileManager FM(FileSystemOptions(), MemFS); DiagnosticOptions DiagOpts; - DiagnosticsEngine DE(new DiagnosticIDs, DiagOpts); + DiagnosticsEngine DE(DiagnosticIDs::create(), DiagOpts); SourceManager SM(DE, FM); for (const auto *Path : RelPaths) { diff --git a/clang-tools-extra/modularize/ModularizeUtilities.cpp b/clang-tools-extra/modularize/ModularizeUtilities.cpp index e66f2058e6617..8916ef4d1f649 100644 --- a/clang-tools-extra/modularize/ModularizeUtilities.cpp +++ b/clang-tools-extra/modularize/ModularizeUtilities.cpp @@ -47,7 +47,7 @@ ModularizeUtilities::ModularizeUtilities(std::vector &InputPaths, ProblemFilesPath(ProblemFilesListPath), HasModuleMap(false), MissingHeaderCount(0), // Init clang stuff needed for loading the module map and preprocessing. - LangOpts(new LangOptions()), DiagIDs(new DiagnosticIDs()), + LangOpts(new LangOptions()), DiagIDs(DiagnosticIDs::create()), DC(llvm::errs(), DiagnosticOpts), Diagnostics(new DiagnosticsEngine(DiagIDs, DiagnosticOpts, &DC, false)), TargetOpts(new ModuleMapTargetOptions()), diff --git a/clang-tools-extra/unittests/clang-apply-replacements/ApplyReplacementsTest.cpp b/clang-tools-extra/unittests/clang-apply-replacements/ApplyReplacementsTest.cpp index 87b0d69f4654a..0b9211893a013 100644 --- a/clang-tools-extra/unittests/clang-apply-replacements/ApplyReplacementsTest.cpp +++ b/clang-tools-extra/unittests/clang-apply-replacements/ApplyReplacementsTest.cpp @@ -33,8 +33,7 @@ makeTUDiagnostics(const std::string &MainSourceFile, StringRef DiagnosticName, // before applying. TEST(ApplyReplacementsTest, mergeDiagnosticsWithNoFixes) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts); FileManager Files((FileSystemOptions())); SourceManager SM(Diagnostics, Files); TUReplacements TURs; diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp index d3ca26a19dd63..410cebf90913d 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp @@ -318,7 +318,8 @@ TEST(CheckOptionsValidation, MissingOptions) { ClangTidyGlobalOptions(), Options)); ClangTidyDiagnosticConsumer DiagConsumer(Context); auto DiagOpts = std::make_unique(); - DiagnosticsEngine DE(new DiagnosticIDs(), *DiagOpts, &DiagConsumer, false); + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, + false); Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); TestCheck TestCheck(&Context); EXPECT_FALSE(TestCheck.getLocal("Opt")); @@ -348,7 +349,8 @@ TEST(CheckOptionsValidation, ValidIntOptions) { ClangTidyGlobalOptions(), Options)); ClangTidyDiagnosticConsumer DiagConsumer(Context); auto DiagOpts = std::make_unique(); - DiagnosticsEngine DE(new DiagnosticIDs(), *DiagOpts, &DiagConsumer, false); + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, + false); Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); TestCheck TestCheck(&Context); @@ -410,7 +412,8 @@ TEST(ValidConfiguration, ValidEnumOptions) { ClangTidyGlobalOptions(), Options)); ClangTidyDiagnosticConsumer DiagConsumer(Context); auto DiagOpts = std::make_unique(); - DiagnosticsEngine DE(new DiagnosticIDs(), *DiagOpts, &DiagConsumer, false); + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, + false); Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); TestCheck TestCheck(&Context); diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h index 789cc2afb4f0c..89f0f9f2a1f19 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h @@ -97,7 +97,8 @@ runCheckOnCode(StringRef Code, std::vector *Errors = nullptr, ClangTidyGlobalOptions(), Options)); ClangTidyDiagnosticConsumer DiagConsumer(Context); auto DiagOpts = std::make_unique(); - DiagnosticsEngine DE(new DiagnosticIDs(), *DiagOpts, &DiagConsumer, false); + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, + false); Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); std::vector Args(1, "clang-tidy"); diff --git a/clang-tools-extra/unittests/include/common/VirtualFileHelper.h b/clang-tools-extra/unittests/include/common/VirtualFileHelper.h index 86991bb343d8d..cb075f8b77355 100644 --- a/clang-tools-extra/unittests/include/common/VirtualFileHelper.h +++ b/clang-tools-extra/unittests/include/common/VirtualFileHelper.h @@ -32,8 +32,7 @@ class VirtualFileHelper { public: VirtualFileHelper() - : Diagnostics(IntrusiveRefCntPtr(new DiagnosticIDs), - DiagOpts), + : Diagnostics(DiagnosticIDs::create(), DiagOpts), DiagnosticPrinter(llvm::outs(), DiagOpts), Files((FileSystemOptions())) {} diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index ebe539bca7909..b0abb491fc3fc 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -1385,6 +1385,12 @@ class ASTContext : public RefCountedBase { return ExternalSource.get(); } + /// Retrieve a pointer to the external AST source associated + /// with this AST context, if any. Returns as an IntrusiveRefCntPtr. + IntrusiveRefCntPtr getExternalSourcePtr() const { + return ExternalSource; + } + /// Attach an AST mutation listener to the AST context. /// /// The AST mutation listener provides the ability to track modifications to diff --git a/clang/include/clang/Basic/DiagnosticIDs.h b/clang/include/clang/Basic/DiagnosticIDs.h index 6ebb7aeb828b7..2f256ae6b22bf 100644 --- a/clang/include/clang/Basic/DiagnosticIDs.h +++ b/clang/include/clang/Basic/DiagnosticIDs.h @@ -281,6 +281,11 @@ class DiagnosticIDs : public RefCountedBase { DiagnosticIDs(); ~DiagnosticIDs(); + // Convenience method to construct a new refcounted DiagnosticIDs. + static llvm::IntrusiveRefCntPtr create() { + return llvm::makeIntrusiveRefCnt(); + } + /// Return an ID for a diagnostic with the specified format string and /// level. /// diff --git a/clang/include/clang/Frontend/ASTUnit.h b/clang/include/clang/Frontend/ASTUnit.h index d86fb4c46cc60..28ab3779f1509 100644 --- a/clang/include/clang/Frontend/ASTUnit.h +++ b/clang/include/clang/Frontend/ASTUnit.h @@ -443,9 +443,15 @@ class ASTUnit { const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; } DiagnosticsEngine &getDiagnostics() { return *Diagnostics; } + llvm::IntrusiveRefCntPtr getDiagnosticsPtr() { + return Diagnostics; + } const SourceManager &getSourceManager() const { return *SourceMgr; } SourceManager &getSourceManager() { return *SourceMgr; } + llvm::IntrusiveRefCntPtr getSourceManagerPtr() { + return SourceMgr; + } const Preprocessor &getPreprocessor() const { return *PP; } Preprocessor &getPreprocessor() { return *PP; } @@ -453,8 +459,11 @@ class ASTUnit { const ASTContext &getASTContext() const { return *Ctx; } ASTContext &getASTContext() { return *Ctx; } + llvm::IntrusiveRefCntPtr getASTContextPtr() { return Ctx; } - void setASTContext(ASTContext *ctx) { Ctx = ctx; } + void setASTContext(llvm::IntrusiveRefCntPtr ctx) { + Ctx = std::move(ctx); + } void setPreprocessor(std::shared_ptr pp); /// Enable source-range based diagnostic messages. @@ -495,6 +504,7 @@ class ASTUnit { const FileManager &getFileManager() const { return *FileMgr; } FileManager &getFileManager() { return *FileMgr; } + IntrusiveRefCntPtr getFileManagerPtr() { return FileMgr; } const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; } @@ -802,8 +812,8 @@ class ASTUnit { std::shared_ptr CI, std::shared_ptr PCHContainerOps, std::shared_ptr DiagOpts, - IntrusiveRefCntPtr Diags, FileManager *FileMgr, - bool OnlyLocalDecls = false, + IntrusiveRefCntPtr Diags, + IntrusiveRefCntPtr FileMgr, bool OnlyLocalDecls = false, CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None, unsigned PrecompilePreambleAfterNParses = 0, TranslationUnitKind TUKind = TU_Complete, @@ -920,8 +930,10 @@ class ASTUnit { bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr PCHContainerOps, - DiagnosticsEngine &Diag, LangOptions &LangOpts, - SourceManager &SourceMgr, FileManager &FileMgr, + llvm::IntrusiveRefCntPtr Diag, + LangOptions &LangOpts, + llvm::IntrusiveRefCntPtr SourceMgr, + llvm::IntrusiveRefCntPtr FileMgr, SmallVectorImpl &StoredDiagnostics, SmallVectorImpl &OwnedBuffers, std::unique_ptr Act); diff --git a/clang/include/clang/Frontend/CompilerInstance.h b/clang/include/clang/Frontend/CompilerInstance.h index 6476d90066872..0ed1455335e17 100644 --- a/clang/include/clang/Frontend/CompilerInstance.h +++ b/clang/include/clang/Frontend/CompilerInstance.h @@ -398,7 +398,7 @@ class CompilerInstance : public ModuleLoader { } /// setDiagnostics - Replace the current diagnostics engine. - void setDiagnostics(DiagnosticsEngine *Value); + void setDiagnostics(llvm::IntrusiveRefCntPtr Value); DiagnosticConsumer &getDiagnosticClient() const { assert(Diagnostics && Diagnostics->getClient() && @@ -504,8 +504,8 @@ class CompilerInstance : public ModuleLoader { FileMgr.resetWithoutRelease(); } - /// Replace the current file manager. - void setFileManager(FileManager *Value); + /// Replace the current file manager and virtual file system. + void setFileManager(IntrusiveRefCntPtr Value); /// @} /// @name Output Manager @@ -549,7 +549,7 @@ class CompilerInstance : public ModuleLoader { } /// setSourceManager - Replace the current source manager. - void setSourceManager(SourceManager *Value); + void setSourceManager(llvm::IntrusiveRefCntPtr Value); /// @} /// @name Preprocessor @@ -594,7 +594,7 @@ class CompilerInstance : public ModuleLoader { } /// setASTContext - Replace the current AST context. - void setASTContext(ASTContext *Value); + void setASTContext(llvm::IntrusiveRefCntPtr Value); /// Replace the current Sema; the compiler instance takes ownership /// of S. diff --git a/clang/include/clang/Frontend/PrecompiledPreamble.h b/clang/include/clang/Frontend/PrecompiledPreamble.h index 624df004bf89e..565395b4f3986 100644 --- a/clang/include/clang/Frontend/PrecompiledPreamble.h +++ b/clang/include/clang/Frontend/PrecompiledPreamble.h @@ -84,7 +84,7 @@ class PrecompiledPreamble { static llvm::ErrorOr Build(const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr Diagnostics, IntrusiveRefCntPtr VFS, std::shared_ptr PCHContainerOps, bool StoreInMemory, StringRef StoragePath, diff --git a/clang/include/clang/Frontend/Utils.h b/clang/include/clang/Frontend/Utils.h index 18bf21c147bde..c1067964160e2 100644 --- a/clang/include/clang/Frontend/Utils.h +++ b/clang/include/clang/Frontend/Utils.h @@ -199,7 +199,7 @@ void AttachHeaderIncludeGen(Preprocessor &PP, /// memory, mainly for testing. IntrusiveRefCntPtr createChainedIncludesSource(CompilerInstance &CI, - IntrusiveRefCntPtr &Reader); + IntrusiveRefCntPtr &OutReader); /// Optional inputs to createInvocation. struct CreateInvocationOptions { diff --git a/clang/include/clang/Sema/MultiplexExternalSemaSource.h b/clang/include/clang/Sema/MultiplexExternalSemaSource.h index 391c2177d75ec..8bcaa121b3039 100644 --- a/clang/include/clang/Sema/MultiplexExternalSemaSource.h +++ b/clang/include/clang/Sema/MultiplexExternalSemaSource.h @@ -40,7 +40,7 @@ class MultiplexExternalSemaSource : public ExternalSemaSource { static char ID; private: - SmallVector Sources; + SmallVector, 2> Sources; public: /// Constructs a new multiplexing external sema source and appends the @@ -49,15 +49,14 @@ class MultiplexExternalSemaSource : public ExternalSemaSource { ///\param[in] S1 - A non-null (old) ExternalSemaSource. ///\param[in] S2 - A non-null (new) ExternalSemaSource. /// - MultiplexExternalSemaSource(ExternalSemaSource *S1, ExternalSemaSource *S2); - - ~MultiplexExternalSemaSource() override; + MultiplexExternalSemaSource(llvm::IntrusiveRefCntPtr S1, + llvm::IntrusiveRefCntPtr S2); /// Appends new source to the source list. /// ///\param[in] Source - An ExternalSemaSource. /// - void AddSource(ExternalSemaSource *Source); + void AddSource(llvm::IntrusiveRefCntPtr Source); //===--------------------------------------------------------------------===// // ExternalASTSource. diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index d691cda9bb8a8..98ac143bf1dcb 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -1136,7 +1136,7 @@ class Sema final : public SemaBase { /// ///\param[in] E - A non-null external sema source. /// - void addExternalSource(ExternalSemaSource *E); + void addExternalSource(IntrusiveRefCntPtr E); /// Print out statistics about the semantic analysis. void PrintStats() const; diff --git a/clang/lib/Basic/SourceManager.cpp b/clang/lib/Basic/SourceManager.cpp index b2b1488f9dc8e..45f90cc31339e 100644 --- a/clang/lib/Basic/SourceManager.cpp +++ b/clang/lib/Basic/SourceManager.cpp @@ -2381,8 +2381,8 @@ SourceManagerForFile::SourceManagerForFile(StringRef FileName, DiagOpts = std::make_unique(); // This is passed to `SM` as reference, so the pointer has to be referenced // by `Environment` due to the same reason above. - Diagnostics = std::make_unique( - IntrusiveRefCntPtr(new DiagnosticIDs), *DiagOpts); + Diagnostics = + std::make_unique(DiagnosticIDs::create(), *DiagOpts); SourceMgr = std::make_unique(*Diagnostics, *FileMgr); FileEntryRef FE = llvm::cantFail(FileMgr->getFileRef(FileName)); FileID ID = diff --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp b/clang/lib/CrossTU/CrossTranslationUnit.cpp index a3fe2f4325e9c..847913d4b03fd 100644 --- a/clang/lib/CrossTU/CrossTranslationUnit.cpp +++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp @@ -573,9 +573,8 @@ CrossTranslationUnitContext::ASTLoader::loadFromDump(StringRef ASTDumpPath) { auto DiagOpts = std::make_shared(); TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), *DiagOpts); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr Diags( - new DiagnosticsEngine(DiagID, *DiagOpts, DiagClient)); + auto Diags = llvm::makeIntrusiveRefCnt( + DiagnosticIDs::create(), *DiagOpts, DiagClient); return ASTUnit::LoadFromASTFile( ASTDumpPath, CI.getPCHContainerOperations()->getRawReader(), ASTUnit::LoadEverything, CI.getVirtualFileSystemPtr(), DiagOpts, Diags, @@ -617,8 +616,8 @@ CrossTranslationUnitContext::ASTLoader::loadFromSource( auto *DiagClient = new ForwardingDiagnosticConsumer{CI.getDiagnosticClient()}; IntrusiveRefCntPtr DiagID{ CI.getDiagnostics().getDiagnosticIDs()}; - IntrusiveRefCntPtr Diags( - new DiagnosticsEngine{DiagID, *DiagOpts, DiagClient}); + auto Diags = llvm::makeIntrusiveRefCnt(DiagID, *DiagOpts, + DiagClient); return ASTUnit::LoadFromCommandLine( CommandLineArgs.begin(), (CommandLineArgs.end()), diff --git a/clang/lib/Frontend/ASTMerge.cpp b/clang/lib/Frontend/ASTMerge.cpp index 51925ec85e7b6..0dff69d613bcf 100644 --- a/clang/lib/Frontend/ASTMerge.cpp +++ b/clang/lib/Frontend/ASTMerge.cpp @@ -41,10 +41,10 @@ void ASTMergeAction::ExecuteAction() { auto SharedState = std::make_shared( *CI.getASTContext().getTranslationUnitDecl()); for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) { - IntrusiveRefCntPtr Diags(new DiagnosticsEngine( + auto Diags = llvm::makeIntrusiveRefCnt( DiagIDs, CI.getDiagnosticOpts(), new ForwardingDiagnosticConsumer(*CI.getDiagnostics().getClient()), - /*ShouldOwnClient=*/true)); + /*ShouldOwnClient=*/true); std::unique_ptr Unit = ASTUnit::LoadFromASTFile( ASTFiles[I], CI.getPCHContainerReader(), ASTUnit::LoadEverything, CI.getVirtualFileSystemPtr(), nullptr, Diags, CI.getFileSystemOpts(), diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index 009b84f03a08c..06ab9930a5861 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -823,11 +823,10 @@ std::unique_ptr ASTUnit::LoadFromASTFile( AST->CaptureDiagnostics = CaptureDiagnostics; AST->DiagOpts = DiagOpts; AST->Diagnostics = Diags; - AST->FileMgr = new FileManager(FileSystemOpts, VFS); + AST->FileMgr = llvm::makeIntrusiveRefCnt(FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; - AST->SourceMgr = new SourceManager(AST->getDiagnostics(), - AST->getFileManager(), - UserFilesAreVolatile); + AST->SourceMgr = llvm::makeIntrusiveRefCnt( + AST->getDiagnostics(), AST->getFileManager(), UserFilesAreVolatile); AST->ModCache = createCrossProcessModuleCache(); AST->HSOpts = std::make_unique(HSOpts); AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormats().front()); @@ -850,17 +849,19 @@ std::unique_ptr ASTUnit::LoadFromASTFile( Preprocessor &PP = *AST->PP; if (ToLoad >= LoadASTOnly) - AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(), - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo(), - AST->getTranslationUnitKind()); + AST->Ctx = llvm::makeIntrusiveRefCnt( + *AST->LangOpts, AST->getSourceManager(), PP.getIdentifierTable(), + PP.getSelectorTable(), PP.getBuiltinInfo(), + AST->getTranslationUnitKind()); DisableValidationForModuleKind disableValid = DisableValidationForModuleKind::None; if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) disableValid = DisableValidationForModuleKind::All; - AST->Reader = new ASTReader( - PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, {}, /*isysroot=*/"", + AST->Reader = llvm::makeIntrusiveRefCnt( + PP, *AST->ModCache, AST->Ctx.get(), PCHContainerRdr, + ArrayRef>(), + /*isysroot=*/"", /*DisableValidationKind=*/disableValid, AllowASTWithCompilerErrors); unsigned Counter = 0; @@ -1182,11 +1183,11 @@ bool ASTUnit::Parse(std::shared_ptr PCHContainerOps, // createFileManager to create one. if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS) { Clang->setVirtualFileSystem(std::move(VFS)); - Clang->setFileManager(&*FileMgr); + Clang->setFileManager(FileMgr); } else { Clang->setVirtualFileSystem(std::move(VFS)); Clang->createFileManager(); - FileMgr = Clang->getFileManagerPtr().get(); + FileMgr = Clang->getFileManagerPtr(); } // Recover resources if we crash before exiting this method. @@ -1198,7 +1199,7 @@ bool ASTUnit::Parse(std::shared_ptr PCHContainerOps, // Set up diagnostics, capturing any diagnostics that would // otherwise be dropped. - Clang->setDiagnostics(&getDiagnostics()); + Clang->setDiagnostics(getDiagnosticsPtr()); // Create the target instance. if (!Clang->createTarget()) @@ -1220,15 +1221,15 @@ bool ASTUnit::Parse(std::shared_ptr PCHContainerOps, ResetForParse(); - SourceMgr = new SourceManager(getDiagnostics(), *FileMgr, - UserFilesAreVolatile); + SourceMgr = llvm::makeIntrusiveRefCnt( + getDiagnostics(), *FileMgr, +UserFilesAreVolatile); if (!OverrideMainBuffer) { checkAndRemoveNonDriverDiags(StoredDiagnostics); TopLevelDeclsInPreamble.clear(); } // Create the source manager. - Clang->setSourceManager(&getSourceManager()); + Clang->setSourceManager(getSourceManagerPtr()); // If the main file has been overridden due to the use of a preamble, // make that override happen and introduce the preamble. @@ -1418,7 +1419,7 @@ ASTUnit::getMainBufferWithPrecompiledPreamble( PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true; llvm::ErrorOr NewPreamble = PrecompiledPreamble::Build( - PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS, + PreambleInvocationIn, MainFileBuffer.get(), Bounds, Diagnostics, VFS, PCHContainerOps, StorePreamblesInMemory, PreambleStoragePath, Callbacks); @@ -1493,13 +1494,13 @@ void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { TheSema = CI.takeSema(); Consumer = CI.takeASTConsumer(); if (CI.hasASTContext()) - Ctx = &CI.getASTContext(); + Ctx = CI.getASTContextPtr(); if (CI.hasPreprocessor()) PP = CI.getPreprocessorPtr(); CI.setSourceManager(nullptr); CI.setFileManager(nullptr); if (CI.hasTarget()) - Target = &CI.getTarget(); + Target = CI.getTargetPtr(); Reader = CI.getASTReader(); HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); if (Invocation != CI.getInvocationPtr()) { @@ -1549,10 +1550,11 @@ ASTUnit::create(std::shared_ptr CI, AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); AST->Invocation = std::move(CI); - AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); + AST->FileMgr = + llvm::makeIntrusiveRefCnt(AST->FileSystemOpts, VFS); AST->UserFilesAreVolatile = UserFilesAreVolatile; - AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr, - UserFilesAreVolatile); + AST->SourceMgr = llvm::makeIntrusiveRefCnt( + AST->getDiagnostics(), *AST->FileMgr, UserFilesAreVolatile); AST->ModCache = createCrossProcessModuleCache(); return AST; @@ -1618,7 +1620,7 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( // Set up diagnostics, capturing any diagnostics that would // otherwise be dropped. - Clang->setDiagnostics(&AST->getDiagnostics()); + Clang->setDiagnostics(AST->getDiagnosticsPtr()); // Create the target instance. if (!Clang->createTarget()) @@ -1641,10 +1643,10 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( // Create a file manager object to provide access to and cache the filesystem. Clang->setVirtualFileSystem(AST->getVirtualFileSystemPtr()); - Clang->setFileManager(&AST->getFileManager()); + Clang->setFileManager(AST->getFileManagerPtr()); // Create the source manager. - Clang->setSourceManager(&AST->getSourceManager()); + Clang->setSourceManager(AST->getSourceManagerPtr()); FrontendAction *Act = Action; @@ -1738,8 +1740,9 @@ std::unique_ptr ASTUnit::LoadFromCompilerInvocation( std::shared_ptr CI, std::shared_ptr PCHContainerOps, std::shared_ptr DiagOpts, - IntrusiveRefCntPtr Diags, FileManager *FileMgr, - bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics, + IntrusiveRefCntPtr Diags, + IntrusiveRefCntPtr FileMgr, bool OnlyLocalDecls, + CaptureDiagsKind CaptureDiagnostics, unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind, bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) { @@ -1846,7 +1849,8 @@ std::unique_ptr ASTUnit::LoadFromCommandLine( AST->Diagnostics = Diags; AST->FileSystemOpts = CI->getFileSystemOpts(); VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS); - AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS); + AST->FileMgr = + llvm::makeIntrusiveRefCnt(AST->FileSystemOpts, VFS); AST->StorePreamblesInMemory = StorePreamblesInMemory; AST->PreambleStoragePath = PreambleStoragePath; AST->ModCache = createCrossProcessModuleCache(); @@ -2206,8 +2210,10 @@ void ASTUnit::CodeComplete( bool IncludeCodePatterns, bool IncludeBriefComments, CodeCompleteConsumer &Consumer, std::shared_ptr PCHContainerOps, - DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, - FileManager &FileMgr, SmallVectorImpl &StoredDiagnostics, + llvm::IntrusiveRefCntPtr Diag, LangOptions &LangOpts, + llvm::IntrusiveRefCntPtr SourceMgr, + llvm::IntrusiveRefCntPtr FileMgr, + SmallVectorImpl &StoredDiagnostics, SmallVectorImpl &OwnedBuffers, std::unique_ptr Act) { if (!Invocation) @@ -2256,12 +2262,12 @@ void ASTUnit::CodeComplete( std::string(Clang->getFrontendOpts().Inputs[0].getFile()); // Set up diagnostics, capturing any diagnostics produced. - Clang->setDiagnostics(&Diag); + Clang->setDiagnostics(Diag); CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All, Clang->getDiagnostics(), &StoredDiagnostics, nullptr); - ProcessWarningOptions(Diag, Inv.getDiagnosticOpts(), - FileMgr.getVirtualFileSystem()); + ProcessWarningOptions(*Diag, Inv.getDiagnosticOpts(), + FileMgr->getVirtualFileSystem()); // Create the target instance. if (!Clang->createTarget()) { @@ -2278,9 +2284,9 @@ void ASTUnit::CodeComplete( "IR inputs not support here!"); // Use the source and file managers that we were given. - Clang->setVirtualFileSystem(FileMgr.getVirtualFileSystemPtr()); - Clang->setFileManager(&FileMgr); - Clang->setSourceManager(&SourceMgr); + Clang->setVirtualFileSystem(FileMgr->getVirtualFileSystemPtr()); + Clang->setFileManager(FileMgr); + Clang->setSourceManager(SourceMgr); // Remap files. PreprocessorOpts.clearRemappedFiles(); @@ -2298,7 +2304,7 @@ void ASTUnit::CodeComplete( auto getUniqueID = [&FileMgr](StringRef Filename) -> std::optional { - if (auto Status = FileMgr.getVirtualFileSystem().status(Filename)) + if (auto Status = FileMgr->getVirtualFileSystem().status(Filename)) return Status->getUniqueID(); return std::nullopt; }; @@ -2319,7 +2325,8 @@ void ASTUnit::CodeComplete( std::unique_ptr OverrideMainBuffer; if (Preamble && Line > 1 && hasSameUniqueID(File, OriginalSourceFile)) { OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( - PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1); + PCHContainerOps, Inv, FileMgr->getVirtualFileSystemPtr(), false, + Line - 1); } // If the main file has been overridden due to the use of a preamble, @@ -2329,7 +2336,7 @@ void ASTUnit::CodeComplete( "No preamble was built, but OverrideMainBuffer is not null"); IntrusiveRefCntPtr VFS = - &FileMgr.getVirtualFileSystem(); + FileMgr->getVirtualFileSystemPtr(); Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS, OverrideMainBuffer.get()); // FIXME: there is no way to update VFS if it was changed by diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp b/clang/lib/Frontend/ChainedIncludesSource.cpp index 990fb3c32a3d0..89dca7f7aa804 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -53,17 +53,16 @@ class ChainedIncludesSource : public ExternalSemaSource { }; } // end anonymous namespace -static ASTReader * +static llvm::IntrusiveRefCntPtr createASTReader(CompilerInstance &CI, StringRef pchFile, SmallVectorImpl> &MemBufs, SmallVectorImpl &bufNames, ASTDeserializationListener *deserialListener = nullptr) { Preprocessor &PP = CI.getPreprocessor(); - std::unique_ptr Reader; - Reader.reset(new ASTReader( + auto Reader = llvm::makeIntrusiveRefCnt( PP, CI.getModuleCache(), &CI.getASTContext(), CI.getPCHContainerReader(), - /*Extensions=*/{}, - /*isysroot=*/"", DisableValidationForModuleKind::PCH)); + /*Extensions=*/ArrayRef>(), + /*isysroot=*/"", DisableValidationForModuleKind::PCH); for (unsigned ti = 0; ti < bufNames.size(); ++ti) { StringRef sr(bufNames[ti]); Reader->addInMemoryBuffer(sr, std::move(MemBufs[ti])); @@ -74,7 +73,7 @@ createASTReader(CompilerInstance &CI, StringRef pchFile, case ASTReader::Success: // Set the predefines buffer as suggested by the PCH reader. PP.setPredefines(Reader->getSuggestedPredefines()); - return Reader.release(); + return Reader; case ASTReader::Failure: case ASTReader::Missing: @@ -87,8 +86,9 @@ createASTReader(CompilerInstance &CI, StringRef pchFile, return nullptr; } -IntrusiveRefCntPtr clang::createChainedIncludesSource( - CompilerInstance &CI, IntrusiveRefCntPtr &Reader) { +IntrusiveRefCntPtr +clang::createChainedIncludesSource(CompilerInstance &CI, + IntrusiveRefCntPtr &OutReader) { std::vector &includes = CI.getPreprocessorOpts().ChainedIncludes; assert(!includes.empty() && "No '-chain-include' in options!"); @@ -118,14 +118,13 @@ IntrusiveRefCntPtr clang::createChainedIncludesSource( TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), CI.getDiagnosticOpts()); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr Diags( - new DiagnosticsEngine(DiagID, CI.getDiagnosticOpts(), DiagClient)); + auto Diags = llvm::makeIntrusiveRefCnt( + DiagnosticIDs::create(), CI.getDiagnosticOpts(), DiagClient); auto Clang = std::make_unique( std::move(CInvok), CI.getPCHContainerOperations()); Clang->createVirtualFileSystem(); - Clang->setDiagnostics(Diags.get()); + Clang->setDiagnostics(Diags); Clang->setTarget(TargetInfo::CreateTargetInfo( Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts())); Clang->createFileManager(); @@ -187,12 +186,12 @@ IntrusiveRefCntPtr clang::createChainedIncludesSource( assert(!SerialBufs.empty()); std::string pchName = includes.back() + ".pch-final"; serialBufNames.push_back(pchName); - Reader = createASTReader(CI, pchName, SerialBufs, serialBufNames); - if (!Reader) + OutReader = createASTReader(CI, pchName, SerialBufs, serialBufNames); + if (!OutReader) return nullptr; auto ChainedSrc = llvm::makeIntrusiveRefCnt(std::move(CIs)); return llvm::makeIntrusiveRefCnt( - ChainedSrc.get(), Reader.get()); + std::move(ChainedSrc), OutReader); } diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index 037567b0ec98a..9ace84ff4f0c9 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -98,8 +98,9 @@ bool CompilerInstance::shouldBuildGlobalModuleIndex() const { !DisableGeneratingGlobalModuleIndex; } -void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { - Diagnostics = Value; +void CompilerInstance::setDiagnostics( + llvm::IntrusiveRefCntPtr Value) { + Diagnostics = std::move(Value); } bool CompilerInstance::isSourceNonReproducible() const { @@ -172,22 +173,24 @@ bool CompilerInstance::createTarget() { return true; } -void CompilerInstance::setFileManager(FileManager *Value) { +void CompilerInstance::setFileManager(IntrusiveRefCntPtr Value) { assert(Value == nullptr || getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr()); - FileMgr = Value; + FileMgr = std::move(Value); } -void CompilerInstance::setSourceManager(SourceManager *Value) { - SourceMgr = Value; +void CompilerInstance::setSourceManager( + llvm::IntrusiveRefCntPtr Value) { + SourceMgr = std::move(Value); } void CompilerInstance::setPreprocessor(std::shared_ptr Value) { PP = std::move(Value); } -void CompilerInstance::setASTContext(ASTContext *Value) { - Context = Value; +void CompilerInstance::setASTContext( + llvm::IntrusiveRefCntPtr Value) { + Context = std::move(Value); if (Context && Consumer) getASTConsumer().Initialize(getASTContext()); @@ -288,7 +291,7 @@ static void collectVFSEntries(CompilerInstance &CI, void CompilerInstance::createVirtualFileSystem( IntrusiveRefCntPtr BaseFS, DiagnosticConsumer *DC) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts, DC, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC, /*ShouldOwnClient=*/false); std::tie(CAS, ActionCache) = @@ -364,9 +367,8 @@ IntrusiveRefCntPtr CompilerInstance::createDiagnostics( llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts, DiagnosticConsumer *Client, bool ShouldOwnClient, const CodeGenOptions *CodeGenOpts) { - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr Diags( - new DiagnosticsEngine(DiagID, Opts)); + auto Diags = llvm::makeIntrusiveRefCnt( + DiagnosticIDs::create(), Opts); // Create the diagnostic client for reporting errors or for // implementing -verify. @@ -406,7 +408,7 @@ void CompilerInstance::createFileManager() { void CompilerInstance::createSourceManager() { assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager"); assert(FileMgr && "FileManager needed for creating SourceManager"); - SourceMgr = new SourceManager(getDiagnostics(), + SourceMgr = llvm::makeIntrusiveRefCnt(getDiagnostics(), getFileManager()); } @@ -576,11 +578,11 @@ std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) { void CompilerInstance::createASTContext() { Preprocessor &PP = getPreprocessor(); - auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), - PP.getIdentifierTable(), PP.getSelectorTable(), - PP.getBuiltinInfo(), PP.TUKind); + auto Context = llvm::makeIntrusiveRefCnt( + getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(), + PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind); Context->InitBuiltinTypes(getTarget(), getAuxTarget()); - setASTContext(Context); + setASTContext(std::move(Context)); } // ExternalASTSource @@ -685,17 +687,17 @@ IntrusiveRefCntPtr CompilerInstance::createPCHExternalASTSource( const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); - IntrusiveRefCntPtr Reader(new ASTReader( + auto Reader = llvm::makeIntrusiveRefCnt( PP, ModCache, &Context, PCHContainerRdr, Extensions, Sysroot.empty() ? "" : Sysroot.data(), DisableValidation, AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, HSOpts.ModulesValidateSystemHeaders, HSOpts.ModulesForceValidateUserHeaders, - HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex)); + HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex); // We need the external source to be set up before we read the AST, because // eagerly-deserialized declarations may use it. - Context.setExternalSource(Reader.get()); + Context.setExternalSource(Reader); Reader->setDeserializationListener( static_cast(DeserializationListener), @@ -881,7 +883,7 @@ void CompilerInstance::createSema(TranslationUnitKind TUKind, // Attach the external sema source if there is any. if (ExternalSemaSrc) { - TheSema->addExternalSource(ExternalSemaSrc.get()); + TheSema->addExternalSource(ExternalSemaSrc); ExternalSemaSrc->InitializeSema(*TheSema); } } @@ -1398,9 +1400,9 @@ std::unique_ptr CompilerInstance::cloneForModuleCompileImpl( Instance.createFileManager(); } else if (FrontendOpts.ModulesShareFileManager) { Instance.setVirtualFileSystem(getVirtualFileSystemPtr()); - Instance.setFileManager(&getFileManager()); + Instance.setFileManager(getFileManagerPtr()); } else { - Instance.setVirtualFileSystem(&getVirtualFileSystem()); + Instance.setVirtualFileSystem(getVirtualFileSystemPtr()); Instance.createFileManager(); } @@ -1869,16 +1871,17 @@ void CompilerInstance::createASTReader() { if (timerGroup) ReadTimer = std::make_unique("reading_modules", "Reading modules", *timerGroup); - TheASTReader = new ASTReader( + TheASTReader = llvm::makeIntrusiveRefCnt( getPreprocessor(), getModuleCache(), &getASTContext(), getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHOrModuleValidation, /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors, - /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, - HSOpts.ModulesForceValidateUserHeaders, - HSOpts.ValidateASTInputFilesContent, - getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); + /*AllowConfigurationMismatch=*/false, + +HSOpts.ModulesValidateSystemHeaders, + +HSOpts.ModulesForceValidateUserHeaders, + +HSOpts.ValidateASTInputFilesContent, + +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); if (hasASTConsumer()) { TheASTReader->setDeserializationListener( getASTConsumer().GetASTDeserializationListener()); diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index 16f6f5a8cf1fc..717d43ee53f06 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -884,7 +884,7 @@ static bool RoundTrip(ParseFn Parse, GenerateFn Generate, // Setup a dummy DiagnosticsEngine. DiagnosticOptions DummyDiagOpts; - DiagnosticsEngine DummyDiags(new DiagnosticIDs(), DummyDiagOpts); + DiagnosticsEngine DummyDiags(DiagnosticIDs::create(), DummyDiagOpts); DummyDiags.setClient(new TextDiagnosticBuffer()); // Run the first parse on the original arguments with the dummy invocation and @@ -2908,7 +2908,7 @@ bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, std::optional IgnoringDiags; if (!Diags) { IgnoringDiagOpts.emplace(); - IgnoringDiags.emplace(new DiagnosticIDs(), *IgnoringDiagOpts, + IgnoringDiags.emplace(DiagnosticIDs::create(), *IgnoringDiagOpts, new IgnoringDiagConsumer()); Diags = &*IgnoringDiags; } diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index ff77592f3dd84..f52bbe880e685 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -892,11 +892,11 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // If we're replaying the build of an AST file, import it and set up // the initial state from its build. if (ReplayASTFile) { - IntrusiveRefCntPtr Diags(&CI.getDiagnostics()); + IntrusiveRefCntPtr Diags = CI.getDiagnosticsPtr(); // The AST unit populates its own diagnostics engine rather than ours. - IntrusiveRefCntPtr ASTDiags(new DiagnosticsEngine( - Diags->getDiagnosticIDs(), Diags->getDiagnosticOptions())); + auto ASTDiags = llvm::makeIntrusiveRefCnt( + Diags->getDiagnosticIDs(), Diags->getDiagnosticOptions()); ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false); // FIXME: What if the input is a memory buffer? @@ -918,7 +918,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. CI.setVirtualFileSystem(AST->getFileManager().getVirtualFileSystemPtr()); - CI.setFileManager(&AST->getFileManager()); + CI.setFileManager(AST->getFileManagerPtr()); CI.createSourceManager(); CI.getSourceManager().initializeForReplay(AST->getSourceManager()); @@ -966,7 +966,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, assert(hasASTFileSupport() && "This action does not have AST file support!"); - IntrusiveRefCntPtr Diags(&CI.getDiagnostics()); + IntrusiveRefCntPtr Diags = CI.getDiagnosticsPtr(); // FIXME: What if the input is a memory buffer? StringRef InputFile = Input.getFile(); @@ -985,14 +985,14 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // Set the shared objects, these are reset when we finish processing the // file, otherwise the CompilerInstance will happily destroy them. - CI.setVirtualFileSystem(AST->getVirtualFileSystemPtr()); - CI.setFileManager(&AST->getFileManager()); - CI.setSourceManager(&AST->getSourceManager()); + CI.setVirtualFileSystem(AST->getFileManager().getVirtualFileSystemPtr()); + CI.setFileManager(AST->getFileManagerPtr()); + CI.setSourceManager(AST->getSourceManagerPtr()); CI.setPreprocessor(AST->getPreprocessorPtr()); Preprocessor &PP = CI.getPreprocessor(); PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), PP.getLangOpts()); - CI.setASTContext(&AST->getASTContext()); + CI.setASTContext(AST->getASTContextPtr()); setCurrentInput(Input, std::move(AST)); @@ -1297,11 +1297,12 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) { // Convert headers to PCH and chain them. - IntrusiveRefCntPtr source, FinalReader; + IntrusiveRefCntPtr source; + IntrusiveRefCntPtr FinalReader; source = createChainedIncludesSource(CI, FinalReader); if (!source) return false; - CI.setASTReader(static_cast(FinalReader.get())); + CI.setASTReader(FinalReader); CI.getASTContext().setExternalSource(source); } else if (CI.getLangOpts().Modules || !CI.getPreprocessorOpts().ImplicitPCHInclude.empty() || @@ -1397,23 +1398,21 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // provides the layouts from that file. if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() && CI.hasASTContext() && !CI.getASTContext().getExternalSource()) { - IntrusiveRefCntPtr - Override(new LayoutOverrideSource( - CI.getFrontendOpts().OverrideRecordLayoutsFile)); + auto Override = llvm::makeIntrusiveRefCnt( + CI.getFrontendOpts().OverrideRecordLayoutsFile); CI.getASTContext().setExternalSource(Override); } // Setup HLSL External Sema Source if (CI.getLangOpts().HLSL && CI.hasASTContext()) { - IntrusiveRefCntPtr HLSLSema( - new HLSLExternalSemaSource()); - if (auto *SemaSource = dyn_cast_if_present( - CI.getASTContext().getExternalSource())) { - IntrusiveRefCntPtr MultiSema( - new MultiplexExternalSemaSource(SemaSource, HLSLSema.get())); - CI.getASTContext().setExternalSource(MultiSema); + auto HLSLSema = llvm::makeIntrusiveRefCnt(); + if (auto SemaSource = dyn_cast_if_present( + CI.getASTContext().getExternalSourcePtr())) { + auto MultiSema = llvm::makeIntrusiveRefCnt( + std::move(SemaSource), std::move(HLSLSema)); + CI.getASTContext().setExternalSource(std::move(MultiSema)); } else - CI.getASTContext().setExternalSource(HLSLSema); + CI.getASTContext().setExternalSource(std::move(HLSLSema)); } FailureCleanup.release(); @@ -1541,7 +1540,6 @@ void ASTFrontendAction::ExecuteAction() { if (!CI.hasSema()) CI.createSema(getTranslationUnitKind(), CompletionConsumer); - ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats, CI.getFrontendOpts().SkipFunctionBodies); } diff --git a/clang/lib/Frontend/PrecompiledPreamble.cpp b/clang/lib/Frontend/PrecompiledPreamble.cpp index f4cd8cabaa462..6dbcb3332fbee 100644 --- a/clang/lib/Frontend/PrecompiledPreamble.cpp +++ b/clang/lib/Frontend/PrecompiledPreamble.cpp @@ -412,7 +412,7 @@ PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default; llvm::ErrorOr PrecompiledPreamble::Build( const CompilerInvocation &Invocation, const llvm::MemoryBuffer *MainFileBuffer, PreambleBounds Bounds, - DiagnosticsEngine &Diagnostics, + IntrusiveRefCntPtr Diagnostics, IntrusiveRefCntPtr VFS, std::shared_ptr PCHContainerOps, bool StoreInMemory, StringRef StoragePath, PreambleCallbacks &Callbacks) { @@ -461,7 +461,7 @@ llvm::ErrorOr PrecompiledPreamble::Build( llvm::CrashRecoveryContextCleanupRegistrar CICleanup( Clang.get()); - Clang->setDiagnostics(&Diagnostics); + Clang->setDiagnostics(Diagnostics); // Create the target instance. if (!Clang->createTarget()) @@ -476,8 +476,8 @@ llvm::ErrorOr PrecompiledPreamble::Build( } // Clear out old caches and data. - Diagnostics.Reset(); - ProcessWarningOptions(Diagnostics, Clang->getDiagnosticOpts(), *VFS); + Diagnostics->Reset(); + ProcessWarningOptions(*Diagnostics, Clang->getDiagnosticOpts(), *VFS); // Create a file manager object to provide access to and cache the filesystem. Clang->createVirtualFileSystem(VFS); diff --git a/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp b/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp index 2abe68b29538e..e7528ea128b4b 100644 --- a/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp +++ b/clang/lib/Frontend/SerializedDiagnosticPrinter.cpp @@ -781,10 +781,9 @@ DiagnosticsEngine *SDiagsWriter::getMetaDiags() { // to be distinct from the engine the writer was being added to and would // normally not be used. if (!State->MetaDiagnostics) { - IntrusiveRefCntPtr IDs(new DiagnosticIDs()); auto Client = new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts); - State->MetaDiagnostics = - std::make_unique(IDs, State->DiagOpts, Client); + State->MetaDiagnostics = std::make_unique( + DiagnosticIDs::create(), State->DiagOpts, Client); } return State->MetaDiagnostics.get(); } diff --git a/clang/lib/Interpreter/CodeCompletion.cpp b/clang/lib/Interpreter/CodeCompletion.cpp index 3ab35ccd880eb..864c4c8a9b56c 100644 --- a/clang/lib/Interpreter/CodeCompletion.cpp +++ b/clang/lib/Interpreter/CodeCompletion.cpp @@ -237,11 +237,9 @@ class ExternalSource : public clang::ExternalASTSource { // compiler instance before the super `ExecuteAction` triggers parsing void IncrementalSyntaxOnlyAction::ExecuteAction() { CompilerInstance &CI = getCompilerInstance(); - ExternalSource *myExternalSource = - new ExternalSource(CI.getASTContext(), CI.getFileManager(), - ParentCI->getASTContext(), ParentCI->getFileManager()); - llvm::IntrusiveRefCntPtr astContextExternalSource( - myExternalSource); + auto astContextExternalSource = llvm::makeIntrusiveRefCnt( + CI.getASTContext(), CI.getFileManager(), ParentCI->getASTContext(), + ParentCI->getFileManager()); CI.getASTContext().setExternalSource(astContextExternalSource); CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage( true); @@ -379,9 +377,9 @@ void ReplCodeCompleter::codeComplete(CompilerInstance *InterpCI, AU->setOwnsRemappedFileBuffers(false); AU->CodeComplete(CodeCompletionFileName, 1, Col, RemappedFiles, false, false, false, consumer, - std::make_shared(), *diag, - InterpCI->getLangOpts(), AU->getSourceManager(), - AU->getFileManager(), sd, tb, std::move(Act)); + std::make_shared(), diag, + InterpCI->getLangOpts(), AU->getSourceManagerPtr(), + AU->getFileManagerPtr(), sd, tb, std::move(Act)); } } // namespace clang diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index 030a7ace92c31..921862b1bbb96 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -86,7 +86,6 @@ GetCC1Arguments(DiagnosticsEngine *Diagnostics, static llvm::Expected> CreateCI(const llvm::opt::ArgStringList &Argv) { std::unique_ptr Clang(new CompilerInstance()); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); // Register the support for object-file-wrapped Clang modules. // FIXME: Clang should register these container operations automatically. @@ -98,7 +97,7 @@ CreateCI(const llvm::opt::ArgStringList &Argv) { // a well formed diagnostic object. DiagnosticOptions DiagOpts; TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; - DiagnosticsEngine Diags(DiagID, DiagOpts, DiagsBuffer); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagsBuffer); bool Success = CompilerInvocation::CreateFromArgs( Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags); @@ -176,11 +175,10 @@ IncrementalCompilerBuilder::create(std::string TT, // Buffer diagnostics from argument parsing so that we can output them using a // well formed diagnostic object. - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); std::unique_ptr DiagOpts = CreateAndPopulateDiagOpts(ClangArgv); TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; - DiagnosticsEngine Diags(DiagID, *DiagOpts, DiagsBuffer); + DiagnosticsEngine Diags(DiagnosticIDs::create(), *DiagOpts, DiagsBuffer); driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags); Driver.setCheckInputsExist(false); // the input comes from mem buffers diff --git a/clang/lib/Sema/MultiplexExternalSemaSource.cpp b/clang/lib/Sema/MultiplexExternalSemaSource.cpp index fbfb242598c24..1f040c879d724 100644 --- a/clang/lib/Sema/MultiplexExternalSemaSource.cpp +++ b/clang/lib/Sema/MultiplexExternalSemaSource.cpp @@ -20,26 +20,19 @@ char MultiplexExternalSemaSource::ID; /// given element to it. /// MultiplexExternalSemaSource::MultiplexExternalSemaSource( - ExternalSemaSource *S1, ExternalSemaSource *S2) { - S1->Retain(); - S2->Retain(); - Sources.push_back(S1); - Sources.push_back(S2); -} - -// pin the vtable here. -MultiplexExternalSemaSource::~MultiplexExternalSemaSource() { - for (auto *S : Sources) - S->Release(); + llvm::IntrusiveRefCntPtr S1, + llvm::IntrusiveRefCntPtr S2) { + Sources.push_back(std::move(S1)); + Sources.push_back(std::move(S2)); } /// Appends new source to the source list. /// ///\param[in] source - An ExternalSemaSource. /// -void MultiplexExternalSemaSource::AddSource(ExternalSemaSource *Source) { - Source->Retain(); - Sources.push_back(Source); +void MultiplexExternalSemaSource::AddSource( + llvm::IntrusiveRefCntPtr Source) { + Sources.push_back(std::move(Source)); } //===----------------------------------------------------------------------===// @@ -92,7 +85,7 @@ CXXBaseSpecifier *MultiplexExternalSemaSource::GetExternalCXXBaseSpecifiers( CXXCtorInitializer ** MultiplexExternalSemaSource::GetExternalCXXCtorInitializers(uint64_t Offset) { - for (auto *S : Sources) + for (auto &S : Sources) if (auto *R = S->GetExternalCXXCtorInitializers(Offset)) return R; return nullptr; @@ -371,6 +364,6 @@ bool MultiplexExternalSemaSource::MaybeDiagnoseMissingCompleteType( void MultiplexExternalSemaSource::AssignedLambdaNumbering( CXXRecordDecl *Lambda) { - for (auto *Source : Sources) + for (auto &Source : Sources) Source->AssignedLambdaNumbering(Lambda); } diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp index 5843568f3ac2d..ed6193b2118ed 100644 --- a/clang/lib/Sema/Sema.cpp +++ b/clang/lib/Sema/Sema.cpp @@ -773,18 +773,19 @@ ASTMutationListener *Sema::getASTMutationListener() const { return getASTConsumer().GetASTMutationListener(); } -void Sema::addExternalSource(ExternalSemaSource *E) { +void Sema::addExternalSource(IntrusiveRefCntPtr E) { assert(E && "Cannot use with NULL ptr"); if (!ExternalSource) { - ExternalSource = E; + ExternalSource = std::move(E); return; } - if (auto *Ex = dyn_cast(ExternalSource)) - Ex->AddSource(E); + if (auto *Ex = dyn_cast(ExternalSource.get())) + Ex->AddSource(std::move(E)); else - ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E); + ExternalSource = llvm::makeIntrusiveRefCnt( + ExternalSource, std::move(E)); } void Sema::PrintStats() const { diff --git a/clang/lib/Serialization/ASTReader.cpp b/clang/lib/Serialization/ASTReader.cpp index 287bab8c3cc8a..ed1fe9d6c3227 100644 --- a/clang/lib/Serialization/ASTReader.cpp +++ b/clang/lib/Serialization/ASTReader.cpp @@ -612,8 +612,7 @@ bool PCHValidator::ReadDiagnosticOptions(DiagnosticOptions &DiagOpts, bool Complain) { DiagnosticsEngine &ExistingDiags = PP.getDiagnostics(); IntrusiveRefCntPtr DiagIDs(ExistingDiags.getDiagnosticIDs()); - IntrusiveRefCntPtr Diags( - new DiagnosticsEngine(DiagIDs, DiagOpts)); + auto Diags = llvm::makeIntrusiveRefCnt(DiagIDs, DiagOpts); // This should never fail, because we would have processed these options // before writing them to an ASTFile. ProcessWarningOptions(*Diags, DiagOpts, diff --git a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp index 940db3daaa179..531c642bf4f31 100644 --- a/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp +++ b/clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp @@ -52,8 +52,8 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { if (Bodies.count(D->getName()) != 0) return; - SourceManager &SM = CI.getSourceManager(); - FileID mainFileID = SM.getMainFileID(); + llvm::IntrusiveRefCntPtr SM = CI.getSourceManagerPtr(); + FileID mainFileID = SM->getMainFileID(); llvm::StringRef modelPath = CI.getAnalyzerOpts().ModelPath; @@ -89,15 +89,15 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { new ForwardingDiagnosticConsumer(CI.getDiagnosticClient()), /*ShouldOwnClient=*/true); - Instance.getDiagnostics().setSourceManager(&SM); + Instance.getDiagnostics().setSourceManager(SM.get()); // The instance wants to take ownership, however DisableFree frontend option // is set to true to avoid double free issues Instance.setVirtualFileSystem(CI.getVirtualFileSystemPtr()); - Instance.setFileManager(&CI.getFileManager()); - Instance.setSourceManager(&SM); + Instance.setFileManager(CI.getFileManagerPtr()); + Instance.setSourceManager(SM); Instance.setPreprocessor(CI.getPreprocessorPtr()); - Instance.setASTContext(&CI.getASTContext()); + Instance.setASTContext(CI.getASTContextPtr()); Instance.getPreprocessor().InitializeForModelFile(); @@ -118,5 +118,5 @@ void ModelInjector::onBodySynthesis(const NamedDecl *D) { // the main file id is changed to the model file during parsing and it needs // to be reset to the former main file id after parsing of the model file // is done. - SM.setMainFileID(mainFileID); + SM->setMainFileID(mainFileID); } diff --git a/clang/lib/Tooling/CompilationDatabase.cpp b/clang/lib/Tooling/CompilationDatabase.cpp index d5fc21601ae40..860457acced85 100644 --- a/clang/lib/Tooling/CompilationDatabase.cpp +++ b/clang/lib/Tooling/CompilationDatabase.cpp @@ -241,9 +241,8 @@ static bool stripPositionalArgs(std::vector Args, llvm::raw_string_ostream Output(ErrorMsg); TextDiagnosticPrinter DiagnosticPrinter(Output, DiagOpts); UnusedInputDiagConsumer DiagClient(DiagnosticPrinter); - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &DiagClient, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, &DiagClient, + false); // The clang executable path isn't required since the jobs the driver builds // will not be executed. diff --git a/clang/lib/Tooling/Core/Replacement.cpp b/clang/lib/Tooling/Core/Replacement.cpp index 1506218d88553..6452a828d11ab 100644 --- a/clang/lib/Tooling/Core/Replacement.cpp +++ b/clang/lib/Tooling/Core/Replacement.cpp @@ -585,8 +585,7 @@ llvm::Expected applyAllReplacements(StringRef Code, new llvm::vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs), DiagOpts); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts); SourceManager SourceMgr(Diagnostics, Files); Rewriter Rewrite(SourceMgr, LangOptions()); InMemoryFileSystem->addFile( diff --git a/clang/lib/Tooling/DependencyScanning/CMakeLists.txt b/clang/lib/Tooling/DependencyScanning/CMakeLists.txt index 917b3f5810e96..a6a23ab18b330 100644 --- a/clang/lib/Tooling/DependencyScanning/CMakeLists.txt +++ b/clang/lib/Tooling/DependencyScanning/CMakeLists.txt @@ -14,6 +14,7 @@ add_clang_library(clangDependencyScanning DependencyScanningWorker.cpp DependencyScanningTool.cpp IncludeTreeActionController.cpp + DependencyScannerImpl.cpp InProcessModuleCache.cpp ModuleDepCollector.cpp ScanAndUpdateArgs.cpp @@ -29,6 +30,5 @@ add_clang_library(clangDependencyScanning clangFrontend clangLex clangSerialization - clangTooling ${LLVM_PTHREAD_LIB} ) diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.cpp new file mode 100644 index 0000000000000..5bd206626fac3 --- /dev/null +++ b/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.cpp @@ -0,0 +1,961 @@ +//===- DependencyScanner.cpp - Performs module dependency scanning --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "DependencyScannerImpl.h" +#include "clang/Basic/DiagnosticCAS.h" +#include "clang/Basic/DiagnosticFrontend.h" +#include "clang/Basic/DiagnosticSerialization.h" +#include "clang/Driver/Driver.h" +#include "clang/Frontend/FrontendActions.h" +#include "clang/Frontend/MultiplexConsumer.h" +#include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h" +#include "clang/Tooling/DependencyScanning/ScanAndUpdateArgs.h" +#include "llvm/CAS/CASProvidingFileSystem.h" +#include "llvm/TargetParser/Host.h" + +using namespace clang; +using namespace tooling; +using namespace dependencies; +using llvm::Error; + +namespace { +/// Forwards the gatherered dependencies to the consumer. +class DependencyConsumerForwarder : public DependencyFileGenerator { +public: + DependencyConsumerForwarder(std::unique_ptr Opts, + StringRef WorkingDirectory, DependencyConsumer &C, + bool EmitDependencyFile) + : DependencyFileGenerator(*Opts), WorkingDirectory(WorkingDirectory), + Opts(std::move(Opts)), C(C), EmitDependencyFile(EmitDependencyFile) {} + + void finishedMainFile(DiagnosticsEngine &Diags) override { + C.handleDependencyOutputOpts(*Opts); + llvm::SmallString<256> CanonPath; + for (const auto &File : getDependencies()) { + CanonPath = File; + llvm::sys::path::remove_dots(CanonPath, /*remove_dot_dot=*/true); + llvm::sys::path::make_absolute(WorkingDirectory, CanonPath); + C.handleFileDependency(CanonPath); + } + if (EmitDependencyFile) + DependencyFileGenerator::finishedMainFile(Diags); + } + +private: + StringRef WorkingDirectory; + std::unique_ptr Opts; + DependencyConsumer &C; + bool EmitDependencyFile = false; +}; + +static bool checkHeaderSearchPaths(const HeaderSearchOptions &HSOpts, + const HeaderSearchOptions &ExistingHSOpts, + DiagnosticsEngine *Diags, + const LangOptions &LangOpts) { + if (LangOpts.Modules) { + if (HSOpts.VFSOverlayFiles != ExistingHSOpts.VFSOverlayFiles) { + if (Diags) { + Diags->Report(diag::warn_pch_vfsoverlay_mismatch); + auto VFSNote = [&](int Type, ArrayRef VFSOverlays) { + if (VFSOverlays.empty()) { + Diags->Report(diag::note_pch_vfsoverlay_empty) << Type; + } else { + std::string Files = llvm::join(VFSOverlays, "\n"); + Diags->Report(diag::note_pch_vfsoverlay_files) << Type << Files; + } + }; + VFSNote(0, HSOpts.VFSOverlayFiles); + VFSNote(1, ExistingHSOpts.VFSOverlayFiles); + } + } + } + return false; +} + +using PrebuiltModuleFilesT = decltype(HeaderSearchOptions::PrebuiltModuleFiles); + +/// A listener that collects the imported modules and the input +/// files. While visiting, collect vfsoverlays and file inputs that determine +/// whether prebuilt modules fully resolve in stable directories. +class PrebuiltModuleListener : public ASTReaderListener { +public: + PrebuiltModuleListener(CompilerInstance &CI, + PrebuiltModuleFilesT &PrebuiltModuleFiles, + llvm::SmallVector &NewModuleFiles, + PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, + DiagnosticsEngine &Diags, + const ArrayRef StableDirs) + : CI(CI), PrebuiltModuleFiles(PrebuiltModuleFiles), + NewModuleFiles(NewModuleFiles), + PrebuiltModulesASTMap(PrebuiltModulesASTMap), Diags(Diags), + StableDirs(StableDirs) {} + + bool needsImportVisitation() const override { return true; } + bool needsInputFileVisitation() override { return true; } + bool needsSystemInputFileVisitation() override { return true; } + + /// Accumulate the modules are transitively depended on by the initial + /// prebuilt module. + void visitImport(StringRef ModuleName, StringRef Filename) override { + if (PrebuiltModuleFiles.insert({ModuleName.str(), Filename.str()}).second) + NewModuleFiles.push_back(Filename.str()); + + auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(Filename); + PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; + if (PrebuiltMapEntry.second) + PrebuiltModule.setInStableDir(!StableDirs.empty()); + + if (auto It = PrebuiltModulesASTMap.find(CurrentFile); + It != PrebuiltModulesASTMap.end() && CurrentFile != Filename) + PrebuiltModule.addDependent(It->getKey()); + } + + /// For each input file discovered, check whether it's external path is in a + /// stable directory. Traversal is stopped if the current module is not + /// considered stable. + bool visitInputFile(StringRef FilenameAsRequested, StringRef Filename, + bool isSystem, bool isOverridden, + bool isExplicitModule) override { + if (StableDirs.empty()) + return false; + auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(CurrentFile); + if ((PrebuiltEntryIt == PrebuiltModulesASTMap.end()) || + (!PrebuiltEntryIt->second.isInStableDir())) + return false; + + PrebuiltEntryIt->second.setInStableDir( + isPathInStableDir(StableDirs, Filename)); + return PrebuiltEntryIt->second.isInStableDir(); + } + + /// Update which module that is being actively traversed. + void visitModuleFile(StringRef Filename, + serialization::ModuleKind Kind) override { + // If the CurrentFile is not + // considered stable, update any of it's transitive dependents. + auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(CurrentFile); + if ((PrebuiltEntryIt != PrebuiltModulesASTMap.end()) && + !PrebuiltEntryIt->second.isInStableDir()) + PrebuiltEntryIt->second.updateDependentsNotInStableDirs( + PrebuiltModulesASTMap); + CurrentFile = Filename; + } + + /// Check the header search options for a given module when considering + /// if the module comes from stable directories. + bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, + StringRef ModuleFilename, + StringRef SpecificModuleCachePath, + bool Complain) override { + + auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(CurrentFile); + PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; + if (PrebuiltMapEntry.second) + PrebuiltModule.setInStableDir(!StableDirs.empty()); + + if (PrebuiltModule.isInStableDir()) + PrebuiltModule.setInStableDir(areOptionsInStableDir(StableDirs, HSOpts)); + + return false; + } + + /// Accumulate vfsoverlays used to build these prebuilt modules. + bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, + bool Complain) override { + + auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(CurrentFile); + PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; + if (PrebuiltMapEntry.second) + PrebuiltModule.setInStableDir(!StableDirs.empty()); + + PrebuiltModule.setVFS( + llvm::StringSet<>(llvm::from_range, HSOpts.VFSOverlayFiles)); + + return checkHeaderSearchPaths(HSOpts, CI.getHeaderSearchOpts(), + Complain ? &Diags : nullptr, + CI.getLangOpts()); + } + + bool readModuleCacheKey(StringRef ModuleName, StringRef Filename, + StringRef CacheKey) override { + CI.getFrontendOpts().ModuleCacheKeys.emplace_back(std::string(Filename), + std::string(CacheKey)); + // FIXME: add name/path of the importing module? + return CI.addCachedModuleFile(Filename, CacheKey, "imported module"); + } + +private: + CompilerInstance &CI; + PrebuiltModuleFilesT &PrebuiltModuleFiles; + llvm::SmallVector &NewModuleFiles; + PrebuiltModulesAttrsMap &PrebuiltModulesASTMap; + DiagnosticsEngine &Diags; + std::string CurrentFile; + const ArrayRef StableDirs; +}; + +/// Visit the given prebuilt module and collect all of the modules it +/// transitively imports and contributing input files. +static bool visitPrebuiltModule(StringRef PrebuiltModuleFilename, + CompilerInstance &CI, + PrebuiltModuleFilesT &ModuleFiles, + PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, + DiagnosticsEngine &Diags, + const ArrayRef StableDirs) { + // List of module files to be processed. + llvm::SmallVector Worklist; + PrebuiltModuleListener Listener(CI, ModuleFiles, Worklist, + PrebuiltModulesASTMap, Diags, StableDirs); + + Listener.visitModuleFile(PrebuiltModuleFilename, + serialization::MK_ExplicitModule); + if (ASTReader::readASTFileControlBlock( + PrebuiltModuleFilename, CI.getFileManager(), CI.getModuleCache(), + CI.getPCHContainerReader(), + /*FindModuleFileExtensions=*/false, Listener, + /*ValidateDiagnosticOptions=*/false, ASTReader::ARR_OutOfDate)) + return true; + + while (!Worklist.empty()) { + Listener.visitModuleFile(Worklist.back(), serialization::MK_ExplicitModule); + if (ASTReader::readASTFileControlBlock( + Worklist.pop_back_val(), CI.getFileManager(), CI.getModuleCache(), + CI.getPCHContainerReader(), + /*FindModuleFileExtensions=*/false, Listener, + /*ValidateDiagnosticOptions=*/false)) + return true; + } + return false; +} + +/// Transform arbitrary file name into an object-like file name. +static std::string makeObjFileName(StringRef FileName) { + SmallString<128> ObjFileName(FileName); + llvm::sys::path::replace_extension(ObjFileName, "o"); + return std::string(ObjFileName); +} + +/// Deduce the dependency target based on the output file and input files. +static std::string +deduceDepTarget(const std::string &OutputFile, + const SmallVectorImpl &InputFiles) { + if (OutputFile != "-") + return OutputFile; + + if (InputFiles.empty() || !InputFiles.front().isFile()) + return "clang-scan-deps\\ dependency"; + + return makeObjFileName(InputFiles.front().getFile()); +} + +// Clang implements -D and -U by splatting text into a predefines buffer. This +// allows constructs such as `-DFඞ=3 "-D F\u{0D9E} 4 3 2”` to be accepted and +// define the same macro, or adding C++ style comments before the macro name. +// +// This function checks that the first non-space characters in the macro +// obviously form an identifier that can be uniqued on without lexing. Failing +// to do this could lead to changing the final definition of a macro. +// +// We could set up a preprocessor and actually lex the name, but that's very +// heavyweight for a situation that will almost never happen in practice. +static std::optional getSimpleMacroName(StringRef Macro) { + StringRef Name = Macro.split("=").first.ltrim(" \t"); + std::size_t I = 0; + + auto FinishName = [&]() -> std::optional { + StringRef SimpleName = Name.slice(0, I); + if (SimpleName.empty()) + return std::nullopt; + return SimpleName; + }; + + for (; I != Name.size(); ++I) { + switch (Name[I]) { + case '(': // Start of macro parameter list + case ' ': // End of macro name + case '\t': + return FinishName(); + case '_': + continue; + default: + if (llvm::isAlnum(Name[I])) + continue; + return std::nullopt; + } + } + return FinishName(); +} + +static void canonicalizeDefines(PreprocessorOptions &PPOpts) { + using MacroOpt = std::pair; + std::vector SimpleNames; + SimpleNames.reserve(PPOpts.Macros.size()); + std::size_t Index = 0; + for (const auto &M : PPOpts.Macros) { + auto SName = getSimpleMacroName(M.first); + // Skip optimizing if we can't guarantee we can preserve relative order. + if (!SName) + return; + SimpleNames.emplace_back(*SName, Index); + ++Index; + } + + llvm::stable_sort(SimpleNames, llvm::less_first()); + // Keep the last instance of each macro name by going in reverse + auto NewEnd = std::unique( + SimpleNames.rbegin(), SimpleNames.rend(), + [](const MacroOpt &A, const MacroOpt &B) { return A.first == B.first; }); + SimpleNames.erase(SimpleNames.begin(), NewEnd.base()); + + // Apply permutation. + decltype(PPOpts.Macros) NewMacros; + NewMacros.reserve(SimpleNames.size()); + for (std::size_t I = 0, E = SimpleNames.size(); I != E; ++I) { + std::size_t OriginalIndex = SimpleNames[I].second; + // We still emit undefines here as they may be undefining a predefined macro + NewMacros.push_back(std::move(PPOpts.Macros[OriginalIndex])); + } + std::swap(PPOpts.Macros, NewMacros); +} + +/// Builds a dependency file after reversing prefix mappings. This allows +/// emitting a .d file that has real paths where they would otherwise be +/// canonicalized. +class ReversePrefixMappingDependencyFileGenerator + : public DependencyFileGenerator { + llvm::PrefixMapper ReverseMapper; + +public: + ReversePrefixMappingDependencyFileGenerator( + const DependencyOutputOptions &Opts) + : DependencyFileGenerator(Opts) {} + + void initialize(const CompilerInvocation &CI) { + llvm::PrefixMapper Mapper; + DepscanPrefixMapping::configurePrefixMapper(CI, Mapper); + if (Mapper.empty()) + return; + + ReverseMapper.addInverseRange(Mapper.getMappings()); + ReverseMapper.sort(); + } + + void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem, + bool IsModuleFile, bool IsMissing) override { + if (ReverseMapper.empty()) + return DependencyFileGenerator::maybeAddDependency( + Filename, FromModule, IsSystem, IsModuleFile, IsMissing); + + // We may get canonicalized paths if prefix headers/PCH are used, so make + // sure to remap them back to original source paths. + SmallString<256> New{Filename}; + ReverseMapper.mapInPlace(New); + return DependencyFileGenerator::maybeAddDependency( + New, FromModule, IsSystem, IsModuleFile, IsMissing); + } +}; + +/// See \c WrapScanModuleBuildAction. +class WrapScanModuleBuildConsumer : public ASTConsumer { +public: + WrapScanModuleBuildConsumer(CompilerInstance &CI, + DependencyActionController &Controller) + : CI(CI), Controller(Controller) {} + + void HandleTranslationUnit(ASTContext &Ctx) override { + if (auto E = Controller.finalizeModuleBuild(CI)) + Ctx.getDiagnostics().Report(diag::err_cas_depscan_failed) << std::move(E); + } + +private: + CompilerInstance &CI; + DependencyActionController &Controller; +}; + +/// A wrapper for implicit module build actions in the scanner. +class WrapScanModuleBuildAction : public WrapperFrontendAction { +public: + WrapScanModuleBuildAction(std::unique_ptr WrappedAction, + DependencyActionController &Controller) + : WrapperFrontendAction(std::move(WrappedAction)), + Controller(Controller) {} + +private: + bool BeginInvocation(CompilerInstance &CI) override { + if (auto E = Controller.initializeModuleBuild(CI)) { + CI.getDiagnostics().Report(diag::err_cas_depscan_failed) << std::move(E); + return false; + } + return WrapperFrontendAction::BeginInvocation(CI); + } + + std::unique_ptr CreateASTConsumer(CompilerInstance &CI, + StringRef InFile) override { + auto OtherConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile); + if (!OtherConsumer) + return nullptr; + Module *M = CI.getPreprocessor().getCurrentModule(); + assert(M && "WrapScanModuleBuildAction should only be used with module"); + if (!M) + return OtherConsumer; + auto Consumer = + std::make_unique(CI, Controller); + std::vector> Consumers; + Consumers.push_back(std::move(Consumer)); + Consumers.push_back(std::move(OtherConsumer)); + return std::make_unique(std::move(Consumers)); + } + +private: + DependencyActionController &Controller; +}; + +class ScanningDependencyDirectivesGetter : public DependencyDirectivesGetter { + DependencyScanningWorkerFilesystem *DepFS; + +public: + ScanningDependencyDirectivesGetter(FileManager &FileMgr) : DepFS(nullptr) { + FileMgr.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &FS) { + auto *DFS = llvm::dyn_cast(&FS); + if (DFS) { + assert(!DepFS && "Found multiple scanning VFSs"); + DepFS = DFS; + } + }); + assert(DepFS && "Did not find scanning VFS"); + } + + std::unique_ptr + cloneFor(FileManager &FileMgr) override { + return std::make_unique(FileMgr); + } + + std::optional> + operator()(FileEntryRef File) override { + return DepFS->getDirectiveTokens(File.getName()); + } +}; + +// FIXME: Make this thread-safe by pulling the FS out of `FileManager`. +class CASDependencyDirectivesGetter : public DependencyDirectivesGetter { + DependencyScanningCASFilesystem *DepCASFS; + +public: + CASDependencyDirectivesGetter(DependencyScanningCASFilesystem *DepCASFS) + : DepCASFS(DepCASFS) {} + + std::unique_ptr + cloneFor(FileManager &FileMgr) override { + (void)FileMgr; + return std::make_unique(DepCASFS); + } + + std::optional> + operator()(FileEntryRef File) override { + return DepCASFS->getDirectiveTokens(File.getName()); + } +}; + +/// Sanitize diagnostic options for dependency scan. +void sanitizeDiagOpts(DiagnosticOptions &DiagOpts) { + // Don't print 'X warnings and Y errors generated'. + DiagOpts.ShowCarets = false; + // Don't write out diagnostic file. + DiagOpts.DiagnosticSerializationFile.clear(); + // Don't emit warnings except for scanning specific warnings. + // TODO: It would be useful to add a more principled way to ignore all + // warnings that come from source code. The issue is that we need to + // ignore warnings that could be surpressed by + // `#pragma clang diagnostic`, while still allowing some scanning + // warnings for things we're not ready to turn into errors yet. + // See `test/ClangScanDeps/diagnostic-pragmas.c` for an example. + llvm::erase_if(DiagOpts.Warnings, [](StringRef Warning) { + return llvm::StringSwitch(Warning) + .Cases("pch-vfs-diff", "error=pch-vfs-diff", false) + .StartsWith("no-error=", false) + .Default(true); + }); +} +} // namespace + +namespace clang::tooling::dependencies { +std::unique_ptr +createDiagOptions(ArrayRef CommandLine) { + std::vector CLI; + for (const std::string &Arg : CommandLine) + CLI.push_back(Arg.c_str()); + auto DiagOpts = CreateAndPopulateDiagOpts(CLI); + sanitizeDiagOpts(*DiagOpts); + return DiagOpts; +} + +DignosticsEngineWithDiagOpts::DignosticsEngineWithDiagOpts( + ArrayRef CommandLine, + IntrusiveRefCntPtr FS, DiagnosticConsumer &DC) { + std::vector CCommandLine(CommandLine.size(), nullptr); + llvm::transform(CommandLine, CCommandLine.begin(), + [](const std::string &Str) { return Str.c_str(); }); + DiagOpts = CreateAndPopulateDiagOpts(CCommandLine); + sanitizeDiagOpts(*DiagOpts); + DiagEngine = CompilerInstance::createDiagnostics(*FS, *DiagOpts, &DC, + /*ShouldOwnClient=*/false); +} + +std::pair, std::unique_ptr> +buildCompilation(ArrayRef ArgStrs, DiagnosticsEngine &Diags, + IntrusiveRefCntPtr FS, + llvm::BumpPtrAllocator &Alloc) { + SmallVector Argv; + Argv.reserve(ArgStrs.size()); + for (const std::string &Arg : ArgStrs) + Argv.push_back(Arg.c_str()); + + std::unique_ptr Driver = std::make_unique( + Argv[0], llvm::sys::getDefaultTargetTriple(), Diags, + "clang LLVM compiler", FS); + Driver->setTitle("clang_based_tool"); + + bool CLMode = driver::IsClangCL( + driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1))); + + if (llvm::Error E = + driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) { + Diags.Report(diag::err_drv_expand_response_file) + << llvm::toString(std::move(E)); + return std::make_pair(nullptr, nullptr); + } + + std::unique_ptr Compilation( + Driver->BuildCompilation(Argv)); + if (!Compilation) + return std::make_pair(nullptr, nullptr); + + if (Compilation->containsError()) + return std::make_pair(nullptr, nullptr); + + return std::make_pair(std::move(Driver), std::move(Compilation)); +} + +std::unique_ptr +createCompilerInvocation(ArrayRef CommandLine, + DiagnosticsEngine &Diags) { + llvm::opt::ArgStringList Argv; + for (const std::string &Str : ArrayRef(CommandLine).drop_front()) + Argv.push_back(Str.c_str()); + + auto Invocation = std::make_unique(); + if (!CompilerInvocation::CreateFromArgs(*Invocation, Argv, Diags)) { + // FIXME: Should we just go on like cc1_main does? + return nullptr; + } + return Invocation; +} + +std::pair, std::vector> +initVFSForTUBuferScanning( + IntrusiveRefCntPtr BaseFS, + ArrayRef CommandLine, StringRef WorkingDirectory, + llvm::MemoryBufferRef TUBuffer, std::shared_ptr CAS, + IntrusiveRefCntPtr DepCASFS) { + // Reset what might have been modified in the previous worker invocation. + BaseFS->setCurrentWorkingDirectory(WorkingDirectory); + + IntrusiveRefCntPtr ModifiedFS; + auto OverlayFS = + llvm::makeIntrusiveRefCnt(BaseFS); + auto InMemoryFS = llvm::makeIntrusiveRefCnt(); + InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory); + auto InputPath = TUBuffer.getBufferIdentifier(); + InMemoryFS->addFile( + InputPath, 0, llvm::MemoryBuffer::getMemBufferCopy(TUBuffer.getBuffer())); + IntrusiveRefCntPtr InMemoryOverlay = InMemoryFS; + + // If we are using a CAS but not dependency CASFS, we need to provide the + // fake input file in a CASProvidingFS for include-tree. + if (CAS && !DepCASFS) + InMemoryOverlay = + llvm::cas::createCASProvidingFileSystem(CAS, std::move(InMemoryFS)); + + OverlayFS->pushOverlay(InMemoryOverlay); + ModifiedFS = OverlayFS; + std::vector ModifiedCommandLine(CommandLine); + ModifiedCommandLine.emplace_back(InputPath); + + return std::make_pair(ModifiedFS, ModifiedCommandLine); +} + +std::pair, std::vector> +initVFSForByNameScanning( + IntrusiveRefCntPtr BaseFS, + ArrayRef CommandLine, StringRef WorkingDirectory, + StringRef ModuleName, std::shared_ptr CAS, + IntrusiveRefCntPtr DepCASFS) { + // Reset what might have been modified in the previous worker invocation. + BaseFS->setCurrentWorkingDirectory(WorkingDirectory); + + // If we're scanning based on a module name alone, we don't expect the client + // to provide us with an input file. However, the driver really wants to have + // one. Let's just make it up to make the driver happy. + auto OverlayFS = + llvm::makeIntrusiveRefCnt(BaseFS); + auto InMemoryFS = llvm::makeIntrusiveRefCnt(); + InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory); + SmallString<128> FakeInputPath; + // TODO: We should retry the creation if the path already exists. + llvm::sys::fs::createUniquePath(ModuleName + "-%%%%%%%%.input", FakeInputPath, + /*MakeAbsolute=*/false); + InMemoryFS->addFile(FakeInputPath, 0, llvm::MemoryBuffer::getMemBuffer("")); + IntrusiveRefCntPtr InMemoryOverlay = InMemoryFS; + + // If we are using a CAS but not dependency CASFS, we need to provide the + // fake input file in a CASProvidingFS for include-tree. + if (CAS && !DepCASFS) + InMemoryOverlay = + llvm::cas::createCASProvidingFileSystem(CAS, std::move(InMemoryFS)); + + OverlayFS->pushOverlay(InMemoryOverlay); + + std::vector ModifiedCommandLine(CommandLine); + ModifiedCommandLine.emplace_back(FakeInputPath); + + return std::make_pair(OverlayFS, ModifiedCommandLine); +} + +bool initializeScanCompilerInstance( + CompilerInstance &ScanInstance, + IntrusiveRefCntPtr FS, + DiagnosticConsumer *DiagConsumer, DependencyScanningService &Service, + IntrusiveRefCntPtr DepFS, + bool DiagGenerationAsCompilation, raw_ostream *VerboseOS, + llvm::IntrusiveRefCntPtr DepCASFS) { + ScanInstance.setBuildingModule(false); + + ScanInstance.createVirtualFileSystem(FS, DiagConsumer); + + // Create the compiler's actual diagnostics engine. + if (!DiagGenerationAsCompilation) + sanitizeDiagOpts(ScanInstance.getDiagnosticOpts()); + + ScanInstance.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); + if (!ScanInstance.hasDiagnostics()) + return false; + if (VerboseOS) + ScanInstance.setVerboseOutputStream(*VerboseOS); + + ScanInstance.getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath = + true; + + if (ScanInstance.getHeaderSearchOpts().ModulesValidateOncePerBuildSession) + ScanInstance.getHeaderSearchOpts().BuildSessionTimestamp = + Service.getBuildSessionTimestamp(); + + ScanInstance.getFrontendOpts().DisableFree = false; + ScanInstance.getFrontendOpts().GenerateGlobalModuleIndex = false; + ScanInstance.getFrontendOpts().UseGlobalModuleIndex = false; + // This will prevent us compiling individual modules asynchronously since + // FileManager is not thread-safe, but it does improve performance for now. + ScanInstance.getFrontendOpts().ModulesShareFileManager = true; + if (DepCASFS) + ScanInstance.getFrontendOpts().ModulesShareFileManager = false; + ScanInstance.getHeaderSearchOpts().ModuleFormat = "raw"; + ScanInstance.getHeaderSearchOpts().ModulesIncludeVFSUsage = + any(Service.getOptimizeArgs() & ScanningOptimizations::VFS); + + // Create a new FileManager to match the invocation's FileSystemOptions. + ScanInstance.createFileManager(); + + // Use the dependency scanning optimized file system if requested to do so. + if (DepFS) { + DepFS->resetBypassedPathPrefix(); + if (!ScanInstance.getHeaderSearchOpts().ModuleCachePath.empty()) { + SmallString<256> ModulesCachePath; + normalizeModuleCachePath( + ScanInstance.getFileManager(), + ScanInstance.getHeaderSearchOpts().ModuleCachePath, ModulesCachePath); + DepFS->setBypassedPathPrefix(ModulesCachePath); + } + + ScanInstance.setDependencyDirectivesGetter( + std::make_unique( + ScanInstance.getFileManager())); + } + + // CAS Implementation. + if (DepCASFS) + ScanInstance.setDependencyDirectivesGetter( + std::make_unique(DepCASFS.get())); + + ScanInstance.createSourceManager(); + + // Consider different header search and diagnostic options to create + // different modules. This avoids the unsound aliasing of module PCMs. + // + // TODO: Implement diagnostic bucketing to reduce the impact of strict + // context hashing. + ScanInstance.getHeaderSearchOpts().ModulesStrictContextHash = true; + ScanInstance.getHeaderSearchOpts().ModulesSerializeOnlyPreprocessor = true; + ScanInstance.getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true; + ScanInstance.getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true; + ScanInstance.getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings = true; + ScanInstance.getHeaderSearchOpts().ModulesForceValidateUserHeaders = false; + + // Avoid some checks and module map parsing when loading PCM files. + ScanInstance.getPreprocessorOpts().ModulesCheckRelocated = false; + + return true; +} + +llvm::SmallVector +getInitialStableDirs(const CompilerInstance &ScanInstance) { + // Create a collection of stable directories derived from the ScanInstance + // for determining whether module dependencies would fully resolve from + // those directories. + llvm::SmallVector StableDirs; + const StringRef Sysroot = ScanInstance.getHeaderSearchOpts().Sysroot; + if (!Sysroot.empty() && (llvm::sys::path::root_directory(Sysroot) != Sysroot)) + StableDirs = {Sysroot, ScanInstance.getHeaderSearchOpts().ResourceDir}; + return StableDirs; +} + +std::optional +computePrebuiltModulesASTMap(CompilerInstance &ScanInstance, + llvm::SmallVector &StableDirs) { + // Store a mapping of prebuilt module files and their properties like header + // search options. This will prevent the implicit build to create duplicate + // modules and will force reuse of the existing prebuilt module files + // instead. + PrebuiltModulesAttrsMap PrebuiltModulesASTMap; + + if (!ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty()) + if (visitPrebuiltModule( + ScanInstance.getPreprocessorOpts().ImplicitPCHInclude, ScanInstance, + ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles, + PrebuiltModulesASTMap, ScanInstance.getDiagnostics(), StableDirs)) + return {}; + + return PrebuiltModulesASTMap; +} + +std::unique_ptr +takeDependencyOutputOptionsFrom(CompilerInstance &ScanInstance, + bool ForceIncludeSystemHeaders) { + // This function moves the existing dependency output options from the + // invocation to the collector. The options in the invocation are reset, + // which ensures that the compiler won't create new dependency collectors, + // and thus won't write out the extra '.d' files to disk. + auto Opts = std::make_unique(); + std::swap(*Opts, ScanInstance.getInvocation().getDependencyOutputOpts()); + // We need at least one -MT equivalent for the generator of make dependency + // files to work. + if (Opts->Targets.empty()) + Opts->Targets = {deduceDepTarget(ScanInstance.getFrontendOpts().OutputFile, + ScanInstance.getFrontendOpts().Inputs)}; + if (ForceIncludeSystemHeaders) { + // Only 'Make' scanning needs to force this because that mode depends on + // getting the dependencies directly from \p DependencyFileGenerator. + Opts->IncludeSystemHeaders = true; + } + + return Opts; +} + +std::shared_ptr initializeScanInstanceDependencyCollector( + CompilerInstance &ScanInstance, + std::unique_ptr DepOutputOpts, + StringRef WorkingDirectory, DependencyConsumer &Consumer, + DependencyScanningService &Service, CompilerInvocation &Inv, + DependencyActionController &Controller, + PrebuiltModulesAttrsMap PrebuiltModulesASTMap, + llvm::SmallVector &StableDirs, bool EmitDependencyFile) { + std::shared_ptr MDC; + // FIXME: The caller APIs in \p DependencyScanningTool expect a specific + // DependencyCollector to get attached to the preprocessor in order to + // function properly (e.g. \p FullDependencyConsumer needs \p + // ModuleDepCollector) but this association is very indirect via the value + // of the \p ScanningOutputFormat. We should remove \p Format field from + // \p DependencyScanningAction, and have the callers pass in a + // “DependencyCollector factory” so the connection of collector<->consumer + // is explicit in each \p DependencyScanningTool function. + switch (Service.getFormat()) { + case ScanningOutputFormat::Make: + case ScanningOutputFormat::Tree: + ScanInstance.addDependencyCollector( + std::make_shared( + std::move(DepOutputOpts), WorkingDirectory, Consumer, + EmitDependencyFile)); + break; + case ScanningOutputFormat::IncludeTree: + case ScanningOutputFormat::P1689: + case ScanningOutputFormat::Full: + case ScanningOutputFormat::FullTree: + case ScanningOutputFormat::FullIncludeTree: + if (EmitDependencyFile) { + auto DFG = std::make_shared( + *DepOutputOpts); + DFG->initialize(ScanInstance.getInvocation()); + ScanInstance.addDependencyCollector(std::move(DFG)); + } + + MDC = std::make_shared( + Service, std::move(DepOutputOpts), ScanInstance, Consumer, Controller, + Inv, std::move(PrebuiltModulesASTMap), StableDirs); + ScanInstance.addDependencyCollector(MDC); + ScanInstance.setGenModuleActionWrapper( + [&Controller = Controller](const FrontendOptions &Opts, + std::unique_ptr Wrapped) { + return std::make_unique(std::move(Wrapped), + Controller); + }); + break; + } + + return MDC; +} +} // namespace clang::tooling::dependencies + +bool DependencyScanningAction::runInvocation( + std::shared_ptr Invocation, + IntrusiveRefCntPtr FS, + std::shared_ptr PCHContainerOps, + DiagnosticConsumer *DiagConsumer) { + // Making sure that we canonicalize the defines before we create the deep + // copy to avoid unnecessary variants in the scanner and in the resulting + // explicit command lines. + if (any(Service.getOptimizeArgs() & ScanningOptimizations::Macros)) + canonicalizeDefines(Invocation->getPreprocessorOpts()); + + // Make a deep copy of the original Clang invocation. + CompilerInvocation OriginalInvocation(*Invocation); + + if (Scanned) { + CompilerInstance &ScanInstance = *ScanInstanceStorage; + auto reportError = [&ScanInstance](Error &&E) -> bool { + ScanInstance.getDiagnostics().Report(diag::err_cas_depscan_failed) + << std::move(E); + return false; + }; + + // Scanning runs once for the first -cc1 invocation in a chain of driver + // jobs. For any dependent jobs, reuse the scanning result and just + // update the LastCC1Arguments to correspond to the new invocation. + // FIXME: to support multi-arch builds, each arch requires a separate scan + if (MDC) + MDC->applyDiscoveredDependencies(OriginalInvocation); + + if (Error E = Controller.finalize(ScanInstance, OriginalInvocation)) + return reportError(std::move(E)); + + LastCC1Arguments = OriginalInvocation.getCC1CommandLine(); + LastCC1CacheKey = Controller.getCacheKey(OriginalInvocation); + return true; + } + + Scanned = true; + + // Create a compiler instance to handle the actual work. + auto ModCache = makeInProcessModuleCache(Service.getModuleCacheEntries()); + ScanInstanceStorage.emplace(std::move(Invocation), std::move(PCHContainerOps), + ModCache.get()); + CompilerInstance &ScanInstance = *ScanInstanceStorage; + ScanInstance.getInvocation().getCASOpts() = CASOpts; + + assert(!DiagConsumerFinished && "attempt to reuse finished consumer"); + if (!initializeScanCompilerInstance(ScanInstance, FS, DiagConsumer, Service, + DepFS, DiagGenerationAsCompilation, + VerboseOS, DepCASFS)) + return false; + + llvm::SmallVector StableDirs = getInitialStableDirs(ScanInstance); + auto MaybePrebuiltModulesASTMap = + computePrebuiltModulesASTMap(ScanInstance, StableDirs); + if (!MaybePrebuiltModulesASTMap) + return false; + + auto DepOutputOpts = takeDependencyOutputOptionsFrom( + ScanInstance, Service.getFormat() == ScanningOutputFormat::Make); + + MDC = initializeScanInstanceDependencyCollector( + ScanInstance, std::move(DepOutputOpts), WorkingDirectory, Consumer, + Service, OriginalInvocation, Controller, *MaybePrebuiltModulesASTMap, + StableDirs, EmitDependencyFile); + + std::unique_ptr Action; + + if (Service.getFormat() == ScanningOutputFormat::P1689) + Action = std::make_unique(); + else if (ModuleName) + Action = std::make_unique(*ModuleName); + else + Action = std::make_unique(); + + // Normally this would be handled by GeneratePCHAction + if (ScanInstance.getFrontendOpts().ProgramAction == frontend::GeneratePCH) + ScanInstance.getLangOpts().CompilingPCH = true; + + auto reportError = [&ScanInstance](Error &&E) -> bool { + ScanInstance.getDiagnostics().Report(diag::err_cas_depscan_failed) + << std::move(E); + return false; + }; + + if (Error E = Controller.initialize(ScanInstance, OriginalInvocation)) + return reportError(std::move(E)); + + if (ScanInstance.getDiagnostics().hasErrorOccurred()) + return false; + + // ExecuteAction is responsible for calling finish. + DiagConsumerFinished = true; + + if (!ScanInstance.ExecuteAction(*Action)) + return false; + + if (MDC) + MDC->applyDiscoveredDependencies(OriginalInvocation); + + if (Error E = Controller.finalize(ScanInstance, OriginalInvocation)) + return reportError(std::move(E)); + + // Forward any CAS results to consumer. + std::string ID = OriginalInvocation.getFileSystemOpts().CASFileSystemRootID; + if (!ID.empty()) + Consumer.handleCASFileSystemRootID(std::move(ID)); + ID = OriginalInvocation.getFrontendOpts().CASIncludeTreeID; + if (!ID.empty()) + Consumer.handleIncludeTreeID(std::move(ID)); + + LastCC1Arguments = OriginalInvocation.getCC1CommandLine(); + LastCC1CacheKey = Controller.getCacheKey(OriginalInvocation); + + return true; +} + +std::vector DependencyScanningAction::takeLastCC1Arguments() { + std::vector Result; + std::swap(Result, LastCC1Arguments); // Reset LastCC1Arguments to empty. + return Result; +} + +std::optional DependencyScanningAction::takeLastCC1CacheKey() { + std::optional Result; + std::swap(Result, LastCC1CacheKey); + return Result; +} + +IntrusiveRefCntPtr +DependencyScanningAction::getDepScanFS() { + if (DepFS) { + assert(!DepCASFS && "CAS DepFS should not be set"); + return DepFS; + } + if (DepCASFS) { + assert(!DepFS && "DepFS should not be set"); + return DepCASFS; + } + return nullptr; +} diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.h b/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.h new file mode 100644 index 0000000000000..8e5df7b92d404 --- /dev/null +++ b/clang/lib/Tooling/DependencyScanning/DependencyScannerImpl.h @@ -0,0 +1,172 @@ +//===- DependencyScanner.h - Performs module dependency scanning *- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLING_DEPENDENCYSCANNING_DEPENDENCYSCANNER_H +#define LLVM_CLANG_TOOLING_DEPENDENCYSCANNING_DEPENDENCYSCANNER_H + +#include "clang/Driver/Compilation.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/CompilerInvocation.h" +#include "clang/Frontend/TextDiagnosticPrinter.h" +#include "clang/Serialization/ObjectFilePCHContainerReader.h" +#include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h" +#include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" + +namespace clang { +class DiagnosticConsumer; + +namespace tooling { +namespace dependencies { +class DependencyScanningService; +class DependencyConsumer; +class DependencyActionController; +class DependencyScanningWorkerFilesystem; + +class DependencyScanningAction { +public: + DependencyScanningAction( + DependencyScanningService &Service, StringRef WorkingDirectory, + DependencyConsumer &Consumer, DependencyActionController &Controller, + llvm::IntrusiveRefCntPtr DepFS, + llvm::IntrusiveRefCntPtr DepCASFS, + llvm::IntrusiveRefCntPtr CacheFS, + bool EmitDependencyFile, bool DiagGenerationAsCompilation, + const CASOptions &CASOpts, + std::optional ModuleName = std::nullopt, + raw_ostream *VerboseOS = nullptr) + : Service(Service), WorkingDirectory(WorkingDirectory), + Consumer(Consumer), Controller(Controller), DepFS(std::move(DepFS)), + DepCASFS(std::move(DepCASFS)), CacheFS(std::move(CacheFS)), + CASOpts(CASOpts), EmitDependencyFile(EmitDependencyFile), + DiagGenerationAsCompilation(DiagGenerationAsCompilation), + ModuleName(ModuleName), VerboseOS(VerboseOS) {} + bool runInvocation(std::shared_ptr Invocation, + IntrusiveRefCntPtr FS, + std::shared_ptr PCHContainerOps, + DiagnosticConsumer *DiagConsumer); + + bool hasScanned() const { return Scanned; } + bool hasDiagConsumerFinished() const { return DiagConsumerFinished; } + + /// Take the cc1 arguments corresponding to the most recent invocation used + /// with this action. Any modifications implied by the discovered dependencies + /// will have already been applied. + std::vector takeLastCC1Arguments(); + + std::optional takeLastCC1CacheKey(); + + IntrusiveRefCntPtr getDepScanFS(); + +private: + DependencyScanningService &Service; + StringRef WorkingDirectory; + DependencyConsumer &Consumer; + DependencyActionController &Controller; + llvm::IntrusiveRefCntPtr DepFS; + llvm::IntrusiveRefCntPtr DepCASFS; + llvm::IntrusiveRefCntPtr CacheFS; + const CASOptions &CASOpts; + bool EmitDependencyFile = false; + bool DiagGenerationAsCompilation; + std::optional ModuleName; + std::optional ScanInstanceStorage; + std::shared_ptr MDC; + std::vector LastCC1Arguments; + std::optional LastCC1CacheKey; + bool Scanned = false; + bool DiagConsumerFinished = false; + raw_ostream *VerboseOS; +}; + +// Helper functions and data types. +std::unique_ptr +createDiagOptions(ArrayRef CommandLine); + +struct DignosticsEngineWithDiagOpts { + // We need to bound the lifetime of the DiagOpts used to create the + // DiganosticsEngine with the DiagnosticsEngine itself. + std::unique_ptr DiagOpts; + IntrusiveRefCntPtr DiagEngine; + + DignosticsEngineWithDiagOpts(ArrayRef CommandLine, + IntrusiveRefCntPtr FS, + DiagnosticConsumer &DC); +}; + +struct TextDiagnosticsPrinterWithOutput { + // We need to bound the lifetime of the data that supports the DiagPrinter + // with it together so they have the same lifetime. + std::string DiagnosticOutput; + llvm::raw_string_ostream DiagnosticsOS; + std::unique_ptr DiagOpts; + TextDiagnosticPrinter DiagPrinter; + + TextDiagnosticsPrinterWithOutput(ArrayRef CommandLine) + : DiagnosticsOS(DiagnosticOutput), + DiagOpts(createDiagOptions(CommandLine)), + DiagPrinter(DiagnosticsOS, *DiagOpts) {} +}; + +std::pair, std::unique_ptr> +buildCompilation(ArrayRef ArgStrs, DiagnosticsEngine &Diags, + IntrusiveRefCntPtr FS, + llvm::BumpPtrAllocator &Alloc); + +std::unique_ptr +createCompilerInvocation(ArrayRef CommandLine, + DiagnosticsEngine &Diags); + +std::pair, std::vector> +initVFSForTUBuferScanning( + IntrusiveRefCntPtr BaseFS, + ArrayRef CommandLine, StringRef WorkingDirectory, + llvm::MemoryBufferRef TUBuffer, std::shared_ptr CAS, + IntrusiveRefCntPtr DepCASFS); + +std::pair, std::vector> +initVFSForByNameScanning( + IntrusiveRefCntPtr BaseFS, + ArrayRef CommandLine, StringRef WorkingDirectory, + StringRef ModuleName, std::shared_ptr CAS, + IntrusiveRefCntPtr DepCASFS); + +bool initializeScanCompilerInstance( + CompilerInstance &ScanInstance, + IntrusiveRefCntPtr FS, + DiagnosticConsumer *DiagConsumer, DependencyScanningService &Service, + IntrusiveRefCntPtr DepFS, + bool DiagGenerationAsCompilation, raw_ostream *VerboseOS, + llvm::IntrusiveRefCntPtr DepCASFS); + +SmallVector +getInitialStableDirs(const CompilerInstance &ScanInstance); + +std::optional +computePrebuiltModulesASTMap(CompilerInstance &ScanInstance, + SmallVector &StableDirs); + +std::unique_ptr +takeDependencyOutputOptionsFrom(CompilerInstance &ScanInstance, + bool ForceIncludeSystemHeaders); + +/// Create the dependency collector that will collect the produced +/// dependencies. May return the created ModuleDepCollector depending +/// on the scanning format. +std::shared_ptr initializeScanInstanceDependencyCollector( + CompilerInstance &ScanInstance, + std::unique_ptr DepOutputOpts, + StringRef WorkingDirectory, DependencyConsumer &Consumer, + DependencyScanningService &Service, CompilerInvocation &Inv, + DependencyActionController &Controller, + PrebuiltModulesAttrsMap PrebuiltModulesASTMap, + llvm::SmallVector &StableDirs, bool EmitDependencyFile); +} // namespace dependencies +} // namespace tooling +} // namespace clang + +#endif diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp index 487d43dc4ec52..ac5fff1d8ecb7 100644 --- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp +++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp @@ -7,827 +7,16 @@ //===----------------------------------------------------------------------===// #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h" -#include "clang/Basic/DiagnosticCAS.h" -#include "clang/Basic/DiagnosticDriver.h" +#include "DependencyScannerImpl.h" #include "clang/Basic/DiagnosticFrontend.h" -#include "clang/Basic/DiagnosticSerialization.h" -#include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" -#include "clang/Driver/Job.h" #include "clang/Driver/Tool.h" -#include "clang/Frontend/CompileJobCacheKey.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/CompilerInvocation.h" -#include "clang/Frontend/FrontendActions.h" -#include "clang/Frontend/MultiplexConsumer.h" -#include "clang/Frontend/TextDiagnosticPrinter.h" -#include "clang/Frontend/Utils.h" -#include "clang/Lex/PreprocessorOptions.h" -#include "clang/Serialization/ObjectFilePCHContainerReader.h" -#include "clang/Tooling/DependencyScanning/DependencyScanningService.h" -#include "clang/Tooling/DependencyScanning/InProcessModuleCache.h" -#include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" -#include "clang/Tooling/DependencyScanning/ScanAndUpdateArgs.h" -#include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/CAS/CASProvidingFileSystem.h" -#include "llvm/CAS/CachingOnDiskFileSystem.h" -#include "llvm/CAS/ObjectStore.h" -#include "llvm/Support/Allocator.h" -#include "llvm/Support/Error.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/PrefixMapper.h" -#include "llvm/TargetParser/Host.h" -#include using namespace clang; using namespace tooling; using namespace dependencies; using llvm::Error; -namespace { - -/// Forwards the gatherered dependencies to the consumer. -class DependencyConsumerForwarder : public DependencyFileGenerator { -public: - DependencyConsumerForwarder(std::unique_ptr Opts, - StringRef WorkingDirectory, DependencyConsumer &C, - bool EmitDependencyFile) - : DependencyFileGenerator(*Opts), WorkingDirectory(WorkingDirectory), - Opts(std::move(Opts)), C(C), EmitDependencyFile(EmitDependencyFile) {} - - void finishedMainFile(DiagnosticsEngine &Diags) override { - C.handleDependencyOutputOpts(*Opts); - llvm::SmallString<256> CanonPath; - for (const auto &File : getDependencies()) { - CanonPath = File; - llvm::sys::path::remove_dots(CanonPath, /*remove_dot_dot=*/true); - llvm::sys::path::make_absolute(WorkingDirectory, CanonPath); - C.handleFileDependency(CanonPath); - } - if (EmitDependencyFile) - DependencyFileGenerator::finishedMainFile(Diags); - } - -private: - StringRef WorkingDirectory; - std::unique_ptr Opts; - DependencyConsumer &C; - bool EmitDependencyFile = false; -}; - -static bool checkHeaderSearchPaths(const HeaderSearchOptions &HSOpts, - const HeaderSearchOptions &ExistingHSOpts, - DiagnosticsEngine *Diags, - const LangOptions &LangOpts) { - if (LangOpts.Modules) { - if (HSOpts.VFSOverlayFiles != ExistingHSOpts.VFSOverlayFiles) { - if (Diags) { - Diags->Report(diag::warn_pch_vfsoverlay_mismatch); - auto VFSNote = [&](int Type, ArrayRef VFSOverlays) { - if (VFSOverlays.empty()) { - Diags->Report(diag::note_pch_vfsoverlay_empty) << Type; - } else { - std::string Files = llvm::join(VFSOverlays, "\n"); - Diags->Report(diag::note_pch_vfsoverlay_files) << Type << Files; - } - }; - VFSNote(0, HSOpts.VFSOverlayFiles); - VFSNote(1, ExistingHSOpts.VFSOverlayFiles); - } - } - } - return false; -} - -using PrebuiltModuleFilesT = decltype(HeaderSearchOptions::PrebuiltModuleFiles); - -/// A listener that collects the imported modules and the input -/// files. While visiting, collect vfsoverlays and file inputs that determine -/// whether prebuilt modules fully resolve in stable directories. -class PrebuiltModuleListener : public ASTReaderListener { -public: - PrebuiltModuleListener(CompilerInstance &CI, - PrebuiltModuleFilesT &PrebuiltModuleFiles, - llvm::SmallVector &NewModuleFiles, - PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, - DiagnosticsEngine &Diags, - const ArrayRef StableDirs) - : CI(CI), PrebuiltModuleFiles(PrebuiltModuleFiles), - NewModuleFiles(NewModuleFiles), - PrebuiltModulesASTMap(PrebuiltModulesASTMap), Diags(Diags), - StableDirs(StableDirs) {} - - bool needsImportVisitation() const override { return true; } - bool needsInputFileVisitation() override { return true; } - bool needsSystemInputFileVisitation() override { return true; } - - /// Accumulate the modules are transitively depended on by the initial - /// prebuilt module. - void visitImport(StringRef ModuleName, StringRef Filename) override { - if (PrebuiltModuleFiles.insert({ModuleName.str(), Filename.str()}).second) - NewModuleFiles.push_back(Filename.str()); - - auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(Filename); - PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; - if (PrebuiltMapEntry.second) - PrebuiltModule.setInStableDir(!StableDirs.empty()); - - if (auto It = PrebuiltModulesASTMap.find(CurrentFile); - It != PrebuiltModulesASTMap.end() && CurrentFile != Filename) - PrebuiltModule.addDependent(It->getKey()); - } - - /// For each input file discovered, check whether it's external path is in a - /// stable directory. Traversal is stopped if the current module is not - /// considered stable. - bool visitInputFile(StringRef FilenameAsRequested, StringRef Filename, - bool isSystem, bool isOverridden, - bool isExplicitModule) override { - if (StableDirs.empty()) - return false; - auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(CurrentFile); - if ((PrebuiltEntryIt == PrebuiltModulesASTMap.end()) || - (!PrebuiltEntryIt->second.isInStableDir())) - return false; - - PrebuiltEntryIt->second.setInStableDir( - isPathInStableDir(StableDirs, Filename)); - return PrebuiltEntryIt->second.isInStableDir(); - } - - /// Update which module that is being actively traversed. - void visitModuleFile(StringRef Filename, - serialization::ModuleKind Kind) override { - // If the CurrentFile is not - // considered stable, update any of it's transitive dependents. - auto PrebuiltEntryIt = PrebuiltModulesASTMap.find(CurrentFile); - if ((PrebuiltEntryIt != PrebuiltModulesASTMap.end()) && - !PrebuiltEntryIt->second.isInStableDir()) - PrebuiltEntryIt->second.updateDependentsNotInStableDirs( - PrebuiltModulesASTMap); - CurrentFile = Filename; - } - - /// Check the header search options for a given module when considering - /// if the module comes from stable directories. - bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, - StringRef ModuleFilename, - StringRef SpecificModuleCachePath, - bool Complain) override { - - auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(CurrentFile); - PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; - if (PrebuiltMapEntry.second) - PrebuiltModule.setInStableDir(!StableDirs.empty()); - - if (PrebuiltModule.isInStableDir()) - PrebuiltModule.setInStableDir(areOptionsInStableDir(StableDirs, HSOpts)); - - return false; - } - - /// Accumulate vfsoverlays used to build these prebuilt modules. - bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, - bool Complain) override { - - auto PrebuiltMapEntry = PrebuiltModulesASTMap.try_emplace(CurrentFile); - PrebuiltModuleASTAttrs &PrebuiltModule = PrebuiltMapEntry.first->second; - if (PrebuiltMapEntry.second) - PrebuiltModule.setInStableDir(!StableDirs.empty()); - - PrebuiltModule.setVFS( - llvm::StringSet<>(llvm::from_range, HSOpts.VFSOverlayFiles)); - - return checkHeaderSearchPaths( - HSOpts, CI.getHeaderSearchOpts(), Complain ? &Diags : nullptr, CI.getLangOpts()); - } - - bool readModuleCacheKey(StringRef ModuleName, StringRef Filename, - StringRef CacheKey) override { - CI.getFrontendOpts().ModuleCacheKeys.emplace_back(std::string(Filename), - std::string(CacheKey)); - // FIXME: add name/path of the importing module? - return CI.addCachedModuleFile(Filename, CacheKey, "imported module"); - } - -private: - CompilerInstance &CI; - PrebuiltModuleFilesT &PrebuiltModuleFiles; - llvm::SmallVector &NewModuleFiles; - PrebuiltModulesAttrsMap &PrebuiltModulesASTMap; - DiagnosticsEngine &Diags; - std::string CurrentFile; - const ArrayRef StableDirs; -}; - -/// Visit the given prebuilt module and collect all of the modules it -/// transitively imports and contributing input files. -static bool visitPrebuiltModule(StringRef PrebuiltModuleFilename, - CompilerInstance &CI, - PrebuiltModuleFilesT &ModuleFiles, - PrebuiltModulesAttrsMap &PrebuiltModulesASTMap, - DiagnosticsEngine &Diags, - const ArrayRef StableDirs) { - // List of module files to be processed. - llvm::SmallVector Worklist; - PrebuiltModuleListener Listener(CI, ModuleFiles, Worklist, - PrebuiltModulesASTMap, Diags, StableDirs); - - Listener.visitModuleFile(PrebuiltModuleFilename, - serialization::MK_ExplicitModule); - if (ASTReader::readASTFileControlBlock( - PrebuiltModuleFilename, CI.getFileManager(), CI.getModuleCache(), - CI.getPCHContainerReader(), - /*FindModuleFileExtensions=*/false, Listener, - /*ValidateDiagnosticOptions=*/false, ASTReader::ARR_OutOfDate)) - return true; - - while (!Worklist.empty()) { - Listener.visitModuleFile(Worklist.back(), serialization::MK_ExplicitModule); - if (ASTReader::readASTFileControlBlock( - Worklist.pop_back_val(), CI.getFileManager(), CI.getModuleCache(), - CI.getPCHContainerReader(), - /*FindModuleFileExtensions=*/false, Listener, - /*ValidateDiagnosticOptions=*/false)) - return true; - } - return false; -} - -/// Transform arbitrary file name into an object-like file name. -static std::string makeObjFileName(StringRef FileName) { - SmallString<128> ObjFileName(FileName); - llvm::sys::path::replace_extension(ObjFileName, "o"); - return std::string(ObjFileName); -} - -/// Deduce the dependency target based on the output file and input files. -static std::string -deduceDepTarget(const std::string &OutputFile, - const SmallVectorImpl &InputFiles) { - if (OutputFile != "-") - return OutputFile; - - if (InputFiles.empty() || !InputFiles.front().isFile()) - return "clang-scan-deps\\ dependency"; - - return makeObjFileName(InputFiles.front().getFile()); -} - -/// Sanitize diagnostic options for dependency scan. -static void sanitizeDiagOpts(DiagnosticOptions &DiagOpts) { - // Don't print 'X warnings and Y errors generated'. - DiagOpts.ShowCarets = false; - // Don't write out diagnostic file. - DiagOpts.DiagnosticSerializationFile.clear(); - // Don't emit warnings except for scanning specific warnings. - // TODO: It would be useful to add a more principled way to ignore all - // warnings that come from source code. The issue is that we need to - // ignore warnings that could be surpressed by - // `#pragma clang diagnostic`, while still allowing some scanning - // warnings for things we're not ready to turn into errors yet. - // See `test/ClangScanDeps/diagnostic-pragmas.c` for an example. - llvm::erase_if(DiagOpts.Warnings, [](StringRef Warning) { - return llvm::StringSwitch(Warning) - .Cases("pch-vfs-diff", "error=pch-vfs-diff", false) - .StartsWith("no-error=", false) - .Default(true); - }); -} - -// Clang implements -D and -U by splatting text into a predefines buffer. This -// allows constructs such as `-DFඞ=3 "-D F\u{0D9E} 4 3 2”` to be accepted and -// define the same macro, or adding C++ style comments before the macro name. -// -// This function checks that the first non-space characters in the macro -// obviously form an identifier that can be uniqued on without lexing. Failing -// to do this could lead to changing the final definition of a macro. -// -// We could set up a preprocessor and actually lex the name, but that's very -// heavyweight for a situation that will almost never happen in practice. -static std::optional getSimpleMacroName(StringRef Macro) { - StringRef Name = Macro.split("=").first.ltrim(" \t"); - std::size_t I = 0; - - auto FinishName = [&]() -> std::optional { - StringRef SimpleName = Name.slice(0, I); - if (SimpleName.empty()) - return std::nullopt; - return SimpleName; - }; - - for (; I != Name.size(); ++I) { - switch (Name[I]) { - case '(': // Start of macro parameter list - case ' ': // End of macro name - case '\t': - return FinishName(); - case '_': - continue; - default: - if (llvm::isAlnum(Name[I])) - continue; - return std::nullopt; - } - } - return FinishName(); -} - -static void canonicalizeDefines(PreprocessorOptions &PPOpts) { - using MacroOpt = std::pair; - std::vector SimpleNames; - SimpleNames.reserve(PPOpts.Macros.size()); - std::size_t Index = 0; - for (const auto &M : PPOpts.Macros) { - auto SName = getSimpleMacroName(M.first); - // Skip optimizing if we can't guarantee we can preserve relative order. - if (!SName) - return; - SimpleNames.emplace_back(*SName, Index); - ++Index; - } - - llvm::stable_sort(SimpleNames, llvm::less_first()); - // Keep the last instance of each macro name by going in reverse - auto NewEnd = std::unique( - SimpleNames.rbegin(), SimpleNames.rend(), - [](const MacroOpt &A, const MacroOpt &B) { return A.first == B.first; }); - SimpleNames.erase(SimpleNames.begin(), NewEnd.base()); - - // Apply permutation. - decltype(PPOpts.Macros) NewMacros; - NewMacros.reserve(SimpleNames.size()); - for (std::size_t I = 0, E = SimpleNames.size(); I != E; ++I) { - std::size_t OriginalIndex = SimpleNames[I].second; - // We still emit undefines here as they may be undefining a predefined macro - NewMacros.push_back(std::move(PPOpts.Macros[OriginalIndex])); - } - std::swap(PPOpts.Macros, NewMacros); -} - -/// Builds a dependency file after reversing prefix mappings. This allows -/// emitting a .d file that has real paths where they would otherwise be -/// canonicalized. -class ReversePrefixMappingDependencyFileGenerator - : public DependencyFileGenerator { - llvm::PrefixMapper ReverseMapper; - -public: - ReversePrefixMappingDependencyFileGenerator( - const DependencyOutputOptions &Opts) - : DependencyFileGenerator(Opts) {} - - void initialize(const CompilerInvocation &CI) { - llvm::PrefixMapper Mapper; - DepscanPrefixMapping::configurePrefixMapper(CI, Mapper); - if (Mapper.empty()) - return; - - ReverseMapper.addInverseRange(Mapper.getMappings()); - ReverseMapper.sort(); - } - - void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem, - bool IsModuleFile, bool IsMissing) override { - if (ReverseMapper.empty()) - return DependencyFileGenerator::maybeAddDependency( - Filename, FromModule, IsSystem, IsModuleFile, IsMissing); - - // We may get canonicalized paths if prefix headers/PCH are used, so make - // sure to remap them back to original source paths. - SmallString<256> New{Filename}; - ReverseMapper.mapInPlace(New); - return DependencyFileGenerator::maybeAddDependency( - New, FromModule, IsSystem, IsModuleFile, IsMissing); - } -}; - -/// See \c WrapScanModuleBuildAction. -class WrapScanModuleBuildConsumer : public ASTConsumer { -public: - WrapScanModuleBuildConsumer(CompilerInstance &CI, - DependencyActionController &Controller) - : CI(CI), Controller(Controller) {} - - void HandleTranslationUnit(ASTContext &Ctx) override { - if (auto E = Controller.finalizeModuleBuild(CI)) - Ctx.getDiagnostics().Report(diag::err_cas_depscan_failed) << std::move(E); - } - -private: - CompilerInstance &CI; - DependencyActionController &Controller; -}; - -/// A wrapper for implicit module build actions in the scanner. -class WrapScanModuleBuildAction : public WrapperFrontendAction { -public: - WrapScanModuleBuildAction(std::unique_ptr WrappedAction, - DependencyActionController &Controller) - : WrapperFrontendAction(std::move(WrappedAction)), - Controller(Controller) {} - -private: - bool BeginInvocation(CompilerInstance &CI) override { - if (auto E = Controller.initializeModuleBuild(CI)) { - CI.getDiagnostics().Report(diag::err_cas_depscan_failed) << std::move(E); - return false; - } - return WrapperFrontendAction::BeginInvocation(CI); - } - - std::unique_ptr CreateASTConsumer(CompilerInstance &CI, - StringRef InFile) override { - auto OtherConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile); - if (!OtherConsumer) - return nullptr; - Module *M = CI.getPreprocessor().getCurrentModule(); - assert(M && "WrapScanModuleBuildAction should only be used with module"); - if (!M) - return OtherConsumer; - auto Consumer = - std::make_unique(CI, Controller); - std::vector> Consumers; - Consumers.push_back(std::move(Consumer)); - Consumers.push_back(std::move(OtherConsumer)); - return std::make_unique(std::move(Consumers)); - } - -private: - DependencyActionController &Controller; -}; - -class ScanningDependencyDirectivesGetter : public DependencyDirectivesGetter { - DependencyScanningWorkerFilesystem *DepFS; - -public: - ScanningDependencyDirectivesGetter(FileManager &FileMgr) : DepFS(nullptr) { - FileMgr.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &FS) { - auto *DFS = llvm::dyn_cast(&FS); - if (DFS) { - assert(!DepFS && "Found multiple scanning VFSs"); - DepFS = DFS; - } - }); - assert(DepFS && "Did not find scanning VFS"); - } - - std::unique_ptr - cloneFor(FileManager &FileMgr) override { - return std::make_unique(FileMgr); - } - - std::optional> - operator()(FileEntryRef File) override { - return DepFS->getDirectiveTokens(File.getName()); - } -}; - -// FIXME: Make this thread-safe by pulling the FS out of `FileManager`. -class CASDependencyDirectivesGetter : public DependencyDirectivesGetter { - DependencyScanningCASFilesystem *DepCASFS; - -public: - CASDependencyDirectivesGetter(DependencyScanningCASFilesystem *DepCASFS) - : DepCASFS(DepCASFS) {} - - std::unique_ptr - cloneFor(FileManager &FileMgr) override { - (void)FileMgr; - return std::make_unique(DepCASFS); - } - - std::optional> - operator()(FileEntryRef File) override { - return DepCASFS->getDirectiveTokens(File.getName()); - } -}; - -/// A clang tool that runs the preprocessor in a mode that's optimized for -/// dependency scanning for the given compiler invocation. -class DependencyScanningAction { -public: - DependencyScanningAction( - DependencyScanningService &Service, StringRef WorkingDirectory, - DependencyConsumer &Consumer, DependencyActionController &Controller, - llvm::IntrusiveRefCntPtr DepFS, - llvm::IntrusiveRefCntPtr DepCASFS, - llvm::IntrusiveRefCntPtr CacheFS, - bool EmitDependencyFile, - bool DiagGenerationAsCompilation, const CASOptions &CASOpts, - std::optional ModuleName = std::nullopt, - raw_ostream *VerboseOS = nullptr) - : Service(Service), WorkingDirectory(WorkingDirectory), Consumer(Consumer), - Controller(Controller), DepFS(std::move(DepFS)), - DepCASFS(std::move(DepCASFS)), CacheFS(std::move(CacheFS)), - CASOpts(CASOpts), EmitDependencyFile(EmitDependencyFile), - DiagGenerationAsCompilation(DiagGenerationAsCompilation), - ModuleName(ModuleName), VerboseOS(VerboseOS) {} - - bool runInvocation(std::shared_ptr Invocation, - IntrusiveRefCntPtr FS, - std::shared_ptr PCHContainerOps, - DiagnosticConsumer *DiagConsumer) { - // Make a deep copy of the original Clang invocation. - CompilerInvocation OriginalInvocation(*Invocation); - if (any(Service.getOptimizeArgs() & ScanningOptimizations::Macros)) - canonicalizeDefines(OriginalInvocation.getPreprocessorOpts()); - - if (Scanned) { - CompilerInstance &ScanInstance = *ScanInstanceStorage; - auto reportError = [&ScanInstance](Error &&E) -> bool { - ScanInstance.getDiagnostics().Report(diag::err_cas_depscan_failed) - << std::move(E); - return false; - }; - - // Scanning runs once for the first -cc1 invocation in a chain of driver - // jobs. For any dependent jobs, reuse the scanning result and just - // update the LastCC1Arguments to correspond to the new invocation. - // FIXME: to support multi-arch builds, each arch requires a separate scan - if (MDC) - MDC->applyDiscoveredDependencies(OriginalInvocation); - - if (Error E = Controller.finalize(ScanInstance, OriginalInvocation)) - return reportError(std::move(E)); - - LastCC1Arguments = OriginalInvocation.getCC1CommandLine(); - LastCC1CacheKey = Controller.getCacheKey(OriginalInvocation); - return true; - } - - Scanned = true; - - // Create a compiler instance to handle the actual work. - auto ModCache = makeInProcessModuleCache(Service.getModuleCacheEntries()); - ScanInstanceStorage.emplace(std::move(Invocation), - std::move(PCHContainerOps), ModCache.get()); - CompilerInstance &ScanInstance = *ScanInstanceStorage; - ScanInstance.getInvocation().getCASOpts() = CASOpts; - ScanInstance.setBuildingModule(false); - - ScanInstance.createVirtualFileSystem(FS, DiagConsumer); - - // Create the compiler's actual diagnostics engine. - if (!DiagGenerationAsCompilation) - sanitizeDiagOpts(ScanInstance.getDiagnosticOpts()); - assert(!DiagConsumerFinished && "attempt to reuse finished consumer"); - ScanInstance.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false); - if (!ScanInstance.hasDiagnostics()) - return false; - if (VerboseOS) - ScanInstance.setVerboseOutputStream(*VerboseOS); - - ScanInstance.getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath = - true; - - if (ScanInstance.getHeaderSearchOpts().ModulesValidateOncePerBuildSession) - ScanInstance.getHeaderSearchOpts().BuildSessionTimestamp = - Service.getBuildSessionTimestamp(); - - ScanInstance.getFrontendOpts().DisableFree = false; - ScanInstance.getFrontendOpts().GenerateGlobalModuleIndex = false; - ScanInstance.getFrontendOpts().UseGlobalModuleIndex = false; - // This will prevent us compiling individual modules asynchronously since - // FileManager is not thread-safe, but it does improve performance for now. - ScanInstance.getFrontendOpts().ModulesShareFileManager = true; - if (DepCASFS) - ScanInstance.getFrontendOpts().ModulesShareFileManager = false; - ScanInstance.getHeaderSearchOpts().ModuleFormat = "raw"; - ScanInstance.getHeaderSearchOpts().ModulesIncludeVFSUsage = - any(Service.getOptimizeArgs() & ScanningOptimizations::VFS); - - // Create a new FileManager to match the invocation's FileSystemOptions. - ScanInstance.createFileManager(); - - // Use the dependency scanning optimized file system if requested to do so. - if (DepFS) { - DepFS->resetBypassedPathPrefix(); - if (!ScanInstance.getHeaderSearchOpts().ModuleCachePath.empty()) { - SmallString<256> ModulesCachePath; - normalizeModuleCachePath( - ScanInstance.getFileManager(), - ScanInstance.getHeaderSearchOpts().ModuleCachePath, - ModulesCachePath); - DepFS->setBypassedPathPrefix(ModulesCachePath); - } - - ScanInstance.setDependencyDirectivesGetter( - std::make_unique( - ScanInstance.getFileManager())); - } - - // CAS Implementation. - if (DepCASFS) - ScanInstance.setDependencyDirectivesGetter( - std::make_unique(DepCASFS.get())); - - ScanInstance.createSourceManager(); - - // Create a collection of stable directories derived from the ScanInstance - // for determining whether module dependencies would fully resolve from - // those directories. - llvm::SmallVector StableDirs; - const StringRef Sysroot = ScanInstance.getHeaderSearchOpts().Sysroot; - if (!Sysroot.empty() && - (llvm::sys::path::root_directory(Sysroot) != Sysroot)) - StableDirs = {Sysroot, ScanInstance.getHeaderSearchOpts().ResourceDir}; - - // Store a mapping of prebuilt module files and their properties like header - // search options. This will prevent the implicit build to create duplicate - // modules and will force reuse of the existing prebuilt module files - // instead. - PrebuiltModulesAttrsMap PrebuiltModulesASTMap; - - if (!ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty()) - if (visitPrebuiltModule( - ScanInstance.getPreprocessorOpts().ImplicitPCHInclude, - ScanInstance, - ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles, - PrebuiltModulesASTMap, ScanInstance.getDiagnostics(), StableDirs)) - return false; - - // Create the dependency collector that will collect the produced - // dependencies. - // - // This also moves the existing dependency output options from the - // invocation to the collector. The options in the invocation are reset, - // which ensures that the compiler won't create new dependency collectors, - // and thus won't write out the extra '.d' files to disk. - auto Opts = std::make_unique(); - std::swap(*Opts, ScanInstance.getInvocation().getDependencyOutputOpts()); - // We need at least one -MT equivalent for the generator of make dependency - // files to work. - if (Opts->Targets.empty()) - Opts->Targets = { - deduceDepTarget(ScanInstance.getFrontendOpts().OutputFile, - ScanInstance.getFrontendOpts().Inputs)}; - if (Service.getFormat() == ScanningOutputFormat::Make) { - // Only 'Make' scanning needs to force this because that mode depends on - // getting the dependencies directly from \p DependencyFileGenerator. - Opts->IncludeSystemHeaders = true; - } - - auto reportError = [&ScanInstance](Error &&E) -> bool { - ScanInstance.getDiagnostics().Report(diag::err_cas_depscan_failed) - << std::move(E); - return false; - }; - - // FIXME: The caller APIs in \p DependencyScanningTool expect a specific - // DependencyCollector to get attached to the preprocessor in order to - // function properly (e.g. \p FullDependencyConsumer needs \p - // ModuleDepCollector) but this association is very indirect via the value - // of the \p ScanningOutputFormat. We should remove \p Format field from - // \p DependencyScanningAction, and have the callers pass in a - // “DependencyCollector factory” so the connection of collector<->consumer - // is explicit in each \p DependencyScanningTool function. - switch (Service.getFormat()) { - case ScanningOutputFormat::Make: - case ScanningOutputFormat::Tree: - ScanInstance.addDependencyCollector( - std::make_shared( - std::move(Opts), WorkingDirectory, Consumer, EmitDependencyFile)); - break; - case ScanningOutputFormat::IncludeTree: - case ScanningOutputFormat::P1689: - case ScanningOutputFormat::Full: - case ScanningOutputFormat::FullTree: - case ScanningOutputFormat::FullIncludeTree: - if (EmitDependencyFile) { - auto DFG = - std::make_shared( - *Opts); - DFG->initialize(ScanInstance.getInvocation()); - ScanInstance.addDependencyCollector(std::move(DFG)); - } - - MDC = std::make_shared( - Service, std::move(Opts), ScanInstance, Consumer, Controller, - OriginalInvocation, std::move(PrebuiltModulesASTMap), StableDirs); - ScanInstance.addDependencyCollector(MDC); - ScanInstance.setGenModuleActionWrapper( - [&Controller = Controller](const FrontendOptions &Opts, - std::unique_ptr Wrapped) { - return std::make_unique( - std::move(Wrapped), Controller); - }); - break; - } - - // Consider different header search and diagnostic options to create - // different modules. This avoids the unsound aliasing of module PCMs. - // - // TODO: Implement diagnostic bucketing to reduce the impact of strict - // context hashing. - ScanInstance.getHeaderSearchOpts().ModulesStrictContextHash = true; - ScanInstance.getHeaderSearchOpts().ModulesSerializeOnlyPreprocessor = true; - ScanInstance.getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true; - ScanInstance.getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true; - ScanInstance.getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings = - true; - ScanInstance.getHeaderSearchOpts().ModulesForceValidateUserHeaders = false; - - // Avoid some checks and module map parsing when loading PCM files. - ScanInstance.getPreprocessorOpts().ModulesCheckRelocated = false; - - std::unique_ptr Action; - - if (Service.getFormat() == ScanningOutputFormat::P1689) - Action = std::make_unique(); - else if (ModuleName) - Action = std::make_unique(*ModuleName); - else - Action = std::make_unique(); - - // Normally this would be handled by GeneratePCHAction - if (ScanInstance.getFrontendOpts().ProgramAction == frontend::GeneratePCH) - ScanInstance.getLangOpts().CompilingPCH = true; - - if (Error E = Controller.initialize(ScanInstance, OriginalInvocation)) - return reportError(std::move(E)); - - if (ScanInstance.getDiagnostics().hasErrorOccurred()) - return false; - - // ExecuteAction is responsible for calling finish. - DiagConsumerFinished = true; - - if (!ScanInstance.ExecuteAction(*Action)) - return false; - - if (MDC) - MDC->applyDiscoveredDependencies(OriginalInvocation); - - if (Error E = Controller.finalize(ScanInstance, OriginalInvocation)) - return reportError(std::move(E)); - - // Forward any CAS results to consumer. - std::string ID = OriginalInvocation.getFileSystemOpts().CASFileSystemRootID; - if (!ID.empty()) - Consumer.handleCASFileSystemRootID(std::move(ID)); - ID = OriginalInvocation.getFrontendOpts().CASIncludeTreeID; - if (!ID.empty()) - Consumer.handleIncludeTreeID(std::move(ID)); - - LastCC1Arguments = OriginalInvocation.getCC1CommandLine(); - LastCC1CacheKey = Controller.getCacheKey(OriginalInvocation); - - return true; - } - - bool hasScanned() const { return Scanned; } - bool hasDiagConsumerFinished() const { return DiagConsumerFinished; } - - /// Take the cc1 arguments corresponding to the most recent invocation used - /// with this action. Any modifications implied by the discovered dependencies - /// will have already been applied. - std::vector takeLastCC1Arguments() { - std::vector Result; - std::swap(Result, LastCC1Arguments); // Reset LastCC1Arguments to empty. - return Result; - } - - std::optional takeLastCC1CacheKey() { - std::optional Result; - std::swap(Result, LastCC1CacheKey); - return Result; - } - - IntrusiveRefCntPtr getDepScanFS() { - if (DepFS) { - assert(!DepCASFS && "CAS DepFS should not be set"); - return DepFS; - } - if (DepCASFS) { - assert(!DepFS && "DepFS should not be set"); - return DepCASFS; - } - return nullptr; - } - - DependencyScanningService &Service; - StringRef WorkingDirectory; - DependencyConsumer &Consumer; - DependencyActionController &Controller; - llvm::IntrusiveRefCntPtr DepFS; - llvm::IntrusiveRefCntPtr DepCASFS; - llvm::IntrusiveRefCntPtr CacheFS; - const CASOptions &CASOpts; - bool EmitDependencyFile = false; - bool DiagGenerationAsCompilation; - std::optional ModuleName; - std::optional ScanInstanceStorage; - std::shared_ptr MDC; - std::vector LastCC1Arguments; - std::optional LastCC1CacheKey; - bool Scanned = false; - bool DiagConsumerFinished = false; - raw_ostream *VerboseOS; -}; - -} // end anonymous namespace - DependencyScanningWorker::DependencyScanningWorker( DependencyScanningService &Service, llvm::IntrusiveRefCntPtr FS) @@ -868,32 +57,19 @@ DependencyScanningWorker::getOrCreateFileManager() const { return new FileManager(FileSystemOptions(), BaseFS); } -static std::unique_ptr -createDiagOptions(const std::vector &CommandLine) { - std::vector CLI; - for (const std::string &Arg : CommandLine) - CLI.push_back(Arg.c_str()); - auto DiagOpts = CreateAndPopulateDiagOpts(CLI); - sanitizeDiagOpts(*DiagOpts); - return DiagOpts; -} - llvm::Error DependencyScanningWorker::computeDependencies( StringRef WorkingDirectory, const std::vector &CommandLine, DependencyConsumer &Consumer, DependencyActionController &Controller, std::optional TUBuffer) { // Capture the emitted diagnostics and report them to the client // in the case of a failure. - std::string DiagnosticOutput; - llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); - auto DiagOpts = createDiagOptions(CommandLine); - TextDiagnosticPrinter DiagPrinter(DiagnosticsOS, *DiagOpts); + TextDiagnosticsPrinterWithOutput DiagPrinterWithOS(CommandLine); if (computeDependencies(WorkingDirectory, CommandLine, Consumer, Controller, - DiagPrinter, TUBuffer)) + DiagPrinterWithOS.DiagPrinter, TUBuffer)) return llvm::Error::success(); - return llvm::make_error(DiagnosticsOS.str(), - llvm::inconvertibleErrorCode()); + return llvm::make_error( + DiagPrinterWithOS.DiagnosticsOS.str(), llvm::inconvertibleErrorCode()); } llvm::Error DependencyScanningWorker::computeDependencies( @@ -902,51 +78,26 @@ llvm::Error DependencyScanningWorker::computeDependencies( StringRef ModuleName) { // Capture the emitted diagnostics and report them to the client // in the case of a failure. - std::string DiagnosticOutput; - llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); - auto DiagOpts = createDiagOptions(CommandLine); - TextDiagnosticPrinter DiagPrinter(DiagnosticsOS, *DiagOpts); + TextDiagnosticsPrinterWithOutput DiagPrinterWithOS(CommandLine); if (computeDependencies(WorkingDirectory, CommandLine, Consumer, Controller, - DiagPrinter, ModuleName)) + DiagPrinterWithOS.DiagPrinter, ModuleName)) return llvm::Error::success(); - return llvm::make_error(DiagnosticsOS.str(), - llvm::inconvertibleErrorCode()); + return llvm::make_error( + DiagPrinterWithOS.DiagnosticsOS.str(), llvm::inconvertibleErrorCode()); } static bool forEachDriverJob( ArrayRef ArgStrs, DiagnosticsEngine &Diags, IntrusiveRefCntPtr FS, llvm::function_ref Callback) { - SmallVector Argv; - Argv.reserve(ArgStrs.size()); - for (const std::string &Arg : ArgStrs) - Argv.push_back(Arg.c_str()); - - std::unique_ptr Driver = std::make_unique( - Argv[0], llvm::sys::getDefaultTargetTriple(), Diags, - "clang LLVM compiler", FS); - Driver->setTitle("clang_based_tool"); - + // Compilation holds a non-owning a reference to the Driver, hence we need to + // keep the Driver alive when we use Compilation. Arguments to commands may be + // owned by Alloc when expanded from response files. llvm::BumpPtrAllocator Alloc; - bool CLMode = driver::IsClangCL( - driver::getDriverMode(Argv[0], ArrayRef(Argv).slice(1))); - - if (llvm::Error E = - driver::expandResponseFiles(Argv, CLMode, Alloc, FS.get())) { - Diags.Report(diag::err_drv_expand_response_file) - << llvm::toString(std::move(E)); - return false; - } - - const std::unique_ptr Compilation( - Driver->BuildCompilation(llvm::ArrayRef(Argv))); + auto [Driver, Compilation] = buildCompilation(ArgStrs, Diags, FS, Alloc); if (!Compilation) return false; - - if (Compilation->containsError()) - return false; - for (const driver::Command &Job : Compilation->getJobs()) { if (!Callback(Job)) return false; @@ -955,23 +106,14 @@ static bool forEachDriverJob( } static bool createAndRunToolInvocation( - std::vector CommandLine, DependencyScanningAction &Action, + const std::vector &CommandLine, + DependencyScanningAction &Action, IntrusiveRefCntPtr FS, std::shared_ptr &PCHContainerOps, DiagnosticsEngine &Diags, DependencyConsumer &Consumer) { - - // Save executable path before providing CommandLine to ToolInvocation - std::string Executable = CommandLine[0]; - - llvm::opt::ArgStringList Argv; - for (const std::string &Str : ArrayRef(CommandLine).drop_front()) - Argv.push_back(Str.c_str()); - - auto Invocation = std::make_shared(); - if (!CompilerInvocation::CreateFromArgs(*Invocation, Argv, Diags)) { - // FIXME: Should we just go on like cc1_main does? + auto Invocation = createCompilerInvocation(CommandLine, Diags); + if (!Invocation) return false; - } if (!Action.runInvocation(std::move(Invocation), std::move(FS), PCHContainerOps, Diags.getClient())) @@ -980,7 +122,7 @@ static bool createAndRunToolInvocation( std::vector Args = Action.takeLastCC1Arguments(); std::optional CacheKey = Action.takeLastCC1CacheKey(); Consumer.handleBuildCommand( - {std::move(Executable), std::move(Args), std::move(CacheKey)}); + {CommandLine[0], std::move(Args), std::move(CacheKey)}); return true; } @@ -989,26 +131,20 @@ bool DependencyScanningWorker::scanDependencies( DependencyConsumer &Consumer, DependencyActionController &Controller, DiagnosticConsumer &DC, llvm::IntrusiveRefCntPtr FS, std::optional ModuleName) { - std::vector CCommandLine(CommandLine.size(), nullptr); - llvm::transform(CommandLine, CCommandLine.begin(), - [](const std::string &Str) { return Str.c_str(); }); - auto DiagOpts = CreateAndPopulateDiagOpts(CCommandLine); - sanitizeDiagOpts(*DiagOpts); - auto Diags = CompilerInstance::createDiagnostics(*FS, *DiagOpts, &DC, - /*ShouldOwnClient=*/false); - - DependencyScanningAction Action(Service, WorkingDirectory, Consumer, Controller, DepFS, - DepCASFS, CacheFS, - /*EmitDependencyFile=*/false, - /*DiagGenerationAsCompilation=*/false, getCASOpts(), - ModuleName); + DignosticsEngineWithDiagOpts DiagEngineWithCmdAndOpts(CommandLine, FS, DC); + DependencyScanningAction Action( + Service, WorkingDirectory, Consumer, Controller, DepFS, DepCASFS, CacheFS, + /*EmitDependencyFile=*/false, + /*DiagGenerationAsCompilation=*/false, getCASOpts(), ModuleName); bool Success = false; if (CommandLine[1] == "-cc1") { - Success = createAndRunToolInvocation(CommandLine, Action, FS, - PCHContainerOps, *Diags, Consumer); + Success = createAndRunToolInvocation( + CommandLine, Action, FS, PCHContainerOps, + *DiagEngineWithCmdAndOpts.DiagEngine, Consumer); } else { Success = forEachDriverJob( - CommandLine, *Diags, FS, [&](const driver::Command &Cmd) { + CommandLine, *DiagEngineWithCmdAndOpts.DiagEngine, FS, + [&](const driver::Command &Cmd) { if (StringRef(Cmd.getCreator().getName()) != "clang") { // Non-clang command. Just pass through to the dependency // consumer. @@ -1028,13 +164,15 @@ bool DependencyScanningWorker::scanDependencies( // system to ensure that any file system requests that // are made by the driver do not go through the // dependency scanning filesystem. - return createAndRunToolInvocation(std::move(Argv), Action, FS, - PCHContainerOps, *Diags, Consumer); + return createAndRunToolInvocation( + std::move(Argv), Action, FS, PCHContainerOps, + *DiagEngineWithCmdAndOpts.DiagEngine, Consumer); }); } if (Success && !Action.hasScanned()) - Diags->Report(diag::err_fe_expected_compiler_job) + DiagEngineWithCmdAndOpts.DiagEngine->Report( + diag::err_fe_expected_compiler_job) << llvm::join(CommandLine, " "); // Ensure finish() is called even if we never reached ExecuteAction(). @@ -1048,78 +186,25 @@ bool DependencyScanningWorker::computeDependencies( StringRef WorkingDirectory, const std::vector &CommandLine, DependencyConsumer &Consumer, DependencyActionController &Controller, DiagnosticConsumer &DC, std::optional TUBuffer) { - // Reset what might have been modified in the previous worker invocation. - BaseFS->setCurrentWorkingDirectory(WorkingDirectory); - - std::optional> ModifiedCommandLine; - llvm::IntrusiveRefCntPtr ModifiedFS; - - // If we're scanning based on a module name alone, we don't expect the client - // to provide us with an input file. However, the driver really wants to have - // one. Let's just make it up to make the driver happy. if (TUBuffer) { - auto OverlayFS = - llvm::makeIntrusiveRefCnt(BaseFS); - auto InMemoryFS = - llvm::makeIntrusiveRefCnt(); - InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory); - auto InputPath = TUBuffer->getBufferIdentifier(); - InMemoryFS->addFile( - InputPath, 0, - llvm::MemoryBuffer::getMemBufferCopy(TUBuffer->getBuffer())); - llvm::IntrusiveRefCntPtr InMemoryOverlay = - InMemoryFS; - - // If we are using a CAS but not dependency CASFS, we need to provide the - // fake input file in a CASProvidingFS for include-tree. - if (CAS && !DepCASFS) - InMemoryOverlay = - llvm::cas::createCASProvidingFileSystem(CAS, std::move(InMemoryFS)); - - OverlayFS->pushOverlay(InMemoryOverlay); - ModifiedFS = OverlayFS; - ModifiedCommandLine = CommandLine; - ModifiedCommandLine->emplace_back(InputPath); + auto [FinalFS, FinalCommandLine] = initVFSForTUBuferScanning( + BaseFS, CommandLine, WorkingDirectory, *TUBuffer, CAS, DepCASFS); + return scanDependencies(WorkingDirectory, FinalCommandLine, Consumer, + Controller, DC, FinalFS, + /*ModuleName=*/std::nullopt); + } else { + BaseFS->setCurrentWorkingDirectory(WorkingDirectory); + return scanDependencies(WorkingDirectory, CommandLine, Consumer, Controller, + DC, BaseFS, /*ModuleName=*/std::nullopt); } - - const std::vector &FinalCommandLine = - ModifiedCommandLine ? *ModifiedCommandLine : CommandLine; - auto &FinalFS = ModifiedFS ? ModifiedFS : BaseFS; - - return scanDependencies(WorkingDirectory, FinalCommandLine, Consumer, - Controller, DC, FinalFS, /*ModuleName=*/std::nullopt); } bool DependencyScanningWorker::computeDependencies( StringRef WorkingDirectory, const std::vector &CommandLine, DependencyConsumer &Consumer, DependencyActionController &Controller, DiagnosticConsumer &DC, StringRef ModuleName) { - // Reset what might have been modified in the previous worker invocation. - BaseFS->setCurrentWorkingDirectory(WorkingDirectory); - - // If we're scanning based on a module name alone, we don't expect the client - // to provide us with an input file. However, the driver really wants to have - // one. Let's just make it up to make the driver happy. - auto OverlayFS = - llvm::makeIntrusiveRefCnt(BaseFS); - auto InMemoryFS = llvm::makeIntrusiveRefCnt(); - InMemoryFS->setCurrentWorkingDirectory(WorkingDirectory); - SmallString<128> FakeInputPath; - // TODO: We should retry the creation if the path already exists. - llvm::sys::fs::createUniquePath(ModuleName + "-%%%%%%%%.input", FakeInputPath, - /*MakeAbsolute=*/false); - InMemoryFS->addFile(FakeInputPath, 0, llvm::MemoryBuffer::getMemBuffer("")); - llvm::IntrusiveRefCntPtr InMemoryOverlay = InMemoryFS; - - // If we are using a CAS but not dependency CASFS, we need to provide the - // fake input file in a CASProvidingFS for include-tree. - if (CAS && !DepCASFS) - InMemoryOverlay = - llvm::cas::createCASProvidingFileSystem(CAS, std::move(InMemoryFS)); - - OverlayFS->pushOverlay(InMemoryOverlay); - auto ModifiedCommandLine = CommandLine; - ModifiedCommandLine.emplace_back(FakeInputPath); + auto [OverlayFS, ModifiedCommandLine] = initVFSForByNameScanning( + BaseFS, CommandLine, WorkingDirectory, ModuleName, CAS, DepCASFS); return scanDependencies(WorkingDirectory, ModifiedCommandLine, Consumer, Controller, DC, OverlayFS, ModuleName); diff --git a/clang/lib/Tooling/Refactoring.cpp b/clang/lib/Tooling/Refactoring.cpp index d2b0b37fd808e..9b1af2377108a 100644 --- a/clang/lib/Tooling/Refactoring.cpp +++ b/clang/lib/Tooling/Refactoring.cpp @@ -39,9 +39,8 @@ int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) { LangOptions DefaultLangOptions; DiagnosticOptions DiagOpts; TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), DiagOpts); - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &DiagnosticPrinter, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, + &DiagnosticPrinter, false); SourceManager Sources(Diagnostics, getFiles()); Rewriter Rewrite(Sources, DefaultLangOptions); diff --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp index cafd0f9646718..9a5849d426823 100644 --- a/clang/lib/Tooling/Tooling.cpp +++ b/clang/lib/Tooling/Tooling.cpp @@ -212,8 +212,8 @@ bool runToolOnCodeWithArgs( SmallString<16> FileNameStorage; StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), VFS)); + llvm::IntrusiveRefCntPtr Files = + llvm::makeIntrusiveRefCnt(FileSystemOptions(), VFS); ArgumentsAdjuster Adjuster = getClangStripDependencyFileAdjuster(); ToolInvocation Invocation( getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileNameRef), FileNameRef), @@ -476,7 +476,8 @@ ClangTool::ClangTool(const CompilationDatabase &Compilations, OverlayFileSystem(new llvm::vfs::OverlayFileSystem(std::move(BaseFS))), InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), Files(Files ? Files - : new FileManager(FileSystemOptions(), OverlayFileSystem)) { + : llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem)) { OverlayFileSystem->pushOverlay(InMemoryFileSystem); appendArgumentsAdjuster(getClangStripOutputAdjuster()); appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); @@ -697,8 +698,9 @@ std::unique_ptr buildASTFromCodeWithArgs( llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + llvm::IntrusiveRefCntPtr Files = + llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); ToolInvocation Invocation( getSyntaxOnlyToolArgs(ToolName, Adjuster(Args, FileName), FileName), diff --git a/clang/test/ClangScanDeps/response-file.c b/clang/test/ClangScanDeps/response-file.c index c08105c127202..f905438e86af6 100644 --- a/clang/test/ClangScanDeps/response-file.c +++ b/clang/test/ClangScanDeps/response-file.c @@ -1,10 +1,12 @@ -// Check that the scanner can handle a response file input. +// Check that the scanner can handle a response file input. Uses -verbatim-args +// to ensure response files are expanded by the scanner library and not the +// argumeent adjuster in clang-scan-deps. // RUN: rm -rf %t // RUN: split-file %s %t // RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json -// RUN: clang-scan-deps -format experimental-full -compilation-database %t/cdb.json > %t/deps.json +// RUN: clang-scan-deps -verbatim-args -format experimental-full -compilation-database %t/cdb.json > %t/deps.json // RUN: cat %t/deps.json | sed 's:\\\\\?:/:g' | FileCheck -DPREFIX=%/t %s diff --git a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp index 64cb012788548..6d8f86b13fa36 100644 --- a/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp +++ b/clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp @@ -134,10 +134,9 @@ GetDiagnosticsEngine(DiagnosticOptions &DiagOpts) { TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(llvm::errs(), DiagOpts); DiagClient->setPrefix("clang-extdef-mappping"); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr DiagEngine( - new DiagnosticsEngine(DiagID, DiagOpts, DiagClient)); + auto DiagEngine = llvm::makeIntrusiveRefCnt( + DiagnosticIDs::create(), DiagOpts, DiagClient); Diags.swap(DiagEngine); // Retain this one time so it's not destroyed by ASTUnit::LoadFromASTFile diff --git a/clang/tools/clang-format/ClangFormat.cpp b/clang/tools/clang-format/ClangFormat.cpp index 24ad3cb42254d..5f6106051b1fd 100644 --- a/clang/tools/clang-format/ClangFormat.cpp +++ b/clang/tools/clang-format/ClangFormat.cpp @@ -241,8 +241,7 @@ static bool fillRanges(MemoryBuffer *Code, new llvm::vfs::InMemoryFileSystem); FileManager Files(FileSystemOptions(), InMemoryFileSystem); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs), DiagOpts); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts); SourceManager Sources(Diagnostics, Files); const auto ID = createInMemoryFile("", *Code, Sources, Files, InMemoryFileSystem.get()); @@ -517,9 +516,8 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) { DiagnosticOptions DiagOpts; ClangFormatDiagConsumer IgnoreDiagnostics; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs), DiagOpts, - &IgnoreDiagnostics, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, + &IgnoreDiagnostics, false); SourceManager Sources(Diagnostics, Files); FileID ID = createInMemoryFile(AssumedFileName, *Code, Sources, Files, InMemoryFileSystem.get()); diff --git a/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp b/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp index 98925c00260f1..8259361bf6f83 100644 --- a/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp +++ b/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp @@ -33,9 +33,8 @@ void clang_fuzzer::HandleCXX(const std::string &S, new FileManager(FileSystemOptions())); IgnoringDiagConsumer Diags; DiagnosticOptions DiagOpts; - DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts, - &Diags, false); + DiagnosticsEngine Diagnostics(DiagnosticIDs::create(), DiagOpts, &Diags, + false); std::unique_ptr Invocation( tooling::newInvocation(&Diagnostics, CC1Args, /*BinaryName=*/nullptr)); std::unique_ptr Input = @@ -49,4 +48,3 @@ void clang_fuzzer::HandleCXX(const std::string &S, action->runInvocation(std::move(Invocation), Files.get(), PCHContainerOps, &Diags); } - diff --git a/clang/tools/clang-installapi/ClangInstallAPI.cpp b/clang/tools/clang-installapi/ClangInstallAPI.cpp index 4a933c76fa372..d47ddbe1822a7 100644 --- a/clang/tools/clang-installapi/ClangInstallAPI.cpp +++ b/clang/tools/clang-installapi/ClangInstallAPI.cpp @@ -78,8 +78,8 @@ static bool run(ArrayRef Args, const char *ProgName) { ArrayRef(Args).slice(1), MissingArgIndex, MissingArgCount); ParseDiagnosticArgs(DiagOpts, ParsedArgs); - IntrusiveRefCntPtr Diag = new clang::DiagnosticsEngine( - new clang::DiagnosticIDs(), DiagOpts, + auto Diag = llvm::makeIntrusiveRefCnt( + clang::DiagnosticIDs::create(), DiagOpts, new clang::TextDiagnosticPrinter(llvm::errs(), DiagOpts)); // Create file manager for all file operations and holding in-memory generated @@ -89,8 +89,9 @@ static bool run(ArrayRef Args, const char *ProgName) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - IntrusiveRefCntPtr FM( - new FileManager(clang::FileSystemOptions(), OverlayFileSystem)); + IntrusiveRefCntPtr FM = + llvm::makeIntrusiveRefCnt(clang::FileSystemOptions(), + OverlayFileSystem); // Capture all options and diagnose any errors. Options Opts(*Diag, FM.get(), Args, ProgName); @@ -114,7 +115,7 @@ static bool run(ArrayRef Args, const char *ProgName) { // Set up compilation. std::unique_ptr CI(new CompilerInstance()); CI->setVirtualFileSystem(FM->getVirtualFileSystemPtr()); - CI->setFileManager(FM.get()); + CI->setFileManager(FM); CI->createDiagnostics(); if (!CI->hasDiagnostics()) return EXIT_FAILURE; diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp b/clang/tools/clang-scan-deps/ClangScanDeps.cpp index d2791565775ba..2b32424fe5e89 100644 --- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp +++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp @@ -121,6 +121,7 @@ static constexpr bool DoRoundTripDefault = false; #endif static bool RoundTripArgs = DoRoundTripDefault; +static bool VerbatimArgs = false; static void ParseArgs(int argc, char **argv) { ScanDepsOptTable Tbl; @@ -277,6 +278,8 @@ static void ParseArgs(int argc, char **argv) { RoundTripArgs = Args.hasArg(OPT_round_trip_args); + VerbatimArgs = Args.hasArg(OPT_verbatim_args); + if (const llvm::opt::Arg *A = Args.getLastArgNoClaim(OPT_DASH_DASH)) CommandLine.assign(A->getValues().begin(), A->getValues().end()); } @@ -1167,14 +1170,16 @@ int clang_scan_deps_main(int argc, char **argv, const llvm::ToolContext &) { llvm::cl::PrintOptionValues(); - // Expand response files in advance, so that we can "see" all the arguments - // when adjusting below. - Compilations = expandResponseFiles(std::move(Compilations), - llvm::vfs::getRealFileSystem()); + if (!VerbatimArgs) { + // Expand response files in advance, so that we can "see" all the arguments + // when adjusting below. + Compilations = expandResponseFiles(std::move(Compilations), + llvm::vfs::getRealFileSystem()); - Compilations = inferTargetAndDriverMode(std::move(Compilations)); + Compilations = inferTargetAndDriverMode(std::move(Compilations)); - Compilations = inferToolLocation(std::move(Compilations)); + Compilations = inferToolLocation(std::move(Compilations)); + } // The command options are rewritten to run Clang in preprocessor only mode. auto AdjustingCompilations = @@ -1182,7 +1187,7 @@ int clang_scan_deps_main(int argc, char **argv, const llvm::ToolContext &) { std::move(Compilations)); ResourceDirectoryCache ResourceDirCache; - AdjustingCompilations->appendArgumentsAdjuster( + auto ArgsAdjuster = [&ResourceDirCache](const tooling::CommandLineArguments &Args, StringRef FileName) { if (EmitCASCompDB) @@ -1255,7 +1260,10 @@ int clang_scan_deps_main(int argc, char **argv, const llvm::ToolContext &) { AdjustedArgs.push_back("-fdepscan-prefix-map=" + std::string(Map)); } return AdjustedArgs; - }); + }; + + if (!VerbatimArgs) + AdjustingCompilations->appendArgumentsAdjuster(ArgsAdjuster); SharedStream Errs(llvm::errs()); diff --git a/clang/tools/clang-scan-deps/Opts.td b/clang/tools/clang-scan-deps/Opts.td index 4f12a697fc3b9..efcf950780f73 100644 --- a/clang/tools/clang-scan-deps/Opts.td +++ b/clang/tools/clang-scan-deps/Opts.td @@ -59,4 +59,6 @@ def verbose : F<"v", "Use verbose output">; def round_trip_args : F<"round-trip-args", "verify that command-line arguments are canonical by parsing and re-serializing">; +def verbatim_args : F<"verbatim-args", "Pass commands to the scanner verbatim without adjustments">; + def DASH_DASH : Option<["--"], "", KIND_REMAINING_ARGS>; diff --git a/clang/tools/diagtool/ShowEnabledWarnings.cpp b/clang/tools/diagtool/ShowEnabledWarnings.cpp index 0d1455d270436..bea0288c09358 100644 --- a/clang/tools/diagtool/ShowEnabledWarnings.cpp +++ b/clang/tools/diagtool/ShowEnabledWarnings.cpp @@ -55,7 +55,6 @@ static char getCharForLevel(DiagnosticsEngine::Level Level) { static IntrusiveRefCntPtr createDiagnostics(unsigned int argc, char **argv) { - IntrusiveRefCntPtr DiagIDs(new DiagnosticIDs()); DiagnosticOptions DiagOpts; // Buffer diagnostics from argument parsing so that we can output them using a @@ -67,7 +66,8 @@ createDiagnostics(unsigned int argc, char **argv) { Args.push_back("diagtool"); Args.append(argv, argv + argc); CreateInvocationOptions CIOpts; - CIOpts.Diags = new DiagnosticsEngine(DiagIDs, DiagOpts, DiagsBuffer); + CIOpts.Diags = llvm::makeIntrusiveRefCnt( + DiagnosticIDs::create(), DiagOpts, DiagsBuffer); std::unique_ptr Invocation = createInvocation(Args, CIOpts); if (!Invocation) diff --git a/clang/tools/diagtool/TreeView.cpp b/clang/tools/diagtool/TreeView.cpp index 7e47c748af959..13b80150e6041 100644 --- a/clang/tools/diagtool/TreeView.cpp +++ b/clang/tools/diagtool/TreeView.cpp @@ -32,7 +32,7 @@ class TreePrinter { static bool isIgnored(unsigned DiagID) { // FIXME: This feels like a hack. static DiagnosticOptions DiagOpts; - static clang::DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts); + static clang::DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts); return Diags.isIgnored(DiagID, SourceLocation()); } diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp index 49bb7e5e63d19..df19f1f76b763 100644 --- a/clang/tools/driver/cc1_main.cpp +++ b/clang/tools/driver/cc1_main.cpp @@ -221,7 +221,7 @@ int cc1_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { ensureSufficientStack(); CompileJobCache JobCache; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); // Register the support for object-file-wrapped Clang modules. auto PCHOps = std::make_shared(); diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp index 207f9f11c4de9..3ea9144a8a779 100644 --- a/clang/tools/driver/cc1as_main.cpp +++ b/clang/tools/driver/cc1as_main.cpp @@ -685,8 +685,7 @@ int cc1as_main(ArrayRef Argv, const char *Argv0, void *MainAddr) { TextDiagnosticPrinter *DiagClient = new TextDiagnosticPrinter(errs(), DiagOpts); DiagClient->setPrefix("clang -cc1as"); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - DiagnosticsEngine Diags(DiagID, DiagOpts, DiagClient); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagClient); auto VFS = vfs::getRealFileSystem(); diff --git a/clang/tools/driver/cc1gen_reproducer_main.cpp b/clang/tools/driver/cc1gen_reproducer_main.cpp index 47e1a1ed28f81..50e348d8f9a50 100644 --- a/clang/tools/driver/cc1gen_reproducer_main.cpp +++ b/clang/tools/driver/cc1gen_reproducer_main.cpp @@ -121,8 +121,8 @@ generateReproducerForInvocationArguments(ArrayRef Argv, DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - DiagnosticsEngine Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, + new IgnoringDiagConsumer()); auto VFS = llvm::vfs::getRealFileSystem(); ProcessWarningOptions(Diags, DiagOpts, *VFS, /*ReportDiags=*/false); Driver TheDriver(ToolContext.Path, llvm::sys::getDefaultTargetTriple(), Diags, diff --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp index 987fec0bdfb29..20db5b5022378 100644 --- a/clang/tools/driver/driver.cpp +++ b/clang/tools/driver/driver.cpp @@ -374,9 +374,7 @@ int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { new TextDiagnosticPrinter(llvm::errs(), *DiagOpts); FixupDiagPrefixExeName(DiagClient, ProgName); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - - DiagnosticsEngine Diags(DiagID, *DiagOpts, DiagClient); + DiagnosticsEngine Diags(DiagnosticIDs::create(), *DiagOpts, DiagClient); if (!DiagOpts->DiagnosticSerializationFile.empty()) { auto SerializedConsumer = diff --git a/clang/tools/libclang/CIndexCodeCompletion.cpp b/clang/tools/libclang/CIndexCodeCompletion.cpp index f20385f047ec7..b2d4c0af6151b 100644 --- a/clang/tools/libclang/CIndexCodeCompletion.cpp +++ b/clang/tools/libclang/CIndexCodeCompletion.cpp @@ -357,10 +357,11 @@ static std::atomic CodeCompletionResultObjects; AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults( IntrusiveRefCntPtr FileMgr) : CXCodeCompleteResults(), - Diag(new DiagnosticsEngine( - IntrusiveRefCntPtr(new DiagnosticIDs), DiagOpts)), + Diag(llvm::makeIntrusiveRefCnt(DiagnosticIDs::create(), + DiagOpts)), FileMgr(std::move(FileMgr)), - SourceMgr(new SourceManager(*Diag, *this->FileMgr)), + SourceMgr( + llvm::makeIntrusiveRefCnt(*Diag, *this->FileMgr)), CodeCompletionAllocator( std::make_shared()), Contexts(CXCompletionContext_Unknown), @@ -736,8 +737,8 @@ clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename, } // Parse the resulting source file to find code-completion results. - AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults( - &AST->getFileManager()); + AllocatedCXCodeCompleteResults *Results = + new AllocatedCXCodeCompleteResults(AST->getFileManagerPtr()); Results->Results = nullptr; Results->NumResults = 0; @@ -764,8 +765,8 @@ clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename, RemappedFiles, (options & CXCodeComplete_IncludeMacros), (options & CXCodeComplete_IncludeCodePatterns), IncludeBriefComments, Capture, - CXXIdx->getPCHContainerOperations(), *Results->Diag, - Results->LangOpts, *Results->SourceMgr, *Results->FileMgr, + CXXIdx->getPCHContainerOperations(), Results->Diag, + Results->LangOpts, Results->SourceMgr, Results->FileMgr, Results->Diagnostics, Results->TemporaryBuffers, /*SyntaxOnlyAction=*/nullptr); diff --git a/clang/tools/libclang/CXIndexDataConsumer.cpp b/clang/tools/libclang/CXIndexDataConsumer.cpp index 964d3b187adbf..bd95c5cdaccf9 100644 --- a/clang/tools/libclang/CXIndexDataConsumer.cpp +++ b/clang/tools/libclang/CXIndexDataConsumer.cpp @@ -415,9 +415,9 @@ const char *ScratchAlloc::copyCStr(StringRef Str) { return buf; } -void CXIndexDataConsumer::setASTContext(ASTContext &ctx) { - Ctx = &ctx; - cxtu::getASTUnit(CXTU)->setASTContext(&ctx); +void CXIndexDataConsumer::setASTContext(IntrusiveRefCntPtr ctx) { + Ctx = ctx.get(); + cxtu::getASTUnit(CXTU)->setASTContext(std::move(ctx)); } void CXIndexDataConsumer::setPreprocessor(std::shared_ptr PP) { diff --git a/clang/tools/libclang/CXIndexDataConsumer.h b/clang/tools/libclang/CXIndexDataConsumer.h index 54a3add3a9c8d..b207db7cde6d7 100644 --- a/clang/tools/libclang/CXIndexDataConsumer.h +++ b/clang/tools/libclang/CXIndexDataConsumer.h @@ -339,7 +339,7 @@ class CXIndexDataConsumer : public index::IndexDataConsumer { ASTContext &getASTContext() const { return *Ctx; } CXTranslationUnit getCXTU() const { return CXTU; } - void setASTContext(ASTContext &ctx); + void setASTContext(llvm::IntrusiveRefCntPtr ctx); void setPreprocessor(std::shared_ptr PP) override; bool shouldSuppressRefs() const { diff --git a/clang/tools/libclang/Indexing.cpp b/clang/tools/libclang/Indexing.cpp index 32a7147af3382..c142f142d5071 100644 --- a/clang/tools/libclang/Indexing.cpp +++ b/clang/tools/libclang/Indexing.cpp @@ -304,7 +304,8 @@ class IndexingConsumer : public ASTConsumer { : DataConsumer(dataConsumer) {} void Initialize(ASTContext &Context) override { - DataConsumer.setASTContext(Context); + // TODO: accept Context as IntrusiveRefCntPtr? + DataConsumer.setASTContext(&Context); DataConsumer.startedTranslationUnit(); } @@ -355,7 +356,7 @@ class IndexingFrontendAction : public ASTFrontendAction { DataConsumer->importedPCH(*File); } - DataConsumer->setASTContext(CI.getASTContext()); + DataConsumer->setASTContext(CI.getASTContextPtr()); Preprocessor &PP = CI.getPreprocessor(); PP.addPPCallbacks(std::make_unique(PP, *DataConsumer)); DataConsumer->setPreprocessor(CI.getPreprocessorPtr()); @@ -706,7 +707,7 @@ static CXErrorCode clang_indexTranslationUnit_Impl( else DataConsumer.enteredMainFile(std::nullopt); - DataConsumer.setASTContext(Unit->getASTContext()); + DataConsumer.setASTContext(Unit->getASTContextPtr()); DataConsumer.startedTranslationUnit(); indexPreprocessingRecord(*Unit, DataConsumer); diff --git a/clang/unittests/AST/ASTImporterTest.cpp b/clang/unittests/AST/ASTImporterTest.cpp index c0fb642d817a0..ac38300142e34 100644 --- a/clang/unittests/AST/ASTImporterTest.cpp +++ b/clang/unittests/AST/ASTImporterTest.cpp @@ -6976,7 +6976,8 @@ TEST_P(LLDBLookupTest, ImporterShouldFindInTransparentContext) { // Set up DeclContextBits.HasLazyExternalLexicalLookups to true. ToTU->setMustBuildLookupTable(); struct TestExternalASTSource : ExternalASTSource {}; - ToTU->getASTContext().setExternalSource(new TestExternalASTSource()); + ToTU->getASTContext().setExternalSource( + llvm::makeIntrusiveRefCnt()); Decl *FromTU = getTuDecl( R"( @@ -8154,8 +8155,8 @@ TEST_P(ImportWithExternalSource, CompleteRecordBeforeImporting) { // Create and add the test ExternalASTSource. std::vector CompletedTags; - IntrusiveRefCntPtr source = - new SourceWithCompletedTagList(CompletedTags); + auto source = + llvm::makeIntrusiveRefCnt(CompletedTags); clang::ASTContext &Context = FromTU->getASTContext(); Context.setExternalSource(std::move(source)); diff --git a/clang/unittests/AST/ASTVectorTest.cpp b/clang/unittests/AST/ASTVectorTest.cpp index 66003b49eccb2..03da54967f1ed 100644 --- a/clang/unittests/AST/ASTVectorTest.cpp +++ b/clang/unittests/AST/ASTVectorTest.cpp @@ -26,14 +26,13 @@ namespace { class ASTVectorTest : public ::testing::Test { protected: ASTVectorTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), Idents(LangOpts, nullptr), Ctxt(LangOpts, SourceMgr, Idents, Sels, Builtins, TU_Complete) {} FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/AST/CommentLexer.cpp b/clang/unittests/AST/CommentLexer.cpp index dc10dae7a2f8f..99f469173964e 100644 --- a/clang/unittests/AST/CommentLexer.cpp +++ b/clang/unittests/AST/CommentLexer.cpp @@ -27,13 +27,12 @@ namespace { class CommentLexerTest : public ::testing::Test { protected: CommentLexerTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), Traits(Allocator, CommentOptions()) {} FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; @@ -2006,4 +2005,3 @@ TEST_F(CommentLexerTest, MultipleComments) { } // end namespace comments } // end namespace clang - diff --git a/clang/unittests/AST/CommentParser.cpp b/clang/unittests/AST/CommentParser.cpp index 67fabe5181798..3bd2bdb692131 100644 --- a/clang/unittests/AST/CommentParser.cpp +++ b/clang/unittests/AST/CommentParser.cpp @@ -33,13 +33,12 @@ const bool MY_DEBUG = true; class CommentParserTest : public ::testing::Test { protected: CommentParserTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), Traits(Allocator, CommentOptions()) {} FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/AST/CommentTextTest.cpp b/clang/unittests/AST/CommentTextTest.cpp index 84ec51a308360..675173c162586 100644 --- a/clang/unittests/AST/CommentTextTest.cpp +++ b/clang/unittests/AST/CommentTextTest.cpp @@ -44,7 +44,7 @@ class CommentTextTest : public ::testing::Test { // shouldn't matter. RawComment Comment(SourceMgr, CommentRange, EmptyOpts, /*Merged=*/true); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts); return Comment.getFormattedText(SourceMgr, Diags); } }; diff --git a/clang/unittests/AST/ExternalASTSourceTest.cpp b/clang/unittests/AST/ExternalASTSourceTest.cpp index 98d708707bc99..15483ad250976 100644 --- a/clang/unittests/AST/ExternalASTSourceTest.cpp +++ b/clang/unittests/AST/ExternalASTSourceTest.cpp @@ -26,7 +26,8 @@ using namespace llvm; class TestFrontendAction : public ASTFrontendAction { public: - TestFrontendAction(ExternalASTSource *Source) : Source(Source) {} + TestFrontendAction(IntrusiveRefCntPtr Source) + : Source(std::move(Source)) {} private: void ExecuteAction() override { @@ -44,7 +45,8 @@ class TestFrontendAction : public ASTFrontendAction { IntrusiveRefCntPtr Source; }; -bool testExternalASTSource(ExternalASTSource *Source, StringRef FileContents) { +bool testExternalASTSource(llvm::IntrusiveRefCntPtr Source, + StringRef FileContents) { auto Invocation = std::make_shared(); Invocation->getPreprocessorOpts().addRemappedFile( @@ -81,6 +83,7 @@ TEST(ExternalASTSourceTest, FailedLookupOccursOnce) { }; unsigned Calls = 0; - ASSERT_TRUE(testExternalASTSource(new TestSource(Calls), "int j, k = j;")); + ASSERT_TRUE(testExternalASTSource( + llvm::makeIntrusiveRefCnt(Calls), "int j, k = j;")); EXPECT_EQ(1u, Calls); } diff --git a/clang/unittests/Analysis/MacroExpansionContextTest.cpp b/clang/unittests/Analysis/MacroExpansionContextTest.cpp index 9874ea687f3ed..6687edc4ad986 100644 --- a/clang/unittests/Analysis/MacroExpansionContextTest.cpp +++ b/clang/unittests/Analysis/MacroExpansionContextTest.cpp @@ -35,8 +35,7 @@ class MacroExpansionContextTest : public ::testing::Test { MacroExpansionContextTest() : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), FileMgr(FileSystemOptions(), InMemoryFileSystem), - DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions()) { TargetOpts->Triple = "x86_64-pc-linux-unknown"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -45,7 +44,6 @@ class MacroExpansionContextTest : public ::testing::Test { IntrusiveRefCntPtr InMemoryFileSystem; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Analysis/UnsafeBufferUsageTest.cpp b/clang/unittests/Analysis/UnsafeBufferUsageTest.cpp index 9da2c58970b84..f795918c743ee 100644 --- a/clang/unittests/Analysis/UnsafeBufferUsageTest.cpp +++ b/clang/unittests/Analysis/UnsafeBufferUsageTest.cpp @@ -12,13 +12,12 @@ namespace { class UnsafeBufferUsageTest : public ::testing::Test { protected: UnsafeBufferUsageTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr) {} FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; @@ -58,4 +57,4 @@ TEST_F(UnsafeBufferUsageTest, FixItHintsConflict) { Fixes = {H1, H2, H3, MkDummyHint(2, 23) /* overlaps H1, H2, and H3 */}; EXPECT_TRUE(internal::anyConflict(Fixes, SourceMgr)); -} \ No newline at end of file +} diff --git a/clang/unittests/Basic/DiagnosticTest.cpp b/clang/unittests/Basic/DiagnosticTest.cpp index b0a034e9af1cd..4b3af00c3b0ce 100644 --- a/clang/unittests/Basic/DiagnosticTest.cpp +++ b/clang/unittests/Basic/DiagnosticTest.cpp @@ -47,7 +47,7 @@ using testing::IsEmpty; // Check that DiagnosticErrorTrap works with SuppressAllDiagnostics. TEST(DiagnosticTest, suppressAndTrap) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()); Diags.setSuppressAllDiagnostics(true); @@ -78,7 +78,7 @@ TEST(DiagnosticTest, suppressAndTrap) { TEST(DiagnosticTest, fatalsAsError) { for (unsigned FatalsAsError = 0; FatalsAsError != 2; ++FatalsAsError) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()); Diags.setFatalsAsError(FatalsAsError); @@ -102,7 +102,7 @@ TEST(DiagnosticTest, fatalsAsError) { TEST(DiagnosticTest, tooManyErrorsIsAlwaysFatal) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()); Diags.setFatalsAsError(true); @@ -119,7 +119,7 @@ TEST(DiagnosticTest, tooManyErrorsIsAlwaysFatal) { // Check that soft RESET works as intended TEST(DiagnosticTest, softReset) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()); unsigned numWarnings = 0U, numErrors = 0U; @@ -143,7 +143,7 @@ TEST(DiagnosticTest, softReset) { TEST(DiagnosticTest, diagnosticError) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()); PartialDiagnostic::DiagStorageAllocator Alloc; llvm::Expected> Value = DiagnosticError::create( @@ -166,7 +166,7 @@ TEST(DiagnosticTest, diagnosticError) { TEST(DiagnosticTest, storedDiagEmptyWarning) { DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs(), DiagOpts); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts); class CaptureDiagnosticConsumer : public DiagnosticConsumer { public: @@ -197,7 +197,7 @@ class SuppressionMappingTest : public testing::Test { llvm::IntrusiveRefCntPtr FS = llvm::makeIntrusiveRefCnt(); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags{new DiagnosticIDs(), DiagOpts}; + DiagnosticsEngine Diags{DiagnosticIDs::create(), DiagOpts}; llvm::ArrayRef diags() { return CaptureConsumer.StoredDiags; diff --git a/clang/unittests/Basic/SarifTest.cpp b/clang/unittests/Basic/SarifTest.cpp index ad9f8ecc208a4..da2c775ee0304 100644 --- a/clang/unittests/Basic/SarifTest.cpp +++ b/clang/unittests/Basic/SarifTest.cpp @@ -43,13 +43,11 @@ class SarifDocumentWriterTest : public ::testing::Test { SarifDocumentWriterTest() : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), FileMgr(FileSystemOptions(), InMemoryFileSystem), - DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr) {} IntrusiveRefCntPtr InMemoryFileSystem; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Basic/SourceManagerTest.cpp b/clang/unittests/Basic/SourceManagerTest.cpp index cbe047b5e599a..04b23dd13ba3e 100644 --- a/clang/unittests/Basic/SourceManagerTest.cpp +++ b/clang/unittests/Basic/SourceManagerTest.cpp @@ -40,8 +40,8 @@ namespace { class SourceManagerTest : public ::testing::Test { protected: SourceManagerTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -49,7 +49,6 @@ class SourceManagerTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Driver/DXCModeTest.cpp b/clang/unittests/Driver/DXCModeTest.cpp index f6845939d04b4..8eb1929bd7526 100644 --- a/clang/unittests/Driver/DXCModeTest.cpp +++ b/clang/unittests/Driver/DXCModeTest.cpp @@ -55,8 +55,6 @@ static void validateTargetProfile( } TEST(DxcModeTest, TargetProfileValidation) { - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); @@ -65,7 +63,7 @@ TEST(DxcModeTest, TargetProfileValidation) { auto *DiagConsumer = new SimpleDiagnosticConsumer; DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagConsumer); validateTargetProfile("-Tvs_6_0", "dxilv1.0--shadermodel6.0-vertex", InMemoryFileSystem, Diags); @@ -105,8 +103,6 @@ TEST(DxcModeTest, TargetProfileValidation) { } TEST(DxcModeTest, ValidatorVersionValidation) { - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); - IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); @@ -115,7 +111,7 @@ TEST(DxcModeTest, ValidatorVersionValidation) { auto *DiagConsumer = new SimpleDiagnosticConsumer; DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer); + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagConsumer); Driver TheDriver("/bin/clang", "", Diags, "", InMemoryFileSystem); std::unique_ptr C(TheDriver.BuildCompilation( {"clang", "--driver-mode=dxc", "-Tlib_6_7", "foo.hlsl"})); diff --git a/clang/unittests/Driver/SanitizerArgsTest.cpp b/clang/unittests/Driver/SanitizerArgsTest.cpp index b8bfc6806da6d..b3da389248a72 100644 --- a/clang/unittests/Driver/SanitizerArgsTest.cpp +++ b/clang/unittests/Driver/SanitizerArgsTest.cpp @@ -53,7 +53,7 @@ class SanitizerArgsTest : public ::testing::Test { assert(!DriverInstance && "Running twice is not allowed"); DiagnosticOptions DiagOpts; - DiagnosticsEngine Diags(new DiagnosticIDs, DiagOpts, + DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, new TextDiagnosticPrinter(llvm::errs(), DiagOpts)); DriverInstance.emplace(ClangBinary, "x86_64-unknown-linux-gnu", Diags, "clang LLVM compiler", prepareFS(ExtraFiles)); diff --git a/clang/unittests/Driver/SimpleDiagnosticConsumer.h b/clang/unittests/Driver/SimpleDiagnosticConsumer.h index c3772baade566..ba31a839a827e 100644 --- a/clang/unittests/Driver/SimpleDiagnosticConsumer.h +++ b/clang/unittests/Driver/SimpleDiagnosticConsumer.h @@ -42,13 +42,12 @@ struct SimpleDiagnosticConsumer : public clang::DiagnosticConsumer { // for testing situations where it will only ever be used for emitting // diagnostics, such as being passed to `MultilibSet::select`. inline clang::driver::Driver diagnostic_test_driver() { - llvm::IntrusiveRefCntPtr DiagID( - new clang::DiagnosticIDs()); llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); auto *DiagConsumer = new SimpleDiagnosticConsumer; clang::DiagnosticOptions DiagOpts; - clang::DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer); + clang::DiagnosticsEngine Diags(clang::DiagnosticIDs::create(), DiagOpts, + DiagConsumer); return clang::driver::Driver("/bin/clang", "", Diags, "", InMemoryFileSystem); } diff --git a/clang/unittests/Driver/ToolChainTest.cpp b/clang/unittests/Driver/ToolChainTest.cpp index 56a961370c0be..53f1cc88adf28 100644 --- a/clang/unittests/Driver/ToolChainTest.cpp +++ b/clang/unittests/Driver/ToolChainTest.cpp @@ -40,7 +40,7 @@ namespace { TEST(ToolChainTest, VFSGCCInstallation) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); @@ -137,7 +137,7 @@ TEST(ToolChainTest, VFSGCCInstallation) { TEST(ToolChainTest, VFSGCCInstallationRelativeDir) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr InMemoryFileSystem( @@ -176,7 +176,7 @@ TEST(ToolChainTest, VFSGCCInstallationRelativeDir) { TEST(ToolChainTest, VFSSolarisMultiGCCInstallation) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); @@ -340,7 +340,7 @@ MATCHER_P(jobHasArgs, Substr, "") { TEST(ToolChainTest, VFSGnuLibcxxPathNoSysroot) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); @@ -371,7 +371,7 @@ TEST(ToolChainTest, VFSGnuLibcxxPathNoSysroot) { TEST(ToolChainTest, DefaultDriverMode) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr InMemoryFileSystem( @@ -402,7 +402,7 @@ TEST(ToolChainTest, DefaultDriverMode) { EXPECT_TRUE(CLDriver.IsCLMode()); } TEST(ToolChainTest, InvalidArgument) { - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); @@ -517,7 +517,7 @@ TEST(ToolChainTest, GetTargetAndMode) { TEST(ToolChainTest, CommandOutput) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr InMemoryFileSystem( @@ -545,7 +545,7 @@ TEST(ToolChainTest, CommandOutput) { TEST(ToolChainTest, PostCallback) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr InMemoryFileSystem( @@ -599,7 +599,7 @@ TEST(ToolChainTest, UEFICallingConventionTest) { TEST(ToolChainTest, UEFIDefaultDebugFormatTest) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr InMemoryFileSystem( @@ -641,7 +641,7 @@ struct SimpleDiagnosticConsumer : public DiagnosticConsumer { TEST(ToolChainTest, ConfigFileSearch) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr FS( @@ -718,7 +718,7 @@ struct FileSystemWithError : public llvm::vfs::FileSystem { TEST(ToolChainTest, ConfigFileError) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); std::unique_ptr DiagConsumer( new SimpleDiagnosticConsumer()); DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer.get(), false); @@ -739,7 +739,7 @@ TEST(ToolChainTest, ConfigFileError) { TEST(ToolChainTest, BadConfigFile) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); std::unique_ptr DiagConsumer( new SimpleDiagnosticConsumer()); DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer.get(), false); @@ -813,7 +813,7 @@ TEST(ToolChainTest, BadConfigFile) { TEST(ToolChainTest, ConfigInexistentInclude) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); std::unique_ptr DiagConsumer( new SimpleDiagnosticConsumer()); DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer.get(), false); @@ -854,7 +854,7 @@ TEST(ToolChainTest, ConfigInexistentInclude) { TEST(ToolChainTest, ConfigRecursiveInclude) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); std::unique_ptr DiagConsumer( new SimpleDiagnosticConsumer()); DiagnosticsEngine Diags(DiagID, DiagOpts, DiagConsumer.get(), false); @@ -900,7 +900,7 @@ TEST(ToolChainTest, ConfigRecursiveInclude) { TEST(ToolChainTest, NestedConfigFile) { DiagnosticOptions DiagOpts; - IntrusiveRefCntPtr DiagID(new DiagnosticIDs()); + IntrusiveRefCntPtr DiagID = DiagnosticIDs::create(); struct TestDiagnosticConsumer : public DiagnosticConsumer {}; DiagnosticsEngine Diags(DiagID, DiagOpts, new TestDiagnosticConsumer); IntrusiveRefCntPtr FS( diff --git a/clang/unittests/Frontend/ASTUnitTest.cpp b/clang/unittests/Frontend/ASTUnitTest.cpp index 268dab2b169a3..437b233c40be8 100644 --- a/clang/unittests/Frontend/ASTUnitTest.cpp +++ b/clang/unittests/Frontend/ASTUnitTest.cpp @@ -55,7 +55,8 @@ class ASTUnitTest : public ::testing::Test { if (!CInvok) return nullptr; - FileManager *FileMgr = new FileManager(FileSystemOptions(), VFS); + auto FileMgr = + llvm::makeIntrusiveRefCnt(FileSystemOptions(), VFS); PCHContainerOps = std::make_shared(); return ASTUnit::LoadFromCompilerInvocation( @@ -145,7 +146,8 @@ TEST_F(ASTUnitTest, ModuleTextualHeader) { CInvok = createInvocation(Args, std::move(CIOpts)); ASSERT_TRUE(CInvok); - FileManager *FileMgr = new FileManager(FileSystemOptions(), InMemoryFs); + auto FileMgr = + llvm::makeIntrusiveRefCnt(FileSystemOptions(), InMemoryFs); PCHContainerOps = std::make_shared(); auto AU = ASTUnit::LoadFromCompilerInvocation( diff --git a/clang/unittests/Frontend/CompilerInstanceTest.cpp b/clang/unittests/Frontend/CompilerInstanceTest.cpp index e0f228668b884..cd3fefa1ea994 100644 --- a/clang/unittests/Frontend/CompilerInstanceTest.cpp +++ b/clang/unittests/Frontend/CompilerInstanceTest.cpp @@ -71,7 +71,7 @@ TEST(CompilerInstance, DefaultVFSOverlayFromInvocation) { // Create a minimal CompilerInstance which should use the VFS we specified // in the CompilerInvocation (as we don't explicitly set our own). CompilerInstance Instance(std::move(CInvok)); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.createVirtualFileSystem(); Instance.createFileManager(); @@ -137,7 +137,7 @@ TEST(CompilerInstance, MultipleInputsCleansFileIDs) { CompilerInstance Instance(std::move(CInvok)); Instance.setVirtualFileSystem(VFS); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.createFileManager(); // Run once for `a.cc` and then for `a.h`. This makes sure we get the same diff --git a/clang/unittests/Frontend/FrontendActionTest.cpp b/clang/unittests/Frontend/FrontendActionTest.cpp index 125940b44170c..c4003182c4b1d 100644 --- a/clang/unittests/Frontend/FrontendActionTest.cpp +++ b/clang/unittests/Frontend/FrontendActionTest.cpp @@ -248,7 +248,8 @@ TEST(ASTFrontendAction, ExternalSemaSource) { auto *TDC = new TypoDiagnosticConsumer; Compiler.setVirtualFileSystem(llvm::vfs::getRealFileSystem()); Compiler.createDiagnostics(TDC, /*ShouldOwnClient=*/true); - Compiler.setExternalSemaSource(new TypoExternalSemaSource(Compiler)); + Compiler.setExternalSemaSource( + llvm::makeIntrusiveRefCnt(Compiler)); SyntaxOnlyAction TestAction; ASSERT_TRUE(Compiler.ExecuteAction(TestAction)); diff --git a/clang/unittests/Frontend/PCHPreambleTest.cpp b/clang/unittests/Frontend/PCHPreambleTest.cpp index faad408193f62..06e585357dda5 100644 --- a/clang/unittests/Frontend/PCHPreambleTest.cpp +++ b/clang/unittests/Frontend/PCHPreambleTest.cpp @@ -100,7 +100,7 @@ class PCHPreambleTest : public ::testing::Test { CompilerInstance::createDiagnostics(*VFS, *DiagOpts, new DiagnosticConsumer)); - FileManager *FileMgr = new FileManager(FSOpts, VFS); + auto FileMgr = llvm::makeIntrusiveRefCnt(FSOpts, VFS); std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation( CI, PCHContainerOpts, DiagOpts, Diags, FileMgr, false, diff --git a/clang/unittests/Frontend/ReparseWorkingDirTest.cpp b/clang/unittests/Frontend/ReparseWorkingDirTest.cpp index 1b8051f80e9b8..c67891d95940b 100644 --- a/clang/unittests/Frontend/ReparseWorkingDirTest.cpp +++ b/clang/unittests/Frontend/ReparseWorkingDirTest.cpp @@ -62,7 +62,8 @@ class ReparseWorkingDirTest : public ::testing::Test { CompilerInstance::createDiagnostics(*VFS, *DiagOpts, new DiagnosticConsumer)); - FileManager *FileMgr = new FileManager(CI->getFileSystemOpts(), VFS); + auto FileMgr = + llvm::makeIntrusiveRefCnt(CI->getFileSystemOpts(), VFS); std::unique_ptr AST = ASTUnit::LoadFromCompilerInvocation( CI, PCHContainerOpts, DiagOpts, Diags, FileMgr, false, diff --git a/clang/unittests/Frontend/SearchPathTest.cpp b/clang/unittests/Frontend/SearchPathTest.cpp index c74a5c75fada5..afea2ddf411b0 100644 --- a/clang/unittests/Frontend/SearchPathTest.cpp +++ b/clang/unittests/Frontend/SearchPathTest.cpp @@ -40,7 +40,7 @@ namespace { class SearchPathTest : public ::testing::Test { protected: SearchPathTest() - : Diags(new DiagnosticIDs(), DiagOpts, new IgnoringDiagConsumer()), + : Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), VFS(new llvm::vfs::InMemoryFileSystem), FileMgr(FileSystemOptions(), VFS), SourceMgr(Diags, FileMgr), Invocation(std::make_unique()) {} diff --git a/clang/unittests/Frontend/TextDiagnosticTest.cpp b/clang/unittests/Frontend/TextDiagnosticTest.cpp index 8fd8187134b63..622dbc5883067 100644 --- a/clang/unittests/Frontend/TextDiagnosticTest.cpp +++ b/clang/unittests/Frontend/TextDiagnosticTest.cpp @@ -36,9 +36,8 @@ TEST(TextDiagnostic, ShowLine) { // Create dummy FileManager and SourceManager. FileSystemOptions FSOpts; FileManager FileMgr(FSOpts); - IntrusiveRefCntPtr DiagID(new DiagnosticIDs); DiagnosticOptions DiagEngineOpts; - DiagnosticsEngine DiagEngine(DiagID, DiagEngineOpts, + DiagnosticsEngine DiagEngine(DiagnosticIDs::create(), DiagEngineOpts, new IgnoringDiagConsumer()); SourceManager SrcMgr(DiagEngine, FileMgr); diff --git a/clang/unittests/Lex/HeaderSearchTest.cpp b/clang/unittests/Lex/HeaderSearchTest.cpp index 9903c1246d33d..6d7c588efa0ed 100644 --- a/clang/unittests/Lex/HeaderSearchTest.cpp +++ b/clang/unittests/Lex/HeaderSearchTest.cpp @@ -29,8 +29,7 @@ class HeaderSearchTest : public ::testing::Test { protected: HeaderSearchTest() : VFS(new llvm::vfs::InMemoryFileSystem), FileMgr(FileMgrOpts, VFS), - DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions), Search(HSOpts, SourceMgr, Diags, LangOpts, Target.get()) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; @@ -80,7 +79,6 @@ class HeaderSearchTest : public ::testing::Test { IntrusiveRefCntPtr VFS; FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Lex/LexerTest.cpp b/clang/unittests/Lex/LexerTest.cpp index bb6404c434485..c51cd0d2bfdaa 100644 --- a/clang/unittests/Lex/LexerTest.cpp +++ b/clang/unittests/Lex/LexerTest.cpp @@ -41,8 +41,8 @@ using testing::ElementsAre; class LexerTest : public ::testing::Test { protected: LexerTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -102,7 +102,6 @@ class LexerTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Lex/ModuleDeclStateTest.cpp b/clang/unittests/Lex/ModuleDeclStateTest.cpp index 0c03cfd6d0f89..ac2ddfaf52cd0 100644 --- a/clang/unittests/Lex/ModuleDeclStateTest.cpp +++ b/clang/unittests/Lex/ModuleDeclStateTest.cpp @@ -54,8 +54,8 @@ class CheckNamedModuleImportingCB : public PPCallbacks { class ModuleDeclStateTest : public ::testing::Test { protected: ModuleDeclStateTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-unknown-linux-gnu"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -94,7 +94,6 @@ class ModuleDeclStateTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Lex/PPCallbacksTest.cpp b/clang/unittests/Lex/PPCallbacksTest.cpp index af86c1888f2c7..f76ba793c7258 100644 --- a/clang/unittests/Lex/PPCallbacksTest.cpp +++ b/clang/unittests/Lex/PPCallbacksTest.cpp @@ -135,7 +135,7 @@ class PPCallbacksTest : public ::testing::Test { PPCallbacksTest() : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), FileMgr(FileSystemOptions(), InMemoryFileSystem), - DiagID(new DiagnosticIDs()), + DiagID(DiagnosticIDs::create()), Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions()) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; diff --git a/clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp b/clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp index 54c1d020aa0ea..4a88bd4d3586f 100644 --- a/clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp +++ b/clang/unittests/Lex/PPConditionalDirectiveRecordTest.cpp @@ -29,8 +29,8 @@ namespace { class PPConditionalDirectiveRecordTest : public ::testing::Test { protected: PPConditionalDirectiveRecordTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -38,7 +38,6 @@ class PPConditionalDirectiveRecordTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Lex/PPDependencyDirectivesTest.cpp b/clang/unittests/Lex/PPDependencyDirectivesTest.cpp index 061cb136a552a..08d9b4f811234 100644 --- a/clang/unittests/Lex/PPDependencyDirectivesTest.cpp +++ b/clang/unittests/Lex/PPDependencyDirectivesTest.cpp @@ -31,8 +31,8 @@ namespace { class PPDependencyDirectivesTest : public ::testing::Test { protected: PPDependencyDirectivesTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-macos12"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -40,7 +40,6 @@ class PPDependencyDirectivesTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Lex/PPMemoryAllocationsTest.cpp b/clang/unittests/Lex/PPMemoryAllocationsTest.cpp index 4d83003e28b36..f873774eb2019 100644 --- a/clang/unittests/Lex/PPMemoryAllocationsTest.cpp +++ b/clang/unittests/Lex/PPMemoryAllocationsTest.cpp @@ -27,8 +27,8 @@ namespace { class PPMemoryAllocationsTest : public ::testing::Test { protected: PPMemoryAllocationsTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Diags(DiagID, DiagOpts, new IgnoringDiagConsumer()), + : FileMgr(FileMgrOpts), + Diags(DiagnosticIDs::create(), DiagOpts, new IgnoringDiagConsumer()), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { TargetOpts->Triple = "x86_64-apple-darwin11.1.0"; Target = TargetInfo::CreateTargetInfo(Diags, *TargetOpts); @@ -36,7 +36,6 @@ class PPMemoryAllocationsTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; DiagnosticsEngine Diags; SourceManager SourceMgr; diff --git a/clang/unittests/Parse/ParseHLSLRootSignatureTest.cpp b/clang/unittests/Parse/ParseHLSLRootSignatureTest.cpp index 4b24800489c8e..31cbd05bc6582 100644 --- a/clang/unittests/Parse/ParseHLSLRootSignatureTest.cpp +++ b/clang/unittests/Parse/ParseHLSLRootSignatureTest.cpp @@ -71,8 +71,8 @@ class ExpectedDiagConsumer : public DiagnosticConsumer { class ParseHLSLRootSignatureTest : public ::testing::Test { protected: ParseHLSLRootSignatureTest() - : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()), - Consumer(new ExpectedDiagConsumer()), Diags(DiagID, DiagOpts, Consumer), + : FileMgr(FileMgrOpts), Consumer(new ExpectedDiagConsumer()), + Diags(DiagnosticIDs::create(), DiagOpts, Consumer), SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) { // This is an arbitrarily chosen target triple to create the target info. TargetOpts->Triple = "dxil"; @@ -114,7 +114,6 @@ class ParseHLSLRootSignatureTest : public ::testing::Test { FileSystemOptions FileMgrOpts; FileManager FileMgr; - IntrusiveRefCntPtr DiagID; DiagnosticOptions DiagOpts; ExpectedDiagConsumer *Consumer; DiagnosticsEngine Diags; diff --git a/clang/unittests/Sema/ExternalSemaSourceTest.cpp b/clang/unittests/Sema/ExternalSemaSourceTest.cpp index cc9dd4175af55..2524ac3ea518b 100644 --- a/clang/unittests/Sema/ExternalSemaSourceTest.cpp +++ b/clang/unittests/Sema/ExternalSemaSourceTest.cpp @@ -181,7 +181,7 @@ class FunctionTypoProvider : public clang::ExternalSemaSource { // performing semantic analysis. class ExternalSemaSourceInstaller : public clang::ASTFrontendAction { std::vector Watchers; - std::vector Sources; + std::vector> Sources; std::unique_ptr OwnedClient; protected: @@ -212,8 +212,8 @@ class ExternalSemaSourceInstaller : public clang::ASTFrontendAction { } public: - void PushSource(clang::ExternalSemaSource *Source) { - Sources.push_back(Source); + void PushSource(llvm::IntrusiveRefCntPtr Source) { + Sources.push_back(std::move(Source)); } void PushWatcher(DiagnosticWatcher *Watcher) { Watchers.push_back(Watcher); } @@ -238,7 +238,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionPrioritized) { auto Installer = std::make_unique(); auto Provider = makeIntrusiveRefCnt("AAB", "BBB"); DiagnosticWatcher Watcher("AAB", "BBB"); - Installer->PushSource(Provider.get()); + Installer->PushSource(Provider); Installer->PushWatcher(&Watcher); std::vector Args(1, "-std=c++11"); ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs( @@ -255,9 +255,9 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) { auto Second = makeIntrusiveRefCnt("AAB", "CCC"); auto Third = makeIntrusiveRefCnt("AAB", "DDD"); DiagnosticWatcher Watcher("AAB", "CCC"); - Installer->PushSource(First.get()); - Installer->PushSource(Second.get()); - Installer->PushSource(Third.get()); + Installer->PushSource(First); + Installer->PushSource(Second); + Installer->PushSource(Third); Installer->PushWatcher(&Watcher); std::vector Args(1, "-std=c++11"); ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs( @@ -273,7 +273,7 @@ TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) { TEST(ExternalSemaSource, TryOtherTacticsBeforeDiagnosing) { auto Installer = std::make_unique(); auto Diagnoser = makeIntrusiveRefCnt(false); - Installer->PushSource(Diagnoser.get()); + Installer->PushSource(Diagnoser); std::vector Args(1, "-std=c++11"); // This code hits the class template specialization/class member of a class // template specialization checks in Sema::RequireCompleteTypeImpl. @@ -291,9 +291,9 @@ TEST(ExternalSemaSource, FirstDiagnoserTaken) { auto First = makeIntrusiveRefCnt(false); auto Second = makeIntrusiveRefCnt(true); auto Third = makeIntrusiveRefCnt(true); - Installer->PushSource(First.get()); - Installer->PushSource(Second.get()); - Installer->PushSource(Third.get()); + Installer->PushSource(First); + Installer->PushSource(Second); + Installer->PushSource(Third); std::vector Args(1, "-std=c++11"); ASSERT_FALSE(clang::tooling::runToolOnCodeWithArgs( std::move(Installer), "class Incomplete; Incomplete IncompleteInstance;", diff --git a/clang/unittests/Sema/SemaNoloadLookupTest.cpp b/clang/unittests/Sema/SemaNoloadLookupTest.cpp index 5a04f42697b99..e565372698e5e 100644 --- a/clang/unittests/Sema/SemaNoloadLookupTest.cpp +++ b/clang/unittests/Sema/SemaNoloadLookupTest.cpp @@ -82,7 +82,7 @@ class NoloadLookupTest : public ::testing::Test { EXPECT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.getFrontendOpts().OutputFile = CacheBMIPath; GenerateReducedModuleInterfaceAction Action; EXPECT_TRUE(Instance.ExecuteAction(Action)); diff --git a/clang/unittests/Serialization/ForceCheckFileInputTest.cpp b/clang/unittests/Serialization/ForceCheckFileInputTest.cpp index 70e9fad858767..edf33ae04230b 100644 --- a/clang/unittests/Serialization/ForceCheckFileInputTest.cpp +++ b/clang/unittests/Serialization/ForceCheckFileInputTest.cpp @@ -87,7 +87,7 @@ export int aa = 43; Buf->release(); CompilerInstance Instance(std::move(Invocation)); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.getFrontendOpts().OutputFile = BMIPath; @@ -120,7 +120,7 @@ export int aa = 43; CompilerInstance Clang(std::move(Invocation)); - Clang.setDiagnostics(Diags.get()); + Clang.setDiagnostics(Diags); Clang.createVirtualFileSystem(CIOpts.VFS); Clang.createFileManager(); Clang.createSourceManager(); diff --git a/clang/unittests/Serialization/LoadSpecLazilyTest.cpp b/clang/unittests/Serialization/LoadSpecLazilyTest.cpp index 631547431ce7c..d7b55491fddac 100644 --- a/clang/unittests/Serialization/LoadSpecLazilyTest.cpp +++ b/clang/unittests/Serialization/LoadSpecLazilyTest.cpp @@ -80,7 +80,7 @@ class LoadSpecLazilyTest : public ::testing::Test { EXPECT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.getFrontendOpts().OutputFile = CacheBMIPath; // Avoid memory leaks. Instance.getFrontendOpts().DisableFree = false; diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp b/clang/unittests/Serialization/ModuleCacheTest.cpp index dbf2076b40396..e9b8da3dba6af 100644 --- a/clang/unittests/Serialization/ModuleCacheTest.cpp +++ b/clang/unittests/Serialization/ModuleCacheTest.cpp @@ -122,7 +122,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) { ASSERT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); Instance.setVirtualFileSystem(CIOpts.VFS); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); SyntaxOnlyAction Action; ASSERT_TRUE(Instance.ExecuteAction(Action)); ASSERT_FALSE(Diags->hasErrorOccurred()); @@ -147,7 +147,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) { Instance.getPCHContainerOperations(), &Instance.getModuleCache()); Instance2.setVirtualFileSystem(CIOpts.VFS); - Instance2.setDiagnostics(Diags.get()); + Instance2.setDiagnostics(Diags); SyntaxOnlyAction Action2; ASSERT_FALSE(Instance2.ExecuteAction(Action2)); ASSERT_TRUE(Diags->hasErrorOccurred()); @@ -174,7 +174,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) { ASSERT_TRUE(Invocation); CompilerInstance Instance(std::move(Invocation)); Instance.setVirtualFileSystem(CIOpts.VFS); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); SyntaxOnlyAction Action; ASSERT_TRUE(Instance.ExecuteAction(Action)); ASSERT_FALSE(Diags->hasErrorOccurred()); @@ -193,7 +193,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) { Instance.getPCHContainerOperations(), &Instance.getModuleCache()); Instance2.setVirtualFileSystem(CIOpts.VFS); - Instance2.setDiagnostics(Diags.get()); + Instance2.setDiagnostics(Diags); SyntaxOnlyAction Action2; ASSERT_FALSE(Instance2.ExecuteAction(Action2)); ASSERT_TRUE(Diags->hasErrorOccurred()); diff --git a/clang/unittests/Serialization/NoCommentsTest.cpp b/clang/unittests/Serialization/NoCommentsTest.cpp index f091e51e86c93..01bb6999a7c90 100644 --- a/clang/unittests/Serialization/NoCommentsTest.cpp +++ b/clang/unittests/Serialization/NoCommentsTest.cpp @@ -100,7 +100,7 @@ void foo() {} CompilerInstance Instance(std::move(Invocation)); Instance.createVirtualFileSystem(CIOpts.VFS); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); Instance.getFrontendOpts().OutputFile = CacheBMIPath; GenerateReducedModuleInterfaceAction Action; ASSERT_TRUE(Instance.ExecuteAction(Action)); diff --git a/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp b/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp index 9f7ec8182f748..55ee72875ead2 100644 --- a/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp +++ b/clang/unittests/Serialization/PreambleInNamedModulesTest.cpp @@ -101,7 +101,7 @@ export using ::E; PreambleCallbacks Callbacks; llvm::ErrorOr BuiltPreamble = PrecompiledPreamble::Build( - *Invocation, Buffer.get(), Bounds, *Diags, VFS, + *Invocation, Buffer.get(), Bounds, Diags, VFS, std::make_shared(), /*StoreInMemory=*/false, /*StoragePath=*/TestDir, Callbacks); @@ -112,7 +112,7 @@ export using ::E; BuiltPreamble->OverridePreamble(*Invocation, VFS, Buffer.get()); auto Clang = std::make_unique(std::move(Invocation)); - Clang->setDiagnostics(Diags.get()); + Clang->setDiagnostics(Diags); Clang->createVirtualFileSystem(VFS); Clang->createFileManager(); EXPECT_TRUE(Clang->createTarget()); diff --git a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp index 5b2988ed26336..743f851fc5fe1 100644 --- a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp +++ b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp @@ -106,7 +106,7 @@ export namespace Fibonacci Invocation->getFrontendOpts().DisableFree = false; CompilerInstance Instance(std::move(Invocation)); - Instance.setDiagnostics(Diags.get()); + Instance.setDiagnostics(Diags); std::string CacheBMIPath = llvm::Twine(TestDir + "/Cached.pcm").str(); Instance.getFrontendOpts().OutputFile = CacheBMIPath; diff --git a/clang/unittests/Tooling/RewriterTestContext.h b/clang/unittests/Tooling/RewriterTestContext.h index 2d697e276c5e8..3ac99a4c47e5f 100644 --- a/clang/unittests/Tooling/RewriterTestContext.h +++ b/clang/unittests/Tooling/RewriterTestContext.h @@ -49,8 +49,7 @@ struct RewriterDiagnosticConsumer : public DiagnosticConsumer { class RewriterTestContext { public: RewriterTestContext() - : Diagnostics(IntrusiveRefCntPtr(new DiagnosticIDs), - DiagOpts), + : Diagnostics(DiagnosticIDs::create(), DiagOpts), InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), OverlayFileSystem( new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())), diff --git a/clang/unittests/Tooling/Syntax/TokensTest.cpp b/clang/unittests/Tooling/Syntax/TokensTest.cpp index 8af6b28b7dec5..0eef6faadeed5 100644 --- a/clang/unittests/Tooling/Syntax/TokensTest.cpp +++ b/clang/unittests/Tooling/Syntax/TokensTest.cpp @@ -133,10 +133,10 @@ class TokenCollectorTest : public ::testing::Test { CI->getPreprocessorOpts().addRemappedFile( FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release()); CompilerInstance Compiler(std::move(CI)); - Compiler.setDiagnostics(Diags.get()); + Compiler.setDiagnostics(Diags); Compiler.setVirtualFileSystem(FS); - Compiler.setFileManager(FileMgr.get()); - Compiler.setSourceManager(SourceMgr.get()); + Compiler.setFileManager(FileMgr); + Compiler.setSourceManager(SourceMgr); this->Buffer = TokenBuffer(*SourceMgr); RecordTokens Recorder(this->Buffer); @@ -251,13 +251,14 @@ class TokenCollectorTest : public ::testing::Test { // Data fields. DiagnosticOptions DiagOpts; llvm::IntrusiveRefCntPtr Diags = - new DiagnosticsEngine(new DiagnosticIDs, DiagOpts); + llvm::makeIntrusiveRefCnt(DiagnosticIDs::create(), + DiagOpts); IntrusiveRefCntPtr FS = new llvm::vfs::InMemoryFileSystem; llvm::IntrusiveRefCntPtr FileMgr = - new FileManager(FileSystemOptions(), FS); + llvm::makeIntrusiveRefCnt(FileSystemOptions(), FS); llvm::IntrusiveRefCntPtr SourceMgr = - new SourceManager(*Diags, *FileMgr); + llvm::makeIntrusiveRefCnt(*Diags, *FileMgr); /// Contains last result of calling recordTokens(). TokenBuffer Buffer = TokenBuffer(*SourceMgr); }; diff --git a/clang/unittests/Tooling/Syntax/TreeTestBase.cpp b/clang/unittests/Tooling/Syntax/TreeTestBase.cpp index 6772cf8e11428..b2be64fc08f3d 100644 --- a/clang/unittests/Tooling/Syntax/TreeTestBase.cpp +++ b/clang/unittests/Tooling/Syntax/TreeTestBase.cpp @@ -152,10 +152,10 @@ SyntaxTreeTest::buildTree(StringRef Code, const TestClangConfig &ClangConfig) { Invocation->getPreprocessorOpts().addRemappedFile( FileName, llvm::MemoryBuffer::getMemBufferCopy(Code).release()); CompilerInstance Compiler(Invocation); - Compiler.setDiagnostics(Diags.get()); + Compiler.setDiagnostics(Diags); Compiler.setVirtualFileSystem(FS); - Compiler.setFileManager(FileMgr.get()); - Compiler.setSourceManager(SourceMgr.get()); + Compiler.setFileManager(FileMgr); + Compiler.setSourceManager(SourceMgr); syntax::TranslationUnit *Root = nullptr; BuildSyntaxTreeAction Recorder(Root, this->TM, this->TB, this->Arena); diff --git a/clang/unittests/Tooling/Syntax/TreeTestBase.h b/clang/unittests/Tooling/Syntax/TreeTestBase.h index 6110cffa708d9..633560dd0d103 100644 --- a/clang/unittests/Tooling/Syntax/TreeTestBase.h +++ b/clang/unittests/Tooling/Syntax/TreeTestBase.h @@ -42,13 +42,14 @@ class SyntaxTreeTest : public ::testing::Test, // Data fields. DiagnosticOptions DiagOpts; IntrusiveRefCntPtr Diags = - new DiagnosticsEngine(new DiagnosticIDs, DiagOpts); + llvm::makeIntrusiveRefCnt(DiagnosticIDs::create(), + DiagOpts); IntrusiveRefCntPtr FS = new llvm::vfs::InMemoryFileSystem; IntrusiveRefCntPtr FileMgr = - new FileManager(FileSystemOptions(), FS); + llvm::makeIntrusiveRefCnt(FileSystemOptions(), FS); IntrusiveRefCntPtr SourceMgr = - new SourceManager(*Diags, *FileMgr); + llvm::makeIntrusiveRefCnt(*Diags, *FileMgr); std::shared_ptr Invocation; // Set after calling buildTree(). std::unique_ptr TB; diff --git a/clang/unittests/Tooling/ToolingTest.cpp b/clang/unittests/Tooling/ToolingTest.cpp index 32af4b6b3b359..a713560b29078 100644 --- a/clang/unittests/Tooling/ToolingTest.cpp +++ b/clang/unittests/Tooling/ToolingTest.cpp @@ -193,8 +193,8 @@ TEST(ToolInvocation, TestMapVirtualFile) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); @@ -219,8 +219,8 @@ TEST(ToolInvocation, TestVirtualModulesCompilation) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); @@ -245,8 +245,8 @@ TEST(ToolInvocation, DiagnosticsEngineProperlyInitializedForCC1Construction) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); @@ -274,8 +274,8 @@ TEST(ToolInvocation, CustomDiagnosticOptionsOverwriteParsedOnes) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); @@ -320,8 +320,8 @@ TEST(ToolInvocation, DiagConsumerExpectingSourceManager) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); // Note: intentional error; user probably meant -ferror-limit=0. @@ -346,8 +346,8 @@ TEST(ToolInvocation, CC1Args) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); Args.push_back("-cc1"); @@ -366,8 +366,8 @@ TEST(ToolInvocation, CC1ArgsInvalid) { llvm::IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); OverlayFileSystem->pushOverlay(InMemoryFileSystem); - llvm::IntrusiveRefCntPtr Files( - new FileManager(FileSystemOptions(), OverlayFileSystem)); + auto Files = llvm::makeIntrusiveRefCnt(FileSystemOptions(), + OverlayFileSystem); std::vector Args; Args.push_back("tool-executable"); Args.push_back("-cc1"); diff --git a/flang/lib/Frontend/CompilerInstance.cpp b/flang/lib/Frontend/CompilerInstance.cpp index 2e0f91fb0521c..cd8dddad05282 100644 --- a/flang/lib/Frontend/CompilerInstance.cpp +++ b/flang/lib/Frontend/CompilerInstance.cpp @@ -233,10 +233,8 @@ clang::IntrusiveRefCntPtr CompilerInstance::createDiagnostics(clang::DiagnosticOptions &opts, clang::DiagnosticConsumer *client, bool shouldOwnClient) { - clang::IntrusiveRefCntPtr diagID( - new clang::DiagnosticIDs()); - clang::IntrusiveRefCntPtr diags( - new clang::DiagnosticsEngine(diagID, opts)); + auto diags = llvm::makeIntrusiveRefCnt( + clang::DiagnosticIDs::create(), opts); // Create the diagnostic client for reporting errors or for // implementing -verify. diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp index 3a2dffc66428f..8321b165ba5bb 100644 --- a/flang/tools/flang-driver/driver.cpp +++ b/flang/tools/flang-driver/driver.cpp @@ -123,15 +123,14 @@ int main(int argc, const char **argv) { // Create DiagnosticsEngine for the compiler driver std::unique_ptr diagOpts = createAndPopulateDiagOpts(args); - llvm::IntrusiveRefCntPtr diagID( - new clang::DiagnosticIDs()); Fortran::frontend::TextDiagnosticPrinter *diagClient = new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), *diagOpts); diagClient->setPrefix( std::string(llvm::sys::path::stem(getExecutablePath(args[0])))); - clang::DiagnosticsEngine diags(diagID, *diagOpts, diagClient); + clang::DiagnosticsEngine diags(clang::DiagnosticIDs::create(), *diagOpts, + diagClient); // Prepare the driver clang::driver::Driver theDriver(driverPath, diff --git a/flang/tools/flang-driver/fc1_main.cpp b/flang/tools/flang-driver/fc1_main.cpp index f2cd513d0028c..d9b103dbe6c8c 100644 --- a/flang/tools/flang-driver/fc1_main.cpp +++ b/flang/tools/flang-driver/fc1_main.cpp @@ -65,10 +65,9 @@ int fc1_main(llvm::ArrayRef argv, const char *argv0) { // Create CompilerInvocation - use a dedicated instance of DiagnosticsEngine // for parsing the arguments - llvm::IntrusiveRefCntPtr diagID( - new clang::DiagnosticIDs()); clang::DiagnosticOptions diagOpts; - clang::DiagnosticsEngine diags(diagID, diagOpts, diagsBuffer); + clang::DiagnosticsEngine diags(clang::DiagnosticIDs::create(), diagOpts, + diagsBuffer); bool success = CompilerInvocation::createFromArgs(flang->getInvocation(), argv, diags, argv0); diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp index 5d67a51b26905..a95fce1c5aa96 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.cpp @@ -18,10 +18,7 @@ lldb_private::ASTConsumerForwarder::~ASTConsumerForwarder() = default; void lldb_private::ASTConsumerForwarder::PrintStats() { m_c->PrintStats(); } -lldb_private::SemaSourceWithPriorities::~SemaSourceWithPriorities() { - for (auto *Source : Sources) - Source->Release(); -} +lldb_private::SemaSourceWithPriorities::~SemaSourceWithPriorities() = default; void lldb_private::SemaSourceWithPriorities::PrintStats() { for (size_t i = 0; i < Sources.size(); ++i) diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h index fe6f477b6d326..8c025d522e171 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h +++ b/lldb/source/Plugins/ExpressionParser/Clang/ASTUtils.h @@ -33,8 +33,9 @@ class ExternalASTSourceWrapper : public clang::ExternalSemaSource { llvm::IntrusiveRefCntPtr m_Source; public: - explicit ExternalASTSourceWrapper(ExternalASTSource *Source) - : m_Source(Source) { + explicit ExternalASTSourceWrapper( + llvm::IntrusiveRefCntPtr Source) + : m_Source(std::move(Source)) { assert(m_Source && "Can't wrap nullptr ExternalASTSource"); } @@ -284,7 +285,8 @@ class SemaSourceWithPriorities : public clang::ExternalSemaSource { private: /// The sources ordered in decreasing priority. - llvm::SmallVector Sources; + llvm::SmallVector, 2> + Sources; public: /// Construct a SemaSourceWithPriorities with a 'high quality' source that @@ -292,16 +294,14 @@ class SemaSourceWithPriorities : public clang::ExternalSemaSource { /// as a fallback. /// /// This class assumes shared ownership of the sources provided to it. - SemaSourceWithPriorities(clang::ExternalSemaSource *high_quality_source, - clang::ExternalSemaSource *low_quality_source) { + SemaSourceWithPriorities( + llvm::IntrusiveRefCntPtr high_quality_source, + llvm::IntrusiveRefCntPtr low_quality_source) { assert(high_quality_source); assert(low_quality_source); - high_quality_source->Retain(); - low_quality_source->Retain(); - - Sources.push_back(high_quality_source); - Sources.push_back(low_quality_source); + Sources.push_back(std::move(high_quality_source)); + Sources.push_back(std::move(low_quality_source)); } ~SemaSourceWithPriorities() override; @@ -382,7 +382,7 @@ class SemaSourceWithPriorities : public clang::ExternalSemaSource { clang::CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override { - for (auto *S : Sources) + for (const auto &S : Sources) if (auto *R = S->GetExternalCXXCtorInitializers(Offset)) return R; return nullptr; @@ -430,7 +430,7 @@ class SemaSourceWithPriorities : public clang::ExternalSemaSource { } void CompleteType(clang::TagDecl *Tag) override { - for (clang::ExternalSemaSource *S : Sources) { + for (const auto &S : Sources) { S->CompleteType(Tag); // Stop after the first source completed the type. if (Tag->isCompleteDefinition()) diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h index ee3acb409e692..d08befc7eaa06 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangASTSource.h @@ -257,8 +257,8 @@ class ClangASTSource : public clang::ExternalASTSource, ClangASTSource &m_original; }; - clang::ExternalASTSource *CreateProxy() { - return new ClangASTSourceProxy(*this); + llvm::IntrusiveRefCntPtr CreateProxy() { + return llvm::makeIntrusiveRefCnt(*this); } protected: diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp index 3c691b5c92e78..c75464d2fa1ad 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp @@ -1344,16 +1344,18 @@ ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager, decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer()); decl_map->InstallDiagnosticManager(diagnostic_manager); - clang::ExternalASTSource *ast_source = decl_map->CreateProxy(); + llvm::IntrusiveRefCntPtr ast_source = + decl_map->CreateProxy(); - auto *ast_source_wrapper = new ExternalASTSourceWrapper(ast_source); + auto ast_source_wrapper = + llvm::makeIntrusiveRefCnt(ast_source); if (ast_context.getExternalSource()) { - auto *module_wrapper = - new ExternalASTSourceWrapper(ast_context.getExternalSource()); + auto module_wrapper = llvm::makeIntrusiveRefCnt( + ast_context.getExternalSourcePtr()); - auto *multiplexer = - new SemaSourceWithPriorities(module_wrapper, ast_source_wrapper); + auto multiplexer = llvm::makeIntrusiveRefCnt( + module_wrapper, ast_source_wrapper); ast_context.setExternalSource(multiplexer); } else { diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp index 06f3a7efac7a2..ff9ed9c27f70f 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionSourceCode.cpp @@ -260,9 +260,8 @@ TokenVerifier::TokenVerifier(std::string body) { // Let's build the actual source code Clang needs and setup some utility // objects. - llvm::IntrusiveRefCntPtr diag_ids(new DiagnosticIDs()); DiagnosticOptions diags_opts; - DiagnosticsEngine diags(diag_ids, diags_opts); + DiagnosticsEngine diags(DiagnosticIDs::create(), diags_opts); clang::SourceManager SM(diags, file_mgr); auto buf = llvm::MemoryBuffer::getMemBuffer(body); diff --git a/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp b/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp index 14f08d3039b81..d421d6d8067b4 100644 --- a/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp +++ b/lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp @@ -747,7 +747,7 @@ ClangModulesDeclVendor::Create(Target &target) { // Make sure clang uses the same VFS as LLDB. instance->setVirtualFileSystem(FileSystem::Instance().GetVirtualFileSystem()); instance->createFileManager(); - instance->setDiagnostics(diagnostics_engine.get()); + instance->setDiagnostics(diagnostics_engine); std::unique_ptr action(new clang::SyntaxOnlyAction); diff --git a/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp b/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp index 8cc5714d0f0fc..9cb5ea3078995 100644 --- a/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp +++ b/lldb/source/Plugins/Language/ClangCommon/ClangHighlighter.cpp @@ -162,9 +162,8 @@ void ClangHighlighter::Highlight(const HighlightStyle &options, // Let's build the actual source code Clang needs and setup some utility // objects. std::string full_source = previous_lines.str() + line.str(); - llvm::IntrusiveRefCntPtr diag_ids(new DiagnosticIDs()); DiagnosticOptions diags_opts; - DiagnosticsEngine diags(diag_ids, diags_opts); + DiagnosticsEngine diags(DiagnosticIDs::create(), diags_opts); clang::SourceManager SM(diags, file_mgr); auto buf = llvm::MemoryBuffer::getMemBuffer(full_source); diff --git a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp index a5e33e65fe2b4..86bc4d1161aec 100644 --- a/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp +++ b/lldb/source/Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCDeclVendor.cpp @@ -145,9 +145,9 @@ AppleObjCDeclVendor::AppleObjCDeclVendor(ObjCLanguageRuntime &runtime) m_ast_ctx = std::make_shared( "AppleObjCDeclVendor AST", runtime.GetProcess()->GetTarget().GetArchitecture().GetTriple()); - m_external_source = new AppleObjCExternalASTSource(*this); - llvm::IntrusiveRefCntPtr external_source_owning_ptr( - m_external_source); + auto external_source_owning_ptr = + llvm::makeIntrusiveRefCnt(*this); + m_external_source = external_source_owning_ptr.get(); m_ast_ctx->getASTContext().setExternalSource(external_source_owning_ptr); } diff --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp index f768df34221cc..f068401e6cde4 100644 --- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp +++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp @@ -632,10 +632,10 @@ void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) { } void TypeSystemClang::SetExternalSource( - llvm::IntrusiveRefCntPtr &ast_source_up) { + llvm::IntrusiveRefCntPtr ast_source_sp) { ASTContext &ast = getASTContext(); ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true); - ast.setExternalSource(ast_source_up); + ast.setExternalSource(std::move(ast_source_sp)); } ASTContext &TypeSystemClang::getASTContext() const { @@ -682,10 +682,9 @@ void TypeSystemClang::CreateASTContext() { m_file_manager_up = std::make_unique( file_system_options, FileSystem::Instance().GetVirtualFileSystem()); - llvm::IntrusiveRefCntPtr diag_id_sp(new DiagnosticIDs()); m_diagnostic_options_up = std::make_unique(); - m_diagnostics_engine_up = - std::make_unique(diag_id_sp, *m_diagnostic_options_up); + m_diagnostics_engine_up = std::make_unique( + DiagnosticIDs::create(), *m_diagnostic_options_up); m_source_manager_up = std::make_unique( *m_diagnostics_engine_up, *m_file_manager_up); @@ -719,9 +718,9 @@ void TypeSystemClang::CreateASTContext() { GetASTMap().Insert(m_ast_up.get(), this); - llvm::IntrusiveRefCntPtr ast_source_up( - new ClangExternalASTSourceCallbacks(*this)); - SetExternalSource(ast_source_up); + auto ast_source_sp = + llvm::makeIntrusiveRefCnt(*this); + SetExternalSource(ast_source_sp); } TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) { @@ -9728,8 +9727,8 @@ class SpecializedScratchAST : public TypeSystemClang { m_scratch_ast_source_up(std::move(ast_source)) { // Setup the ClangASTSource to complete this AST. m_scratch_ast_source_up->InstallASTContext(*this); - llvm::IntrusiveRefCntPtr proxy_ast_source( - m_scratch_ast_source_up->CreateProxy()); + llvm::IntrusiveRefCntPtr proxy_ast_source = + m_scratch_ast_source_up->CreateProxy(); SetExternalSource(proxy_ast_source); } @@ -9749,8 +9748,8 @@ ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target, new ClangPersistentVariables(target.shared_from_this())) { m_scratch_ast_source_up = CreateASTSource(); m_scratch_ast_source_up->InstallASTContext(*this); - llvm::IntrusiveRefCntPtr proxy_ast_source( - m_scratch_ast_source_up->CreateProxy()); + llvm::IntrusiveRefCntPtr proxy_ast_source = + m_scratch_ast_source_up->CreateProxy(); SetExternalSource(proxy_ast_source); } diff --git a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h index 0d4d95bc8c457..6bf8b81147ca1 100644 --- a/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h +++ b/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h @@ -180,7 +180,7 @@ class TypeSystemClang : public TypeSystem { const char *GetTargetTriple(); void SetExternalSource( - llvm::IntrusiveRefCntPtr &ast_source_up); + llvm::IntrusiveRefCntPtr ast_source_sp); bool GetCompleteDecl(clang::Decl *decl) { return TypeSystemClang::GetCompleteDecl(&getASTContext(), decl);