diff options
Diffstat (limited to 'clang/lib/Frontend')
-rw-r--r-- | clang/lib/Frontend/ASTUnit.cpp | 4 | ||||
-rw-r--r-- | clang/lib/Frontend/ChainedIncludesSource.cpp | 1 | ||||
-rw-r--r-- | clang/lib/Frontend/CompilerInstance.cpp | 625 | ||||
-rw-r--r-- | clang/lib/Frontend/CompilerInvocation.cpp | 146 | ||||
-rw-r--r-- | clang/lib/Frontend/CreateInvocationFromCommandLine.cpp | 5 | ||||
-rw-r--r-- | clang/lib/Frontend/FrontendAction.cpp | 9 | ||||
-rw-r--r-- | clang/lib/Frontend/FrontendActions.cpp | 8 | ||||
-rw-r--r-- | clang/lib/Frontend/InitPreprocessor.cpp | 23 | ||||
-rw-r--r-- | clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp | 49 | ||||
-rw-r--r-- | clang/lib/Frontend/MultiplexConsumer.cpp | 5 | ||||
-rw-r--r-- | clang/lib/Frontend/PrecompiledPreamble.cpp | 17 | ||||
-rw-r--r-- | clang/lib/Frontend/Rewrite/FrontendActions.cpp | 8 | ||||
-rw-r--r-- | clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp | 24 | ||||
-rw-r--r-- | clang/lib/Frontend/Rewrite/RewriteObjC.cpp | 24 | ||||
-rw-r--r-- | clang/lib/Frontend/TextDiagnostic.cpp | 23 |
15 files changed, 564 insertions, 407 deletions
diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp index f5e291b7fe17..b3264952ff47 100644 --- a/clang/lib/Frontend/ASTUnit.cpp +++ b/clang/lib/Frontend/ASTUnit.cpp @@ -61,7 +61,7 @@ #include "clang/Serialization/ASTWriter.h" #include "clang/Serialization/ContinuousRangeMap.h" #include "clang/Serialization/InMemoryModuleCache.h" -#include "clang/Serialization/Module.h" +#include "clang/Serialization/ModuleFile.h" #include "clang/Serialization/PCHContainerOperations.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" @@ -1457,7 +1457,7 @@ void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) { CI.setFileManager(nullptr); if (CI.hasTarget()) Target = &CI.getTarget(); - Reader = CI.getModuleManager(); + Reader = CI.getASTReader(); HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure(); } diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp b/clang/lib/Frontend/ChainedIncludesSource.cpp index 29fee7246d14..dec281529b9e 100644 --- a/clang/lib/Frontend/ChainedIncludesSource.cpp +++ b/clang/lib/Frontend/ChainedIncludesSource.cpp @@ -11,6 +11,7 @@ // //===----------------------------------------------------------------------===// +#include "clang/Basic/Builtins.h" #include "clang/Basic/TargetInfo.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp index c409c07ff133..688f21dd0908 100644 --- a/clang/lib/Frontend/CompilerInstance.cpp +++ b/clang/lib/Frontend/CompilerInstance.cpp @@ -75,7 +75,7 @@ void CompilerInstance::setInvocation( bool CompilerInstance::shouldBuildGlobalModuleIndex() const { return (BuildGlobalModuleIndex || - (ModuleManager && ModuleManager->isGlobalIndexUnavailable() && + (TheASTReader && TheASTReader->isGlobalIndexUnavailable() && getFrontendOpts().GenerateGlobalModuleIndex)) && !ModuleBuildFailed; } @@ -135,13 +135,13 @@ std::unique_ptr<Sema> CompilerInstance::takeSema() { return std::move(TheSema); } -IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const { - return ModuleManager; +IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const { + return TheASTReader; } void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) { assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() && "Expected ASTReader to use the same PCM cache"); - ModuleManager = std::move(Reader); + TheASTReader = std::move(Reader); } std::shared_ptr<ModuleDependencyCollector> @@ -380,7 +380,7 @@ void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { const PreprocessorOptions &PPOpts = getPreprocessorOpts(); // The module manager holds a reference to the old preprocessor (if any). - ModuleManager.reset(); + TheASTReader.reset(); // Create the Preprocessor. HeaderSearch *HeaderInfo = @@ -494,7 +494,7 @@ void CompilerInstance::createPCHExternalASTSource( StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener) { bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; - ModuleManager = createPCHExternalASTSource( + TheASTReader = createPCHExternalASTSource( Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation, AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(), getASTContext(), getPCHContainerReader(), @@ -672,7 +672,7 @@ CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile, StringRef Extension) { return createOutputFile(getFrontendOpts().OutputFile, Binary, /*RemoveFileOnSignal=*/true, InFile, Extension, - /*UseTemporary=*/true); + getFrontendOpts().UseTemporary); } std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { @@ -917,8 +917,9 @@ bool CompilerInstance::ExecuteAction(FrontendAction &Act) { if (!hasTarget()) return false; - // Create TargetInfo for the other side of CUDA and OpenMP compilation. - if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) && + // Create TargetInfo for the other side of CUDA/OpenMP/SYCL compilation. + if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || + getLangOpts().SYCLIsDevice) && !getFrontendOpts().AuxTriple.empty()) { auto TO = std::make_shared<TargetOptions>(); TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); @@ -1179,13 +1180,12 @@ static const FileEntry *getPublicModuleMap(const FileEntry *File, return nullptr; } -/// Compile a module file for the given module, using the options -/// provided by the importing compiler instance. Returns true if the module -/// was built without errors. -static bool compileModuleImpl(CompilerInstance &ImportingInstance, - SourceLocation ImportLoc, - Module *Module, - StringRef ModuleFileName) { +/// Compile a module file for the given module in a separate compiler instance, +/// using the options provided by the importing compiler instance. Returns true +/// if the module was built without errors. +static bool compileModule(CompilerInstance &ImportingInstance, + SourceLocation ImportLoc, Module *Module, + StringRef ModuleFileName) { InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()), InputKind::ModuleMap); @@ -1245,10 +1245,17 @@ static bool compileModuleImpl(CompilerInstance &ImportingInstance, return Result; } -static bool compileAndLoadModule(CompilerInstance &ImportingInstance, - SourceLocation ImportLoc, - SourceLocation ModuleNameLoc, Module *Module, - StringRef ModuleFileName) { +/// Compile a module in a separate compiler instance and read the AST, +/// returning true if the module compiles without errors. +/// +/// Uses a lock file manager and exponential backoff to reduce the chances that +/// multiple instances will compete to create the same module. On timeout, +/// deletes the lock file in order to avoid deadlock from crashing processes or +/// bugs in the lock file manager. +static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, + SourceLocation ImportLoc, + SourceLocation ModuleNameLoc, + Module *Module, StringRef ModuleFileName) { DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); auto diagnoseBuildFailure = [&] { @@ -1276,8 +1283,8 @@ static bool compileAndLoadModule(CompilerInstance &ImportingInstance, LLVM_FALLTHROUGH; case llvm::LockFileManager::LFS_Owned: // We're responsible for building the module ourselves. - if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module, - ModuleFileName)) { + if (!compileModule(ImportingInstance, ModuleNameLoc, Module, + ModuleFileName)) { diagnoseBuildFailure(); return false; } @@ -1307,7 +1314,7 @@ static bool compileAndLoadModule(CompilerInstance &ImportingInstance, // Try to read the module file, now that we've compiled it. ASTReader::ASTReadResult ReadResult = - ImportingInstance.getModuleManager()->ReadAST( + ImportingInstance.getASTReader()->ReadAST( ModuleFileName, serialization::MK_ImplicitModule, ImportLoc, ModuleLoadCapabilities); @@ -1471,52 +1478,52 @@ static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { } } -void CompilerInstance::createModuleManager() { - if (!ModuleManager) { - if (!hasASTContext()) - createASTContext(); +void CompilerInstance::createASTReader() { + if (TheASTReader) + return; - // If we're implicitly building modules but not currently recursively - // building a module, check whether we need to prune the module cache. - if (getSourceManager().getModuleBuildStack().empty() && - !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && - getHeaderSearchOpts().ModuleCachePruneInterval > 0 && - getHeaderSearchOpts().ModuleCachePruneAfter > 0) { - pruneModuleCache(getHeaderSearchOpts()); - } + if (!hasASTContext()) + createASTContext(); + + // If we're implicitly building modules but not currently recursively + // building a module, check whether we need to prune the module cache. + if (getSourceManager().getModuleBuildStack().empty() && + !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && + getHeaderSearchOpts().ModuleCachePruneInterval > 0 && + getHeaderSearchOpts().ModuleCachePruneAfter > 0) { + pruneModuleCache(getHeaderSearchOpts()); + } - HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); - std::string Sysroot = HSOpts.Sysroot; - const PreprocessorOptions &PPOpts = getPreprocessorOpts(); - std::unique_ptr<llvm::Timer> ReadTimer; - if (FrontendTimerGroup) - ReadTimer = std::make_unique<llvm::Timer>("reading_modules", - "Reading modules", - *FrontendTimerGroup); - ModuleManager = new ASTReader( - getPreprocessor(), getModuleCache(), &getASTContext(), - getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, - Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation, - /*AllowASTWithCompilerErrors=*/false, - /*AllowConfigurationMismatch=*/false, - HSOpts.ModulesValidateSystemHeaders, - HSOpts.ValidateASTInputFilesContent, - getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); - if (hasASTConsumer()) { - ModuleManager->setDeserializationListener( + HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); + std::string Sysroot = HSOpts.Sysroot; + const PreprocessorOptions &PPOpts = getPreprocessorOpts(); + std::unique_ptr<llvm::Timer> ReadTimer; + if (FrontendTimerGroup) + ReadTimer = std::make_unique<llvm::Timer>("reading_modules", + "Reading modules", + *FrontendTimerGroup); + TheASTReader = new ASTReader( + getPreprocessor(), getModuleCache(), &getASTContext(), + getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, + Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation, + /*AllowASTWithCompilerErrors=*/false, + /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, + HSOpts.ValidateASTInputFilesContent, + getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); + if (hasASTConsumer()) { + TheASTReader->setDeserializationListener( getASTConsumer().GetASTDeserializationListener()); - getASTContext().setASTMutationListener( - getASTConsumer().GetASTMutationListener()); - } - getASTContext().setExternalSource(ModuleManager); - if (hasSema()) - ModuleManager->InitializeSema(getSema()); - if (hasASTConsumer()) - ModuleManager->StartTranslationUnit(&getASTConsumer()); - - for (auto &Listener : DependencyCollectors) - Listener->attachToASTReader(*ModuleManager); + getASTContext().setASTMutationListener( + getASTConsumer().GetASTMutationListener()); } + getASTContext().setExternalSource(TheASTReader); + if (hasSema()) + TheASTReader->InitializeSema(getSema()); + if (hasASTConsumer()) + TheASTReader->StartTranslationUnit(&getASTConsumer()); + + for (auto &Listener : DependencyCollectors) + Listener->attachToASTReader(*TheASTReader); } bool CompilerInstance::loadModuleFile(StringRef FileName) { @@ -1541,12 +1548,9 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { } void registerAll() { - for (auto *II : LoadedModules) { - CI.KnownModules[II] = CI.getPreprocessor() - .getHeaderSearchInfo() - .getModuleMap() - .findModule(II->getName()); - } + ModuleMap &MM = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(); + for (auto *II : LoadedModules) + MM.cacheModuleLoad(*II, MM.findModule(II->getName())); LoadedModules.clear(); } @@ -1576,8 +1580,8 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { }; // If we don't already have an ASTReader, create one now. - if (!ModuleManager) - createModuleManager(); + if (!TheASTReader) + createASTReader(); // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the // ASTReader to diagnose it, since it can produce better errors that we can. @@ -1588,11 +1592,11 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { auto Listener = std::make_unique<ReadModuleNames>(*this); auto &ListenerRef = *Listener; - ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager, + ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader, std::move(Listener)); // Try to load the module file. - switch (ModuleManager->ReadAST( + switch (TheASTReader->ReadAST( FileName, serialization::MK_ExplicitModule, SourceLocation(), ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) { case ASTReader::Success: @@ -1615,6 +1619,220 @@ bool CompilerInstance::loadModuleFile(StringRef FileName) { } } +namespace { +enum ModuleSource { + MS_ModuleNotFound, + MS_ModuleCache, + MS_PrebuiltModulePath, + MS_ModuleBuildPragma +}; +} // end namespace + +/// Select a source for loading the named module and compute the filename to +/// load it from. +static ModuleSource +selectModuleSource(Module *M, StringRef ModuleName, std::string &ModuleFilename, + const std::map<std::string, std::string> &BuiltModules, + HeaderSearch &HS) { + assert(ModuleFilename.empty() && "Already has a module source?"); + + // Check to see if the module has been built as part of this compilation + // via a module build pragma. + auto BuiltModuleIt = BuiltModules.find(ModuleName); + if (BuiltModuleIt != BuiltModules.end()) { + ModuleFilename = BuiltModuleIt->second; + return MS_ModuleBuildPragma; + } + + // Try to load the module from the prebuilt module path. + const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts(); + if (!HSOpts.PrebuiltModuleFiles.empty() || + !HSOpts.PrebuiltModulePaths.empty()) { + ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName); + if (!ModuleFilename.empty()) + return MS_PrebuiltModulePath; + } + + // Try to load the module from the module cache. + if (M) { + ModuleFilename = HS.getCachedModuleFileName(M); + return MS_ModuleCache; + } + + return MS_ModuleNotFound; +} + +ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST( + StringRef ModuleName, SourceLocation ImportLoc, + SourceLocation ModuleNameLoc, bool IsInclusionDirective) { + // Search for a module with the given name. + HeaderSearch &HS = PP->getHeaderSearchInfo(); + Module *M = HS.lookupModule(ModuleName, true, !IsInclusionDirective); + + // Select the source and filename for loading the named module. + std::string ModuleFilename; + ModuleSource Source = + selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS); + if (Source == MS_ModuleNotFound) { + // We can't find a module, error out here. + getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) + << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); + ModuleBuildFailed = true; + // FIXME: Why is this not cached? + return ModuleLoadResult::OtherUncachedFailure; + } + if (ModuleFilename.empty()) { + if (M && M->HasIncompatibleModuleFile) { + // We tried and failed to load a module file for this module. Fall + // back to textual inclusion for its headers. + return ModuleLoadResult::ConfigMismatch; + } + + getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) + << ModuleName; + ModuleBuildFailed = true; + // FIXME: Why is this not cached? + return ModuleLoadResult::OtherUncachedFailure; + } + + // Create an ASTReader on demand. + if (!getASTReader()) + createASTReader(); + + // Time how long it takes to load the module. + llvm::Timer Timer; + if (FrontendTimerGroup) + Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename, + *FrontendTimerGroup); + llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); + llvm::TimeTraceScope TimeScope("Module Load", ModuleName); + + // Try to load the module file. If we are not trying to load from the + // module cache, we don't know how to rebuild modules. + unsigned ARRFlags = Source == MS_ModuleCache + ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing + : Source == MS_PrebuiltModulePath + ? 0 + : ASTReader::ARR_ConfigurationMismatch; + switch (getASTReader()->ReadAST(ModuleFilename, + Source == MS_PrebuiltModulePath + ? serialization::MK_PrebuiltModule + : Source == MS_ModuleBuildPragma + ? serialization::MK_ExplicitModule + : serialization::MK_ImplicitModule, + ImportLoc, ARRFlags)) { + case ASTReader::Success: { + if (M) + return M; + assert(Source != MS_ModuleCache && + "missing module, but file loaded from cache"); + + // A prebuilt module is indexed as a ModuleFile; the Module does not exist + // until the first call to ReadAST. Look it up now. + M = HS.lookupModule(ModuleName, true, !IsInclusionDirective); + + // Check whether M refers to the file in the prebuilt module path. + if (M && M->getASTFile()) + if (auto ModuleFile = FileMgr->getFile(ModuleFilename)) + if (*ModuleFile == M->getASTFile()) + return M; + + ModuleBuildFailed = true; + getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) + << ModuleName; + return ModuleLoadResult(); + } + + case ASTReader::OutOfDate: + case ASTReader::Missing: + // The most interesting case. + break; + + case ASTReader::ConfigurationMismatch: + if (Source == MS_PrebuiltModulePath) + // FIXME: We shouldn't be setting HadFatalFailure below if we only + // produce a warning here! + getDiagnostics().Report(SourceLocation(), + diag::warn_module_config_mismatch) + << ModuleFilename; + // Fall through to error out. + LLVM_FALLTHROUGH; + case ASTReader::VersionMismatch: + case ASTReader::HadErrors: + // FIXME: Should this set ModuleBuildFailed = true? + ModuleLoader::HadFatalFailure = true; + // FIXME: The ASTReader will already have complained, but can we shoehorn + // that diagnostic information into a more useful form? + return ModuleLoadResult(); + + case ASTReader::Failure: + // FIXME: Should this set ModuleBuildFailed = true? + ModuleLoader::HadFatalFailure = true; + return ModuleLoadResult(); + } + + // ReadAST returned Missing or OutOfDate. + if (Source != MS_ModuleCache) { + // We don't know the desired configuration for this module and don't + // necessarily even have a module map. Since ReadAST already produces + // diagnostics for these two cases, we simply error out here. + ModuleBuildFailed = true; + return ModuleLoadResult(); + } + + // The module file is missing or out-of-date. Build it. + assert(M && "missing module, but trying to compile for cache"); + + // Check whether there is a cycle in the module graph. + ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); + ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); + for (; Pos != PosEnd; ++Pos) { + if (Pos->first == ModuleName) + break; + } + + if (Pos != PosEnd) { + SmallString<256> CyclePath; + for (; Pos != PosEnd; ++Pos) { + CyclePath += Pos->first; + CyclePath += " -> "; + } + CyclePath += ModuleName; + + getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) + << ModuleName << CyclePath; + // FIXME: Should this set ModuleBuildFailed = true? + // FIXME: Why is this not cached? + return ModuleLoadResult::OtherUncachedFailure; + } + + // Check whether we have already attempted to build this module (but + // failed). + if (getPreprocessorOpts().FailedModules && + getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { + getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) + << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); + ModuleBuildFailed = true; + // FIXME: Why is this not cached? + return ModuleLoadResult::OtherUncachedFailure; + } + + // Try to compile and then read the AST. + if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M, + ModuleFilename)) { + assert(getDiagnostics().hasErrorOccurred() && + "undiagnosed error in compileModuleAndReadAST"); + if (getPreprocessorOpts().FailedModules) + getPreprocessorOpts().FailedModules->addFailed(ModuleName); + ModuleBuildFailed = true; + // FIXME: Why is this not cached? + return ModuleLoadResult::OtherUncachedFailure; + } + + // Okay, we've rebuilt and now loaded the module. + return M; +} + ModuleLoadResult CompilerInstance::loadModule(SourceLocation ImportLoc, ModuleIdPath Path, @@ -1630,19 +1848,17 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) { // Make the named module visible. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) - ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, - ImportLoc); + TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility, + ImportLoc); return LastModuleImportResult; } - clang::Module *Module = nullptr; - // If we don't already have information on this module, load the module now. - llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known - = KnownModules.find(Path[0].first); - if (Known != KnownModules.end()) { - // Retrieve the cached top-level module. - Module = Known->second; + Module *Module = nullptr; + ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap(); + if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) { + // Use the cached result, which may be nullptr. + Module = *MaybeModule; } else if (ModuleName == getLangOpts().CurrentModule) { // This is the module we're building. Module = PP->getHeaderSearchInfo().lookupModule( @@ -1656,198 +1872,23 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, // ModuleBuildFailed = true; // return ModuleLoadResult(); //} - Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; + MM.cacheModuleLoad(*Path[0].first, Module); } else { - // Search for a module with the given name. - Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true, - !IsInclusionDirective); - HeaderSearchOptions &HSOpts = - PP->getHeaderSearchInfo().getHeaderSearchOpts(); - - std::string ModuleFileName; - enum ModuleSource { - ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma - } Source = ModuleNotFound; - - // Check to see if the module has been built as part of this compilation - // via a module build pragma. - auto BuiltModuleIt = BuiltModules.find(ModuleName); - if (BuiltModuleIt != BuiltModules.end()) { - ModuleFileName = BuiltModuleIt->second; - Source = ModuleBuildPragma; - } - - // Try to load the module from the prebuilt module path. - if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() || - !HSOpts.PrebuiltModulePaths.empty())) { - ModuleFileName = - PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName); - if (!ModuleFileName.empty()) - Source = PrebuiltModulePath; - } - - // Try to load the module from the module cache. - if (Source == ModuleNotFound && Module) { - ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module); - Source = ModuleCache; - } - - if (Source == ModuleNotFound) { - // We can't find a module, error out here. - getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) - << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); - ModuleBuildFailed = true; - return ModuleLoadResult(); - } - - if (ModuleFileName.empty()) { - if (Module && Module->HasIncompatibleModuleFile) { - // We tried and failed to load a module file for this module. Fall - // back to textual inclusion for its headers. - return ModuleLoadResult::ConfigMismatch; - } - - getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) - << ModuleName; - ModuleBuildFailed = true; - return ModuleLoadResult(); - } - - // If we don't already have an ASTReader, create one now. - if (!ModuleManager) - createModuleManager(); - - llvm::Timer Timer; - if (FrontendTimerGroup) - Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName, - *FrontendTimerGroup); - llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); - llvm::TimeTraceScope TimeScope("Module Load", ModuleName); - - // Try to load the module file. If we are not trying to load from the - // module cache, we don't know how to rebuild modules. - unsigned ARRFlags = Source == ModuleCache ? - ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing : - Source == PrebuiltModulePath ? - 0 : - ASTReader::ARR_ConfigurationMismatch; - switch (ModuleManager->ReadAST(ModuleFileName, - Source == PrebuiltModulePath - ? serialization::MK_PrebuiltModule - : Source == ModuleBuildPragma - ? serialization::MK_ExplicitModule - : serialization::MK_ImplicitModule, - ImportLoc, ARRFlags)) { - case ASTReader::Success: { - if (Source != ModuleCache && !Module) { - Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true, - !IsInclusionDirective); - auto ModuleFile = FileMgr->getFile(ModuleFileName); - if (!Module || !Module->getASTFile() || - !ModuleFile || (*ModuleFile != Module->getASTFile())) { - // Error out if Module does not refer to the file in the prebuilt - // module path. - getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) - << ModuleName; - ModuleBuildFailed = true; - KnownModules[Path[0].first] = nullptr; - return ModuleLoadResult(); - } - } - break; - } - - case ASTReader::OutOfDate: - case ASTReader::Missing: { - if (Source != ModuleCache) { - // We don't know the desired configuration for this module and don't - // necessarily even have a module map. Since ReadAST already produces - // diagnostics for these two cases, we simply error out here. - ModuleBuildFailed = true; - KnownModules[Path[0].first] = nullptr; - return ModuleLoadResult(); - } - - // The module file is missing or out-of-date. Build it. - assert(Module && "missing module file"); - // Check whether there is a cycle in the module graph. - ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); - ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); - for (; Pos != PosEnd; ++Pos) { - if (Pos->first == ModuleName) - break; - } - - if (Pos != PosEnd) { - SmallString<256> CyclePath; - for (; Pos != PosEnd; ++Pos) { - CyclePath += Pos->first; - CyclePath += " -> "; - } - CyclePath += ModuleName; - - getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) - << ModuleName << CyclePath; - return ModuleLoadResult(); - } - - // Check whether we have already attempted to build this module (but - // failed). - if (getPreprocessorOpts().FailedModules && - getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { - getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) - << ModuleName - << SourceRange(ImportLoc, ModuleNameLoc); - ModuleBuildFailed = true; - return ModuleLoadResult(); - } - - // Try to compile and then load the module. - if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module, - ModuleFileName)) { - assert(getDiagnostics().hasErrorOccurred() && - "undiagnosed error in compileAndLoadModule"); - if (getPreprocessorOpts().FailedModules) - getPreprocessorOpts().FailedModules->addFailed(ModuleName); - KnownModules[Path[0].first] = nullptr; - ModuleBuildFailed = true; - return ModuleLoadResult(); - } - - // Okay, we've rebuilt and now loaded the module. - break; - } - - case ASTReader::ConfigurationMismatch: - if (Source == PrebuiltModulePath) - // FIXME: We shouldn't be setting HadFatalFailure below if we only - // produce a warning here! - getDiagnostics().Report(SourceLocation(), - diag::warn_module_config_mismatch) - << ModuleFileName; - // Fall through to error out. - LLVM_FALLTHROUGH; - case ASTReader::VersionMismatch: - case ASTReader::HadErrors: - ModuleLoader::HadFatalFailure = true; - // FIXME: The ASTReader will already have complained, but can we shoehorn - // that diagnostic information into a more useful form? - KnownModules[Path[0].first] = nullptr; - return ModuleLoadResult(); - - case ASTReader::Failure: - ModuleLoader::HadFatalFailure = true; - // Already complained, but note now that we failed. - KnownModules[Path[0].first] = nullptr; - ModuleBuildFailed = true; - return ModuleLoadResult(); - } - - // Cache the result of this top-level module lookup for later. - Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; + ModuleLoadResult Result = findOrCompileModuleAndReadAST( + ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective); + // FIXME: Can we pull 'ModuleBuildFailed = true' out of the return + // sequences for findOrCompileModuleAndReadAST and do it here (as long as + // the result is not a config mismatch)? See FIXMEs there. + if (!Result.isNormal()) + return Result; + Module = Result; + MM.cacheModuleLoad(*Path[0].first, Module); + if (!Module) + return Module; } - // If we never found the module, fail. + // If we never found the module, fail. Otherwise, verify the module and link + // it up. if (!Module) return ModuleLoadResult(); @@ -1967,7 +2008,7 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, return ModuleLoadResult(); } - ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc); + TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc); } // Check for any configuration macros that have changed. @@ -1988,9 +2029,9 @@ CompilerInstance::loadModule(SourceLocation ImportLoc, return LastModuleImportResult; } -void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc, - StringRef ModuleName, - StringRef Source) { +void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc, + StringRef ModuleName, + StringRef Source) { // Avoid creating filenames with special characters. SmallString<128> CleanModuleName(ModuleName); for (auto &C : CleanModuleName) @@ -2044,27 +2085,27 @@ void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc, void CompilerInstance::makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) { - if (!ModuleManager) - createModuleManager(); - if (!ModuleManager) + if (!TheASTReader) + createASTReader(); + if (!TheASTReader) return; - ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc); + TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc); } GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( SourceLocation TriggerLoc) { if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) return nullptr; - if (!ModuleManager) - createModuleManager(); + if (!TheASTReader) + createASTReader(); // Can't do anything if we don't have the module manager. - if (!ModuleManager) + if (!TheASTReader) return nullptr; // Get an existing global index. This loads it if not already // loaded. - ModuleManager->loadGlobalIndex(); - GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex(); + TheASTReader->loadGlobalIndex(); + GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex(); // If the global index doesn't exist, create it. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && hasPreprocessor()) { @@ -2080,9 +2121,9 @@ GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( consumeError(std::move(Err)); return nullptr; } - ModuleManager->resetForReload(); - ModuleManager->loadGlobalIndex(); - GlobalIndex = ModuleManager->getGlobalIndex(); + TheASTReader->resetForReload(); + TheASTReader->loadGlobalIndex(); + GlobalIndex = TheASTReader->getGlobalIndex(); } // For finding modules needing to be imported for fixit messages, // we need to make the global index cover all modules, so we do that here. @@ -2111,9 +2152,9 @@ GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( consumeError(std::move(Err)); return nullptr; } - ModuleManager->resetForReload(); - ModuleManager->loadGlobalIndex(); - GlobalIndex = ModuleManager->getGlobalIndex(); + TheASTReader->resetForReload(); + TheASTReader->loadGlobalIndex(); + GlobalIndex = TheASTReader->getGlobalIndex(); } HaveFullGlobalModuleIndex = true; } diff --git a/clang/lib/Frontend/CompilerInvocation.cpp b/clang/lib/Frontend/CompilerInvocation.cpp index 665695ec3b18..e1e59565083b 100644 --- a/clang/lib/Frontend/CompilerInvocation.cpp +++ b/clang/lib/Frontend/CompilerInvocation.cpp @@ -334,7 +334,7 @@ static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, StringRef CheckerAndPackageList = A->getValue(); SmallVector<StringRef, 16> CheckersAndPackages; CheckerAndPackageList.split(CheckersAndPackages, ","); - for (const StringRef CheckerOrPackage : CheckersAndPackages) + for (const StringRef &CheckerOrPackage : CheckersAndPackages) Opts.CheckersAndPackages.emplace_back(CheckerOrPackage, IsEnabled); } @@ -476,7 +476,7 @@ static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, SmallVector<StringRef, 16> CheckersAndPackages; AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); - for (const StringRef CheckerOrPackage : CheckersAndPackages) { + for (const StringRef &CheckerOrPackage : CheckersAndPackages) { if (Diags) { bool IsChecker = CheckerOrPackage.contains('.'); bool IsValidName = @@ -607,7 +607,7 @@ static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, XRayInstrSet &S) { llvm::SmallVector<StringRef, 2> BundleParts; llvm::SplitString(Bundle, BundleParts, ","); - for (const auto B : BundleParts) { + for (const auto &B : BundleParts) { auto Mask = parseXRayInstrValue(B); if (Mask == XRayInstrKind::None) if (B != "none") @@ -731,6 +731,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, llvm::StringSwitch<unsigned>(A->getValue()) .Case("line-tables-only", codegenoptions::DebugLineTablesOnly) .Case("line-directives-only", codegenoptions::DebugDirectivesOnly) + .Case("constructor", codegenoptions::DebugInfoConstructor) .Case("limited", codegenoptions::LimitedDebugInfo) .Case("standalone", codegenoptions::FullDebugInfo) .Default(~0U); @@ -769,6 +770,9 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params); Opts.EmbedSource = Args.hasArg(OPT_gembed_source); + Opts.ForceDwarfFrameSection = + Args.hasFlag(OPT_fforce_dwarf_frame, OPT_fno_force_dwarf_frame, false); + for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) Opts.DebugPrefixMap.insert(StringRef(Arg).split('=')); @@ -784,8 +788,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, llvm::Triple::arm, llvm::Triple::armeb}; llvm::Triple T(TargetOpts.Triple); - if (Opts.OptimizationLevel > 0 && - Opts.getDebugInfo() >= codegenoptions::LimitedDebugInfo && + if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && llvm::is_contained(DebugEntryValueArchs, T.getArch())) Opts.EnableDebugEntryValues = Args.hasArg(OPT_femit_debug_entry_values); @@ -806,6 +809,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.RecordCommandLine = Args.getLastArgValue(OPT_record_command_line); Opts.MergeAllConstants = Args.hasArg(OPT_fmerge_all_constants); Opts.NoCommon = Args.hasArg(OPT_fno_common); + Opts.NoInlineLineTables = Args.hasArg(OPT_gno_inline_line_tables); Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float); Opts.OptimizeSize = getOptimizationLevelSize(Args); Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) || @@ -949,7 +953,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, << Args.getLastArg(OPT_mthread_model)->getAsString(Args) << Opts.ThreadModel; Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ); - Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array); + Opts.UseInitArray = !Args.hasArg(OPT_fno_use_init_array); Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections, OPT_fno_function_sections, false); @@ -1003,6 +1007,7 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name); Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier); + Opts.ControlFlowGuardNoChecks = Args.hasArg(OPT_cfguard_no_checks); Opts.ControlFlowGuard = Args.hasArg(OPT_cfguard); Opts.DisableGCov = Args.hasArg(OPT_test_coverage); @@ -1096,8 +1101,13 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, Diags, Opts.XRayInstrumentationBundle); + Opts.PatchableFunctionEntryCount = + getLastArgIntValue(Args, OPT_fpatchable_function_entry_EQ, 0, Diags); Opts.InstrumentForProfiling = Args.hasArg(OPT_pg); Opts.CallFEntry = Args.hasArg(OPT_mfentry); + Opts.MNopMCount = Args.hasArg(OPT_mnop_mcount); + Opts.RecordMCount = Args.hasArg(OPT_mrecord_mcount); + Opts.PackedStack = Args.hasArg(OPT_mpacked_stack); Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info); if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { @@ -1258,15 +1268,12 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, } } + Opts.TLSSize = getLastArgIntValue(Args, OPT_mtls_size_EQ, 0, Diags); + if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { StringRef Val = A->getValue(); - if (Val == "ieee") - Opts.FPDenormalMode = "ieee"; - else if (Val == "preserve-sign") - Opts.FPDenormalMode = "preserve-sign"; - else if (Val == "positive-zero") - Opts.FPDenormalMode = "positive-zero"; - else + Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); + if (Opts.FPDenormalMode == llvm::DenormalMode::Invalid) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; } @@ -1441,7 +1448,26 @@ static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, // Add sanitizer blacklists as extra dependencies. // They won't be discovered by the regular preprocessor, so // we let make / ninja to know about this implicit dependency. - Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry); + if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { + for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { + StringRef Val = A->getValue(); + if (Val.find('=') == StringRef::npos) + Opts.ExtraDeps.push_back(Val); + } + if (Opts.IncludeSystemHeaders) { + for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { + StringRef Val = A->getValue(); + if (Val.find('=') == StringRef::npos) + Opts.ExtraDeps.push_back(Val); + } + } + } + + // Propagate the extra dependencies. + for (const auto *A : Args.filtered(OPT_fdepfile_entry)) { + Opts.ExtraDeps.push_back(A->getValue()); + } + // Only the -fmodule-file=<file> form. for (const auto *A : Args.filtered(OPT_fmodule_file)) { StringRef Val = A->getValue(); @@ -1866,6 +1892,7 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files); Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp); + Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file); Opts.CodeCompleteOpts.IncludeMacros = Args.hasArg(OPT_code_completion_macros); @@ -2528,7 +2555,20 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.CUDADeviceApproxTranscendentals = 1; Opts.GPURelocatableDeviceCode = Args.hasArg(OPT_fgpu_rdc); + if (Args.hasArg(OPT_fgpu_allow_device_init)) { + if (Opts.HIP) + Opts.GPUAllowDeviceInit = 1; + else + Diags.Report(diag::warn_ignored_hip_only_option) + << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); + } Opts.HIPUseNewLaunchAPI = Args.hasArg(OPT_fhip_new_launch_api); + if (Opts.HIP) + Opts.GPUMaxThreadsPerBlock = getLastArgIntValue( + Args, OPT_gpu_max_threads_per_block_EQ, Opts.GPUMaxThreadsPerBlock); + else if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ)) + Diags.Report(diag::warn_ignored_hip_only_option) + << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); if (Opts.ObjC) { if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { @@ -2689,7 +2729,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, OPT_fno_dollars_in_identifiers, Opts.DollarIdents); Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings); - Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags); + Opts.setVtorDispMode( + MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags))); Opts.Borland = Args.hasArg(OPT_fborland_extensions); Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings); Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings, @@ -2749,6 +2790,9 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional); Opts.Coroutines = Opts.CPlusPlus2a || Args.hasArg(OPT_fcoroutines_ts); + Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || + Args.hasArg(OPT_fconvergent_functions); + Opts.DoubleSquareBracketAttributes = Args.hasFlag(OPT_fdouble_square_bracket_attributes, OPT_fno_double_square_bracket_attributes, @@ -2823,8 +2867,6 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags); Opts.EnableNewConstInterp = Args.hasArg(OPT_fexperimental_new_constant_interpreter); - Opts.ForceNewConstInterp = - Args.hasArg(OPT_fforce_experimental_new_constant_interpreter); Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags); Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing); Opts.NumLargeByValueCopy = @@ -2951,7 +2993,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Arch != llvm::Triple::x86; emitError |= (DefaultCC == LangOptions::DCC_VectorCall || DefaultCC == LangOptions::DCC_RegCall) && - !(Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64); + !T.isX86(); if (emitError) Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getSpelling() << T.getTriple(); @@ -2985,6 +3027,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); Opts.OpenMPIsDevice = Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); + Opts.OpenMPIRBuilder = + Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); bool IsTargetSpecified = Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); @@ -3041,7 +3085,8 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, llvm::Triple TT(A->getValue(i)); if (TT.getArch() == llvm::Triple::UnknownArch || - !(TT.getArch() == llvm::Triple::ppc || + !(TT.getArch() == llvm::Triple::aarch64 || + TT.getArch() == llvm::Triple::ppc || TT.getArch() == llvm::Triple::ppc64 || TT.getArch() == llvm::Triple::ppc64le || TT.getArch() == llvm::Triple::nvptx || @@ -3116,6 +3161,34 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; } + LangOptions::FPRoundingModeKind FPRM = LangOptions::FPR_ToNearest; + if (Args.hasArg(OPT_frounding_math)) { + FPRM = LangOptions::FPR_Dynamic; + } + Opts.setFPRoundingMode(FPRM); + + if (Args.hasArg(OPT_ftrapping_math)) { + Opts.setFPExceptionMode(LangOptions::FPE_Strict); + } + + if (Args.hasArg(OPT_fno_trapping_math)) { + Opts.setFPExceptionMode(LangOptions::FPE_Ignore); + } + + LangOptions::FPExceptionModeKind FPEB = LangOptions::FPE_Ignore; + if (Arg *A = Args.getLastArg(OPT_ffp_exception_behavior_EQ)) { + StringRef Val = A->getValue(); + if (Val.equals("ignore")) + FPEB = LangOptions::FPE_Ignore; + else if (Val.equals("maytrap")) + FPEB = LangOptions::FPE_MayTrap; + else if (Val.equals("strict")) + FPEB = LangOptions::FPE_Strict; + else + Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; + } + Opts.setFPExceptionMode(FPEB); + Opts.RetainCommentsFromSystemHeaders = Args.hasArg(OPT_fretain_comments_from_system_headers); @@ -3151,6 +3224,11 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.SanitizeAddressFieldPadding = getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags); Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); + std::vector<std::string> systemBlacklists = + Args.getAllArgValues(OPT_fsanitize_system_blacklist); + Opts.SanitizerBlacklistFiles.insert(Opts.SanitizerBlacklistFiles.end(), + systemBlacklists.begin(), + systemBlacklists.end()); // -fxray-instrument Opts.XRayInstrument = @@ -3279,6 +3357,9 @@ static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); + for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) + Opts.MacroPrefixMap.insert(StringRef(A).split('=')); + if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { StringRef Value(A->getValue()); size_t Comma = Value.find(','); @@ -3645,35 +3726,8 @@ std::string CompilerInvocation::getModuleHash() const { return llvm::APInt(64, code).toString(36, /*Signed=*/false); } -template<typename IntTy> -static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, - IntTy Default, - DiagnosticsEngine *Diags) { - IntTy Res = Default; - if (Arg *A = Args.getLastArg(Id)) { - if (StringRef(A->getValue()).getAsInteger(10, Res)) { - if (Diags) - Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args) - << A->getValue(); - } - } - return Res; -} - namespace clang { -// Declared in clang/Frontend/Utils.h. -int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default, - DiagnosticsEngine *Diags) { - return getLastArgIntValueImpl<int>(Args, Id, Default, Diags); -} - -uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id, - uint64_t Default, - DiagnosticsEngine *Diags) { - return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags); -} - IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags) { diff --git a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp index ab62b633cda3..18c4814bbd5c 100644 --- a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp +++ b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -26,7 +26,8 @@ using namespace llvm::opt; std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine( ArrayRef<const char *> ArgList, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, - IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool ShouldRecoverOnErorrs) { + IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool ShouldRecoverOnErorrs, + std::vector<std::string> *CC1Args) { if (!Diags.get()) { // No diagnostics engine was provided, so create our own diagnostics object // with the default options. @@ -89,6 +90,8 @@ std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine( } const ArgStringList &CCArgs = Cmd.getArguments(); + if (CC1Args) + *CC1Args = {CCArgs.begin(), CCArgs.end()}; auto CI = std::make_unique<CompilerInvocation>(); if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags) && !ShouldRecoverOnErorrs) diff --git a/clang/lib/Frontend/FrontendAction.cpp b/clang/lib/Frontend/FrontendAction.cpp index b3b7976f8f3e..934d17b3c925 100644 --- a/clang/lib/Frontend/FrontendAction.cpp +++ b/clang/lib/Frontend/FrontendAction.cpp @@ -10,6 +10,7 @@ #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" +#include "clang/Basic/Builtins.h" #include "clang/Basic/LangStandard.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" @@ -870,9 +871,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, // extended by an external source. if (CI.getLangOpts().Modules || !CI.hasASTContext() || !CI.getASTContext().getExternalSource()) { - CI.createModuleManager(); - CI.getModuleManager()->setDeserializationListener(DeserialListener, - DeleteDeserialListener); + CI.createASTReader(); + CI.getASTReader()->setDeserializationListener(DeserialListener, + DeleteDeserialListener); } } @@ -891,7 +892,7 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI, } else { // FIXME: If this is a problem, recover from it by creating a multiplex // source. - assert((!CI.getLangOpts().Modules || CI.getModuleManager()) && + assert((!CI.getLangOpts().Modules || CI.getASTReader()) && "modules enabled but created an external source that " "doesn't support modules"); } diff --git a/clang/lib/Frontend/FrontendActions.cpp b/clang/lib/Frontend/FrontendActions.cpp index 4d47c768ad3c..8574d0a7e813 100644 --- a/clang/lib/Frontend/FrontendActions.cpp +++ b/clang/lib/Frontend/FrontendActions.cpp @@ -140,7 +140,7 @@ GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile, std::unique_ptr<raw_pwrite_stream> OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, /*RemoveFileOnSignal=*/false, InFile, - /*Extension=*/"", /*UseTemporary=*/true); + /*Extension=*/"", CI.getFrontendOpts().UseTemporary); if (!OS) return nullptr; @@ -413,6 +413,8 @@ private: return "ExceptionSpecInstantiation"; case CodeSynthesisContext::DeclaringSpecialMember: return "DeclaringSpecialMember"; + case CodeSynthesisContext::DeclaringImplicitEqualityComparison: + return "DeclaringImplicitEqualityComparison"; case CodeSynthesisContext::DefiningSynthesizedFunction: return "DefiningSynthesizedFunction"; case CodeSynthesisContext::RewritingOperatorAsSpaceship: @@ -423,6 +425,10 @@ private: return "ConstraintsCheck"; case CodeSynthesisContext::ConstraintSubstitution: return "ConstraintSubstitution"; + case CodeSynthesisContext::ConstraintNormalization: + return "ConstraintNormalization"; + case CodeSynthesisContext::ParameterMappingSubstitution: + return "ParameterMappingSubstitution"; } return ""; } diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp index c27c33c530f6..2c7e3a56c043 100644 --- a/clang/lib/Frontend/InitPreprocessor.cpp +++ b/clang/lib/Frontend/InitPreprocessor.cpp @@ -484,6 +484,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, LangOpts.CPlusPlus2a ? "201907L" : LangOpts.CPlusPlus17 ? "201603L" : LangOpts.CPlusPlus14 ? "201304L" : "200704"); + Builder.defineMacro("__cpp_constexpr_in_decltype", "201711L"); Builder.defineMacro("__cpp_range_based_for", LangOpts.CPlusPlus17 ? "201603L" : "200907"); Builder.defineMacro("__cpp_static_assert", @@ -506,8 +507,10 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, if (LangOpts.CPlusPlus14) { Builder.defineMacro("__cpp_binary_literals", "201304L"); Builder.defineMacro("__cpp_digit_separators", "201309L"); - Builder.defineMacro("__cpp_init_captures", "201304L"); - Builder.defineMacro("__cpp_generic_lambdas", "201304L"); + Builder.defineMacro("__cpp_init_captures", + LangOpts.CPlusPlus2a ? "201803L" : "201304L"); + Builder.defineMacro("__cpp_generic_lambdas", + LangOpts.CPlusPlus2a ? "201707L" : "201304L"); Builder.defineMacro("__cpp_decltype_auto", "201304L"); Builder.defineMacro("__cpp_return_type_deduction", "201304L"); Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L"); @@ -523,7 +526,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, Builder.defineMacro("__cpp_noexcept_function_type", "201510L"); Builder.defineMacro("__cpp_capture_star_this", "201603L"); Builder.defineMacro("__cpp_if_constexpr", "201606L"); - Builder.defineMacro("__cpp_deduction_guides", "201703L"); + Builder.defineMacro("__cpp_deduction_guides", "201703L"); // (not latest) Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name) Builder.defineMacro("__cpp_namespace_attributes", "201411L"); Builder.defineMacro("__cpp_enumerator_attributes", "201411L"); @@ -531,7 +534,8 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, Builder.defineMacro("__cpp_variadic_using", "201611L"); Builder.defineMacro("__cpp_aggregate_bases", "201603L"); Builder.defineMacro("__cpp_structured_bindings", "201606L"); - Builder.defineMacro("__cpp_nontype_template_args", "201411L"); + Builder.defineMacro("__cpp_nontype_template_args", + "201411L"); // (not latest) Builder.defineMacro("__cpp_fold_expressions", "201603L"); Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L"); Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L"); @@ -543,9 +547,17 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, // C++20 features. if (LangOpts.CPlusPlus2a) { + //Builder.defineMacro("__cpp_aggregate_paren_init", "201902L"); + //Builder.defineMacro("__cpp_concepts", "201907L"); Builder.defineMacro("__cpp_conditional_explicit", "201806L"); + //Builder.defineMacro("__cpp_consteval", "201811L"); Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L"); Builder.defineMacro("__cpp_constinit", "201907L"); + //Builder.defineMacro("__cpp_coroutines", "201902L"); + Builder.defineMacro("__cpp_designated_initializers", "201707L"); + Builder.defineMacro("__cpp_impl_three_way_comparison", "201907L"); + //Builder.defineMacro("__cpp_modules", "201907L"); + //Builder.defineMacro("__cpp_using_enum", "201907L"); } if (LangOpts.Char8) Builder.defineMacro("__cpp_char8_t", "201811L"); @@ -1124,7 +1136,8 @@ void clang::InitializePreprocessor( if (InitOpts.UsePredefines) { // FIXME: This will create multiple definitions for most of the predefined // macros. This is not the right way to handle this. - if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice) && PP.getAuxTargetInfo()) + if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice || LangOpts.SYCLIsDevice) && + PP.getAuxTargetInfo()) InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts, PP.getPreprocessorOpts(), Builder); diff --git a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp index 0b28b78de3b1..7241081d6cc0 100644 --- a/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp +++ b/clang/lib/Frontend/InterfaceStubFunctionsConsumer.cpp @@ -52,11 +52,16 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer { if (!isVisible(ND)) return true; - if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) + if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { + if (const auto *Parent = VD->getParentFunctionOrMethod()) + if (isa<BlockDecl>(Parent) || isa<CXXMethodDecl>(Parent)) + return true; + if ((VD->getStorageClass() == StorageClass::SC_Extern) || (VD->getStorageClass() == StorageClass::SC_Static && VD->getParentFunctionOrMethod() == nullptr)) return true; + } if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { if (FD->isInlined() && !isa<CXXMethodDecl>(FD) && @@ -182,8 +187,36 @@ class InterfaceStubFunctionsConsumer : public ASTConsumer { case Decl::Kind::Enum: case Decl::Kind::EnumConstant: case Decl::Kind::TemplateTypeParm: + case Decl::Kind::NonTypeTemplateParm: + case Decl::Kind::CXXConversion: + case Decl::Kind::UnresolvedUsingValue: + case Decl::Kind::Using: + case Decl::Kind::UsingShadow: + case Decl::Kind::TypeAliasTemplate: + case Decl::Kind::TypeAlias: + case Decl::Kind::VarTemplate: + case Decl::Kind::VarTemplateSpecialization: + case Decl::Kind::UsingDirective: + case Decl::Kind::TemplateTemplateParm: + case Decl::Kind::ClassTemplatePartialSpecialization: + case Decl::Kind::IndirectField: + case Decl::Kind::ConstructorUsingShadow: + case Decl::Kind::CXXDeductionGuide: + case Decl::Kind::NamespaceAlias: + case Decl::Kind::UnresolvedUsingTypename: return true; - case Decl::Kind::Var: + case Decl::Kind::Var: { + // Bail on any VarDecl that either has no named symbol. + if (!ND->getIdentifier()) + return true; + const auto *VD = cast<VarDecl>(ND); + // Bail on any VarDecl that is a dependent or templated type. + if (VD->isTemplated() || VD->getType()->isDependentType()) + return true; + if (WriteNamedDecl(ND, Symbols, RDO)) + return true; + break; + } case Decl::Kind::ParmVar: case Decl::Kind::CXXMethod: case Decl::Kind::CXXConstructor: @@ -251,14 +284,16 @@ public: for (const NamedDecl *ND : v.NamedDecls) HandleNamedDecl(ND, Symbols, FromTU); - auto writeIfsV1 = - [this](const llvm::Triple &T, const MangledSymbols &Symbols, - const ASTContext &context, StringRef Format, - raw_ostream &OS) -> void { + auto writeIfsV1 = [this](const llvm::Triple &T, + const MangledSymbols &Symbols, + const ASTContext &context, StringRef Format, + raw_ostream &OS) -> void { OS << "--- !" << Format << "\n"; OS << "IfsVersion: 1.0\n"; OS << "Triple: " << T.str() << "\n"; - OS << "ObjectFileFormat: " << "ELF" << "\n"; // TODO: For now, just ELF. + OS << "ObjectFileFormat: " + << "ELF" + << "\n"; // TODO: For now, just ELF. OS << "Symbols:\n"; for (const auto &E : Symbols) { const MangledSymbol &Symbol = E.second; diff --git a/clang/lib/Frontend/MultiplexConsumer.cpp b/clang/lib/Frontend/MultiplexConsumer.cpp index 04e896296c95..5abbb3a235b4 100644 --- a/clang/lib/Frontend/MultiplexConsumer.cpp +++ b/clang/lib/Frontend/MultiplexConsumer.cpp @@ -322,6 +322,11 @@ void MultiplexConsumer::CompleteTentativeDefinition(VarDecl *D) { Consumer->CompleteTentativeDefinition(D); } +void MultiplexConsumer::CompleteExternalDeclaration(VarDecl *D) { + for (auto &Consumer : Consumers) + Consumer->CompleteExternalDeclaration(D); +} + void MultiplexConsumer::AssignInheritanceModel(CXXRecordDecl *RD) { for (auto &Consumer : Consumers) Consumer->AssignInheritanceModel(RD); diff --git a/clang/lib/Frontend/PrecompiledPreamble.cpp b/clang/lib/Frontend/PrecompiledPreamble.cpp index ced32c670288..0e5a8e504dc5 100644 --- a/clang/lib/Frontend/PrecompiledPreamble.cpp +++ b/clang/lib/Frontend/PrecompiledPreamble.cpp @@ -535,21 +535,15 @@ PrecompiledPreamble::TempPCHFile::CreateNewPreamblePCHFile() { // FIXME: This is a hack so that we can override the preamble file during // crash-recovery testing, which is the only case where the preamble files // are not necessarily cleaned up. - const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"); - if (TmpFile) - return TempPCHFile::createFromCustomPath(TmpFile); - return TempPCHFile::createInSystemTempDir("preamble", "pch"); -} + if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE")) + return TempPCHFile(TmpFile); -llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> -PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix, - StringRef Suffix) { llvm::SmallString<64> File; // Using a version of createTemporaryFile with a file descriptor guarantees // that we would never get a race condition in a multi-threaded setting // (i.e., multiple threads getting the same temporary path). int FD; - auto EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, FD, File); + auto EC = llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File); if (EC) return EC; // We only needed to make sure the file exists, close the file right away. @@ -557,11 +551,6 @@ PrecompiledPreamble::TempPCHFile::createInSystemTempDir(const Twine &Prefix, return TempPCHFile(std::move(File).str()); } -llvm::ErrorOr<PrecompiledPreamble::TempPCHFile> -PrecompiledPreamble::TempPCHFile::createFromCustomPath(const Twine &Path) { - return TempPCHFile(Path.str()); -} - PrecompiledPreamble::TempPCHFile::TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) { TemporaryFiles::getInstance().addFile(*this->FilePath); diff --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp b/clang/lib/Frontend/Rewrite/FrontendActions.cpp index 549b86edebcd..aaffbde3309b 100644 --- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp +++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp @@ -21,7 +21,7 @@ #include "clang/Rewrite/Frontend/FixItRewriter.h" #include "clang/Rewrite/Frontend/Rewriters.h" #include "clang/Serialization/ASTReader.h" -#include "clang/Serialization/Module.h" +#include "clang/Serialization/ModuleFile.h" #include "clang/Serialization/ModuleManager.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/CrashRecoveryContext.h" @@ -220,7 +220,7 @@ public: return; serialization::ModuleFile *MF = - CI.getModuleManager()->getModuleManager().lookup(*File); + CI.getASTReader()->getModuleManager().lookup(*File); assert(MF && "missing module file for loaded module?"); // Not interested in PCH / preambles. @@ -293,8 +293,8 @@ bool RewriteIncludesAction::BeginSourceFileAction(CompilerInstance &CI) { // If we're rewriting imports, set up a listener to track when we import // module files. if (CI.getPreprocessorOutputOpts().RewriteImports) { - CI.createModuleManager(); - CI.getModuleManager()->addListener( + CI.createASTReader(); + CI.getASTReader()->addListener( std::make_unique<RewriteImportsListener>(CI, OutputStream)); } diff --git a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp index 45495065ada6..831f95e8c6be 100644 --- a/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp +++ b/clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp @@ -908,9 +908,9 @@ RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) { static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP, ObjCPropertyDecl *PD, bool getter) { - return getter ? !IMP->getInstanceMethod(PD->getGetterName()) - : !IMP->getInstanceMethod(PD->getSetterName()); - + auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName() + : PD->getSetterName()); + return !OMD || OMD->isSynthesizedAccessorStub(); } void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, @@ -952,7 +952,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, "id objc_getProperty(id, SEL, long, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), - PD->getGetterMethodDecl(), Getr); + PID->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. // See objc-act.c:objc_synthesize_new_getter() for details. @@ -960,7 +960,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) Getr += "typedef "; const FunctionType *FPRetType = nullptr; - RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr, + RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr, FPRetType); Getr += " _TYPE"; if (FPRetType) { @@ -1012,7 +1012,7 @@ void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, } RewriteObjCMethodDecl(OID->getContainingInterface(), - PD->getSetterMethodDecl(), Setr); + PID->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. // See objc-act.c:objc_synthesize_new_setter() for details. @@ -1346,6 +1346,8 @@ void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { InsertText(CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { + if (!OMD->getBody()) + continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); @@ -1357,6 +1359,8 @@ void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) { } for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { + if (!OMD->getBody()) + continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); @@ -7031,12 +7035,12 @@ void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl, ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; - if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) + if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/)) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; - if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) + if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/)) InstanceMethods.push_back(Setter); } @@ -7281,11 +7285,11 @@ void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl, ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; - if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) + if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; - if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) + if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } diff --git a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp index 6a22da178fbc..0cb7592b9982 100644 --- a/clang/lib/Frontend/Rewrite/RewriteObjC.cpp +++ b/clang/lib/Frontend/Rewrite/RewriteObjC.cpp @@ -786,8 +786,9 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, if (!OID) return; + unsigned Attributes = PD->getPropertyAttributes(); - if (!PD->getGetterMethodDecl()->isDefined()) { + if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) { bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) && (Attributes & (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_copy)); @@ -799,7 +800,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, "id objc_getProperty(id, SEL, long, bool);\n"; } RewriteObjCMethodDecl(OID->getContainingInterface(), - PD->getGetterMethodDecl(), Getr); + PID->getGetterMethodDecl(), Getr); Getr += "{ "; // Synthesize an explicit cast to gain access to the ivar. // See objc-act.c:objc_synthesize_new_getter() for details. @@ -807,7 +808,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1) Getr += "typedef "; const FunctionType *FPRetType = nullptr; - RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr, + RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr, FPRetType); Getr += " _TYPE"; if (FPRetType) { @@ -843,7 +844,8 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, InsertText(onePastSemiLoc, Getr); } - if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined()) + if (PD->isReadOnly() || !PID->getSetterMethodDecl() || + PID->getSetterMethodDecl()->isDefined()) return; // Generate the 'setter' function. @@ -858,7 +860,7 @@ void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID, } RewriteObjCMethodDecl(OID->getContainingInterface(), - PD->getSetterMethodDecl(), Setr); + PID->getSetterMethodDecl(), Setr); Setr += "{ "; // Synthesize an explicit cast to initialize the ivar. // See objc-act.c:objc_synthesize_new_setter() for details. @@ -1168,6 +1170,8 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { InsertText(IMD ? IMD->getBeginLoc() : CID->getBeginLoc(), "// "); for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) { + if (!OMD->getBody()) + continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); @@ -1179,6 +1183,8 @@ void RewriteObjC::RewriteImplementationDecl(Decl *OID) { } for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) { + if (!OMD->getBody()) + continue; std::string ResultStr; RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr); SourceLocation LocStart = OMD->getBeginLoc(); @@ -5355,12 +5361,12 @@ void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDe ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; - if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) + if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) if (!Getter->isDefined()) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; - if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) + if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) if (!Setter->isDefined()) InstanceMethods.push_back(Setter); } @@ -5633,11 +5639,11 @@ void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *ID ObjCPropertyDecl *PD = Prop->getPropertyDecl(); if (!PD) continue; - if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl()) + if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl()) InstanceMethods.push_back(Getter); if (PD->isReadOnly()) continue; - if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl()) + if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl()) InstanceMethods.push_back(Setter); } RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(), diff --git a/clang/lib/Frontend/TextDiagnostic.cpp b/clang/lib/Frontend/TextDiagnostic.cpp index 7bb6c5b74d5f..78acaaf9f96e 100644 --- a/clang/lib/Frontend/TextDiagnostic.cpp +++ b/clang/lib/Frontend/TextDiagnostic.cpp @@ -761,11 +761,12 @@ void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS, } void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) { - SmallVector<char, 128> AbsoluteFilename; +#ifdef _WIN32 + SmallString<4096> TmpFilename; +#endif if (DiagOpts->AbsolutePath) { - auto Dir = SM.getFileManager().getDirectory( - llvm::sys::path::parent_path(Filename)); - if (Dir) { + auto File = SM.getFileManager().getFile(Filename); + if (File) { // We want to print a simplified absolute path, i. e. without "dots". // // The hardest part here are the paths like "<part1>/<link>/../<part2>". @@ -781,16 +782,14 @@ void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) { // on Windows we can just use llvm::sys::path::remove_dots(), because, // on that system, both aforementioned paths point to the same place. #ifdef _WIN32 - SmallString<4096> DirName = (*Dir)->getName(); - llvm::sys::fs::make_absolute(DirName); - llvm::sys::path::native(DirName); - llvm::sys::path::remove_dots(DirName, /* remove_dot_dot */ true); + TmpFilename = (*File)->getName(); + llvm::sys::fs::make_absolute(TmpFilename); + llvm::sys::path::native(TmpFilename); + llvm::sys::path::remove_dots(TmpFilename, /* remove_dot_dot */ true); + Filename = StringRef(TmpFilename.data(), TmpFilename.size()); #else - StringRef DirName = SM.getFileManager().getCanonicalName(*Dir); + Filename = SM.getFileManager().getCanonicalName(*File); #endif - llvm::sys::path::append(AbsoluteFilename, DirName, - llvm::sys::path::filename(Filename)); - Filename = StringRef(AbsoluteFilename.data(), AbsoluteFilename.size()); } } |