[clang] Adopt new FileManager error-returning APIs

Update the callers of FileManager::getFile and FileManager::getDirectory to handle the new llvm::ErrorOr-returning methods.

Signed-off-by: Harlan Haskins <harlan@apple.com>
llvm-svn: 367616
This commit is contained in:
Harlan Haskins 2019-08-01 21:31:56 +00:00
parent 461f0722dd
commit 8d323d1506
35 changed files with 298 additions and 215 deletions

View File

@ -78,26 +78,26 @@ bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
Diag);
StringRef toFilename = lines[idx+2];
const FileEntry *origFE = FileMgr->getFile(fromFilename);
llvm::ErrorOr<const FileEntry *> origFE = FileMgr->getFile(fromFilename);
if (!origFE) {
if (ignoreIfFilesChanged)
continue;
return report("File does not exist: " + fromFilename, Diag);
}
const FileEntry *newFE = FileMgr->getFile(toFilename);
llvm::ErrorOr<const FileEntry *> newFE = FileMgr->getFile(toFilename);
if (!newFE) {
if (ignoreIfFilesChanged)
continue;
return report("File does not exist: " + toFilename, Diag);
}
if ((uint64_t)origFE->getModificationTime() != timeModified) {
if ((uint64_t)(*origFE)->getModificationTime() != timeModified) {
if (ignoreIfFilesChanged)
continue;
return report("File was modified: " + fromFilename, Diag);
}
pairs.push_back(std::make_pair(origFE, newFE));
pairs.push_back(std::make_pair(*origFE, *newFE));
}
for (unsigned i = 0, e = pairs.size(); i != e; ++i)
@ -152,9 +152,11 @@ bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) {
newOut.write(mem->getBufferStart(), mem->getBufferSize());
newOut.close();
const FileEntry *newE = FileMgr->getFile(tempPath);
remap(origFE, newE);
infoOut << newE->getName() << '\n';
auto newE = FileMgr->getFile(tempPath);
if (newE) {
remap(origFE, *newE);
infoOut << (*newE)->getName() << '\n';
}
}
}
@ -224,7 +226,9 @@ void FileRemapper::remap(const FileEntry *file, const FileEntry *newfile) {
}
const FileEntry *FileRemapper::getOriginalFile(StringRef filePath) {
const FileEntry *file = FileMgr->getFile(filePath);
const FileEntry *file = nullptr;
if (auto fileOrErr = FileMgr->getFile(filePath))
file = *fileOrErr;
// If we are updating a file that overridden an original file,
// actually update the original file.
llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator

View File

@ -2141,10 +2141,11 @@ private:
StringRef Val = ValueString->getValue(ValueStorage);
if (Key == "file") {
const FileEntry *FE = FileMgr.getFile(Val);
if (!FE)
auto FE = FileMgr.getFile(Val);
if (FE)
Entry.File = *FE;
else
Ignore = true;
Entry.File = FE;
} else if (Key == "offset") {
if (Val.getAsInteger(10, Entry.Offset))
Ignore = true;

View File

@ -8442,13 +8442,13 @@ Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
// disk again
// FIXME: We definitely want to re-use the existing MemoryBuffer, rather
// than mmap the files several times.
const FileEntry *Entry =
auto Entry =
ToFileManager.getFile(Cache->OrigEntry->getName());
// FIXME: The filename may be a virtual name that does probably not
// point to a valid file and we get no Entry here. In this case try with
// the memory buffer below.
if (Entry)
ToID = ToSM.createFileID(Entry, *ToIncludeLoc,
ToID = ToSM.createFileID(*Entry, *ToIncludeLoc,
FromSLoc.getFile().getFileCharacteristic());
}
}

View File

@ -246,8 +246,8 @@ ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
if (!TopHeaderNames.empty()) {
for (std::vector<std::string>::iterator
I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
if (const FileEntry *FE = FileMgr.getFile(*I))
TopHeaders.insert(FE);
if (auto FE = FileMgr.getFile(*I))
TopHeaders.insert(*FE);
}
TopHeaderNames.clear();
}

View File

@ -2263,7 +2263,7 @@ SourceManagerForFile::SourceManagerForFile(StringRef FileName,
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
FileID ID = SourceMgr->createFileID(*FileMgr->getFile(FileName),
SourceLocation(), clang::SrcMgr::C_User);
assert(ID.isValid());
SourceMgr->setMainFileID(ID);

View File

@ -561,13 +561,13 @@ const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
if (D.isLocationAvailable()) {
D.getLocation(Filename, Line, Column);
if (Line > 0) {
const FileEntry *FE = FileMgr.getFile(Filename);
auto FE = FileMgr.getFile(Filename);
if (!FE)
FE = FileMgr.getFile(D.getAbsolutePath());
if (FE) {
// If -gcolumn-info was not used, Column will be 0. This upsets the
// source manager, so pass 1 if Column is not set.
DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
}
}
BadDebugInfo = DILoc.isInvalid();

View File

@ -2368,13 +2368,13 @@ void ASTUnit::TranslateStoredDiagnostics(
// Rebuild the StoredDiagnostic.
if (SD.Filename.empty())
continue;
const FileEntry *FE = FileMgr.getFile(SD.Filename);
auto FE = FileMgr.getFile(SD.Filename);
if (!FE)
continue;
SourceLocation FileLoc;
auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
if (ItFileID == PreambleSrcLocCache.end()) {
FileID FID = SrcMgr.translateFile(FE);
FileID FID = SrcMgr.translateFile(*FE);
FileLoc = SrcMgr.getLocForStartOfFile(FID);
PreambleSrcLocCache[SD.Filename] = FileLoc;
} else {

View File

@ -161,7 +161,7 @@ static void collectIncludePCH(CompilerInstance &CI,
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
FileManager &FileMgr = CI.getFileManager();
const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
auto PCHDir = FileMgr.getDirectory(PCHInclude);
if (!PCHDir) {
MDC->addFile(PCHInclude);
return;
@ -169,7 +169,7 @@ static void collectIncludePCH(CompilerInstance &CI,
std::error_code EC;
SmallString<128> DirNative;
llvm::sys::path::native(PCHDir->getName(), DirNative);
llvm::sys::path::native((*PCHDir)->getName(), DirNative);
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
SimpleASTReaderListener Validator(CI.getPreprocessor());
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
@ -342,7 +342,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Remap files in the source manager (with other files).
for (const auto &RF : InitOpts.RemappedFiles) {
// Find the file that we're mapping to.
const FileEntry *ToFile = FileMgr.getFile(RF.second);
auto ToFile = FileMgr.getFile(RF.second);
if (!ToFile) {
Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
continue;
@ -350,7 +350,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Create the file entry for the file that we're mapping from.
const FileEntry *FromFile =
FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
continue;
@ -358,7 +358,7 @@ static void InitializeFileRemapping(DiagnosticsEngine &Diags,
// Override the contents of the "from" file with the contents of
// the "to" file.
SourceMgr.overrideFileContents(FromFile, ToFile);
SourceMgr.overrideFileContents(FromFile, *ToFile);
}
SourceMgr.setOverridenFilesKeepOriginalName(
@ -558,7 +558,7 @@ static bool EnableCodeCompletion(Preprocessor &PP,
unsigned Column) {
// Tell the source manager to chop off the given file at a specific
// line and column.
const FileEntry *Entry = PP.getFileManager().getFile(Filename);
auto Entry = PP.getFileManager().getFile(Filename);
if (!Entry) {
PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
<< Filename;
@ -566,7 +566,7 @@ static bool EnableCodeCompletion(Preprocessor &PP,
}
// Truncate the named file at the given line/column.
PP.SetCodeCompletionPoint(Entry, Line, Column);
PP.SetCodeCompletionPoint(*Entry, Line, Column);
return false;
}
@ -830,11 +830,12 @@ bool CompilerInstance::InitializeSourceManager(
// Figure out where to get and map in the main file.
if (InputFile != "-") {
const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
if (!File) {
auto FileOrErr = FileMgr.getFile(InputFile, /*OpenFile=*/true);
if (!FileOrErr) {
Diags.Report(diag::err_fe_error_reading) << InputFile;
return false;
}
auto File = *FileOrErr;
// The natural SourceManager infrastructure can't currently handle named
// pipes, but we would at least like to accept them for the main
@ -1154,7 +1155,9 @@ static const FileEntry *getPublicModuleMap(const FileEntry *File,
llvm::sys::path::append(PublicFilename, "module.modulemap");
else
return nullptr;
return FileMgr.getFile(PublicFilename);
if (auto FE = FileMgr.getFile(PublicFilename))
return *FE;
return nullptr;
}
/// Compile a module file for the given module, using the options
@ -1718,8 +1721,9 @@ CompilerInstance::loadModule(SourceLocation ImportLoc,
if (Source != ModuleCache && !Module) {
Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
!IsInclusionDirective);
auto ModuleFile = FileMgr->getFile(ModuleFileName);
if (!Module || !Module->getASTFile() ||
FileMgr->getFile(ModuleFileName) != 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)

View File

@ -370,7 +370,7 @@ static std::error_code collectModuleHeaderIncludes(
.Default(false))
continue;
const FileEntry *Header = FileMgr.getFile(Dir->path());
auto Header = FileMgr.getFile(Dir->path());
// FIXME: This shouldn't happen unless there is a file system race. Is
// that worth diagnosing?
if (!Header)
@ -378,7 +378,7 @@ static std::error_code collectModuleHeaderIncludes(
// If this header is marked 'unavailable' in this module, don't include
// it.
if (ModMap.isHeaderUnavailableInModule(Header, Module))
if (ModMap.isHeaderUnavailableInModule(*Header, Module))
continue;
// Compute the relative path from the directory to this file.
@ -392,7 +392,7 @@ static std::error_code collectModuleHeaderIncludes(
llvm::sys::path::append(RelativeHeader, *It);
// Include this header as part of the umbrella directory.
Module->addTopHeader(Header);
Module->addTopHeader(*Header);
addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
}
@ -481,7 +481,7 @@ static Module *prepareToBuildModule(CompilerInstance &CI,
// the module map, rather than adding it after the fact.
StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
if (!OriginalModuleMapName.empty()) {
auto *OriginalModuleMap =
auto OriginalModuleMap =
CI.getFileManager().getFile(OriginalModuleMapName,
/*openFile*/ true);
if (!OriginalModuleMap) {
@ -489,11 +489,11 @@ static Module *prepareToBuildModule(CompilerInstance &CI,
<< OriginalModuleMapName;
return nullptr;
}
if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
CI.getSourceManager().getMainFileID())) {
M->IsInferred = true;
CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
.setInferredModuleAllowedBy(M, OriginalModuleMap);
.setInferredModuleAllowedBy(M, *OriginalModuleMap);
}
}
@ -674,8 +674,8 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
// Set up embedding for any specified files. Do this before we load any
// source files, including the primary module map for the compilation.
for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
CI.getSourceManager().setFileIsTransient(FE);
if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
CI.getSourceManager().setFileIsTransient(*FE);
else
CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
}
@ -709,10 +709,10 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
std::error_code EC;
SmallString<128> DirNative;
llvm::sys::path::native(PCHDir->getName(), DirNative);
llvm::sys::path::native((*PCHDir)->getName(), DirNative);
bool Found = false;
llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
@ -792,9 +792,9 @@ bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
// If we were asked to load any module map files, do so now.
for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
if (auto *File = CI.getFileManager().getFile(Filename))
if (auto File = CI.getFileManager().getFile(Filename))
CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
File, /*IsSystem*/false);
*File, /*IsSystem*/false);
else
CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
}

View File

@ -148,17 +148,17 @@ bool InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
}
// If the directory exists, add it.
if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
if (auto DE = FM.getDirectory(MappedPathStr)) {
IncludePath.push_back(
std::make_pair(Group, DirectoryLookup(DE, Type, isFramework)));
std::make_pair(Group, DirectoryLookup(*DE, Type, isFramework)));
return true;
}
// Check to see if this is an apple-style headermap (which are not allowed to
// be frameworks).
if (!isFramework) {
if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
if (auto FE = FM.getFile(MappedPathStr)) {
if (const HeaderMap *HM = Headers.CreateHeaderMap(*FE)) {
// It is a headermap, add it to the search path.
IncludePath.push_back(
std::make_pair(Group,
@ -636,8 +636,8 @@ void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
// Set up the builtin include directory in the module map.
SmallString<128> P = StringRef(HSOpts.ResourceDir);
llvm::sys::path::append(P, "include");
if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P))
HS.getModuleMap().setBuiltinIncludeDir(Dir);
if (auto Dir = HS.getFileMgr().getDirectory(P))
HS.getModuleMap().setBuiltinIncludeDir(*Dir);
}
Init.Realize(Lang);

View File

@ -369,9 +369,11 @@ llvm::ErrorOr<PrecompiledPreamble> PrecompiledPreamble::Build(
SourceManager &SourceMgr = Clang->getSourceManager();
for (auto &Filename : PreambleDepCollector->getDependencies()) {
const FileEntry *File = Clang->getFileManager().getFile(Filename);
if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
auto FileOrErr = Clang->getFileManager().getFile(Filename);
if (!FileOrErr ||
*FileOrErr == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
continue;
auto File = *FileOrErr;
if (time_t ModTime = File->getModificationTime()) {
FilesInPreamble[File->getName()] =
PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),

View File

@ -211,16 +211,16 @@ public:
void visitModuleFile(StringRef Filename,
serialization::ModuleKind Kind) override {
auto *File = CI.getFileManager().getFile(Filename);
auto File = CI.getFileManager().getFile(Filename);
assert(File && "missing file for loaded module?");
// Only rewrite each module file once.
if (!Rewritten.insert(File).second)
if (!Rewritten.insert(*File).second)
return;
serialization::ModuleFile *MF =
CI.getModuleManager()->getModuleManager().lookup(File);
assert(File && "missing module file for loaded module?");
CI.getModuleManager()->getModuleManager().lookup(*File);
assert(MF && "missing module file for loaded module?");
// Not interested in PCH / preambles.
if (!MF->isModule())

View File

@ -762,7 +762,7 @@ void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
SmallVector<char, 128> AbsoluteFilename;
if (DiagOpts->AbsolutePath) {
const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
auto Dir = SM.getFileManager().getDirectory(
llvm::sys::path::parent_path(Filename));
if (Dir) {
// We want to print a simplified absolute path, i. e. without "dots".
@ -780,12 +780,12 @@ 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();
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);
#else
StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
StringRef DirName = SM.getFileManager().getCanonicalName(*Dir);
#endif
llvm::sys::path::append(AbsoluteFilename, DirName,
llvm::sys::path::filename(Filename));

View File

@ -204,7 +204,9 @@ const FileEntry *HeaderMap::LookupFile(
if (Dest.empty())
return nullptr;
return FM.getFile(Dest);
if (auto File = FM.getFile(Dest))
return *File;
return nullptr;
}
StringRef HeaderMapImpl::lookupFilename(StringRef Filename,

View File

@ -175,10 +175,10 @@ std::string HeaderSearch::getCachedModuleFileName(StringRef ModuleName,
std::string Parent = llvm::sys::path::parent_path(ModuleMapPath);
if (Parent.empty())
Parent = ".";
auto *Dir = FileMgr.getDirectory(Parent);
auto Dir = FileMgr.getDirectory(Parent);
if (!Dir)
return {};
auto DirName = FileMgr.getCanonicalName(Dir);
auto DirName = FileMgr.getCanonicalName(*Dir);
auto FileName = llvm::sys::path::filename(ModuleMapPath);
llvm::hash_code Hash =
@ -230,11 +230,10 @@ Module *HeaderSearch::lookupModule(StringRef ModuleName, StringRef SearchName,
SmallString<128> FrameworkDirName;
FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
if (const DirectoryEntry *FrameworkDir
= FileMgr.getDirectory(FrameworkDirName)) {
if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
bool IsSystem
= SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
if (Module)
break;
}
@ -310,17 +309,17 @@ const FileEntry *HeaderSearch::getFileAndSuggestModule(
ModuleMap::KnownHeader *SuggestedModule) {
// If we have a module map that might map this header, load it and
// check whether we'll have a suggestion for a module.
const FileEntry *File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
auto File = getFileMgr().getFile(FileName, /*OpenFile=*/true);
if (!File)
return nullptr;
// If there is a module that corresponds to this header, suggest it.
if (!findUsableModuleForHeader(File, Dir ? Dir : File->getDir(),
if (!findUsableModuleForHeader(*File, Dir ? Dir : (*File)->getDir(),
RequestingModule, SuggestedModule,
IsSystemHeaderDir))
return nullptr;
return File;
return *File;
}
/// LookupFile - Lookup the specified file in this search path, returning it
@ -383,8 +382,10 @@ const FileEntry *DirectoryLookup::LookupFile(
Filename = StringRef(MappedName.begin(), MappedName.size());
HasBeenMapped = true;
Result = HM->LookupFile(Filename, HS.getFileMgr());
} else if (auto Res = HS.getFileMgr().getFile(Dest)) {
Result = *Res;
} else {
Result = HS.getFileMgr().getFile(Dest);
Result = nullptr;
}
if (Result) {
@ -427,8 +428,12 @@ getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
//
// Similar issues occur when a top-level framework has moved into an
// embedded framework.
const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
DirName = FileMgr.getCanonicalName(TopFrameworkDir);
const DirectoryEntry *TopFrameworkDir = nullptr;
if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
TopFrameworkDir = *TopFrameworkDirOrErr;
if (TopFrameworkDir)
DirName = FileMgr.getCanonicalName(TopFrameworkDir);
do {
// Get the parent directory name.
DirName = llvm::sys::path::parent_path(DirName);
@ -436,7 +441,7 @@ getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
break;
// Determine whether this directory exists.
const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
auto Dir = FileMgr.getDirectory(DirName);
if (!Dir)
break;
@ -444,7 +449,7 @@ getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
// framework.
if (llvm::sys::path::extension(DirName) == ".framework") {
SubmodulePath.push_back(llvm::sys::path::stem(DirName));
TopFrameworkDir = Dir;
TopFrameworkDir = *Dir;
}
} while (true);
@ -499,7 +504,7 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(
HS.IncrementFrameworkLookupCount();
// If the framework dir doesn't exist, we fail.
const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
auto Dir = FileMgr.getDirectory(FrameworkName);
if (!Dir) return nullptr;
// Otherwise, if it does, remember that this is the right direntry for this
@ -538,8 +543,11 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(
}
FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
const FileEntry *FE = FileMgr.getFile(FrameworkName,
/*OpenFile=*/!SuggestedModule);
const FileEntry *FE = nullptr;
if (auto File = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule))
FE = *File;
if (!FE) {
// Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
const char *Private = "Private";
@ -549,7 +557,9 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(
SearchPath->insert(SearchPath->begin()+OrigSize, Private,
Private+strlen(Private));
FE = FileMgr.getFile(FrameworkName, /*OpenFile=*/!SuggestedModule);
if (auto File = FileMgr.getFile(FrameworkName,
/*OpenFile=*/!SuggestedModule))
FE = *File;
}
// If we found the header and are allowed to suggest a module, do so now.
@ -559,7 +569,7 @@ const FileEntry *DirectoryLookup::DoFrameworkLookup(
bool FoundFramework = false;
do {
// Determine whether this directory exists.
const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
auto Dir = FileMgr.getDirectory(FrameworkPath);
if (!Dir)
break;
@ -1022,12 +1032,12 @@ LookupSubframeworkHeader(StringRef Filename,
++NumSubFrameworkLookups;
// If the framework dir doesn't exist, we fail.
const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
auto Dir = FileMgr.getDirectory(FrameworkName);
if (!Dir) return nullptr;
// Otherwise, if it does, remember that this is the right direntry for this
// framework.
CacheLookup.second.Directory = Dir;
CacheLookup.second.Directory = *Dir;
}
const FileEntry *FE = nullptr;
@ -1047,7 +1057,10 @@ LookupSubframeworkHeader(StringRef Filename,
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))) {
if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
FE = *File;
if (!FE) {
// Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
HeadersFilename = FrameworkName;
HeadersFilename += "PrivateHeaders/";
@ -1058,7 +1071,10 @@ LookupSubframeworkHeader(StringRef Filename,
}
HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
if (!(FE = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true)))
if (auto File = FileMgr.getFile(HeadersFilename, /*OpenFile=*/true))
FE = *File;
if (!FE)
return nullptr;
}
@ -1306,13 +1322,13 @@ bool HeaderSearch::hasModuleMap(StringRef FileName,
return false;
// Determine whether this directory exists.
const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
auto Dir = FileMgr.getDirectory(DirName);
if (!Dir)
return false;
// Try to load the module map file in this directory.
switch (loadModuleMapFile(Dir, IsSystem,
llvm::sys::path::extension(Dir->getName()) ==
switch (loadModuleMapFile(*Dir, IsSystem,
llvm::sys::path::extension((*Dir)->getName()) ==
".framework")) {
case LMM_NewlyLoaded:
case LMM_AlreadyLoaded:
@ -1328,12 +1344,12 @@ bool HeaderSearch::hasModuleMap(StringRef FileName,
}
// If we hit the top of our search, we're done.
if (Dir == Root)
if (*Dir == Root)
return false;
// Keep track of all of the directories we checked, so we can mark them as
// having module maps if we eventually do find a module map.
FixUpDirectories.push_back(Dir);
FixUpDirectories.push_back(*Dir);
} while (true);
}
@ -1417,7 +1433,9 @@ static const FileEntry *getPrivateModuleMap(const FileEntry *File,
llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
else
return nullptr;
return FileMgr.getFile(PrivateFilename);
if (auto File = FileMgr.getFile(PrivateFilename))
return *File;
return nullptr;
}
bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
@ -1426,15 +1444,18 @@ bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
// Find the directory for the module. For frameworks, that may require going
// up from the 'Modules' directory.
const DirectoryEntry *Dir = nullptr;
if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
Dir = FileMgr.getDirectory(".");
else {
if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
if (auto DirOrErr = FileMgr.getDirectory("."))
Dir = *DirOrErr;
} else {
if (!OriginalModuleMapFile.empty()) {
// We're building a preprocessed module map. Find or invent the directory
// that it originally occupied.
Dir = FileMgr.getDirectory(
auto DirOrErr = FileMgr.getDirectory(
llvm::sys::path::parent_path(OriginalModuleMapFile));
if (!Dir) {
if (DirOrErr) {
Dir = *DirOrErr;
} else {
auto *FakeFile = FileMgr.getVirtualFile(OriginalModuleMapFile, 0, 0);
Dir = FakeFile->getDir();
}
@ -1446,7 +1467,8 @@ bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem,
if (llvm::sys::path::filename(DirName) == "Modules") {
DirName = llvm::sys::path::parent_path(DirName);
if (DirName.endswith(".framework"))
Dir = FileMgr.getDirectory(DirName);
if (auto DirOrErr = FileMgr.getDirectory(DirName))
Dir = *DirOrErr;
// FIXME: This assert can fail if there's a race between the above check
// and the removal of the directory.
assert(Dir && "parent must exist");
@ -1503,13 +1525,15 @@ HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
if (IsFramework)
llvm::sys::path::append(ModuleMapFileName, "Modules");
llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
return F;
if (auto F = FileMgr.getFile(ModuleMapFileName))
return *F;
// Continue to allow module.map
ModuleMapFileName = Dir->getName();
llvm::sys::path::append(ModuleMapFileName, "module.map");
return FileMgr.getFile(ModuleMapFileName);
if (auto F = FileMgr.getFile(ModuleMapFileName))
return *F;
return nullptr;
}
Module *HeaderSearch::loadFrameworkModule(StringRef Name,
@ -1540,8 +1564,8 @@ Module *HeaderSearch::loadFrameworkModule(StringRef Name,
HeaderSearch::LoadModuleMapResult
HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
bool IsFramework) {
if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
return loadModuleMapFile(Dir, IsSystem, IsFramework);
if (auto Dir = FileMgr.getDirectory(DirName))
return loadModuleMapFile(*Dir, IsSystem, IsFramework);
return LMM_NoDirectory;
}
@ -1589,13 +1613,13 @@ void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
if (llvm::sys::path::extension(Dir->path()) != ".framework")
continue;
const DirectoryEntry *FrameworkDir =
auto FrameworkDir =
FileMgr.getDirectory(Dir->path());
if (!FrameworkDir)
continue;
// Load this framework module.
loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
loadFrameworkModule(llvm::sys::path::stem(Dir->path()), *FrameworkDir,
IsSystem);
}
continue;

View File

@ -179,12 +179,12 @@ const FileEntry *ModuleMap::findHeader(
SmallString<128> FullPathName(Directory->getName());
auto GetFile = [&](StringRef Filename) -> const FileEntry * {
auto *File = SourceMgr.getFileManager().getFile(Filename);
auto File = SourceMgr.getFileManager().getFile(Filename);
if (!File ||
(Header.Size && File->getSize() != *Header.Size) ||
(Header.ModTime && File->getModificationTime() != *Header.ModTime))
(Header.Size && (*File)->getSize() != *Header.Size) ||
(Header.ModTime && (*File)->getModificationTime() != *Header.ModTime))
return nullptr;
return File;
return *File;
};
auto GetFrameworkFile = [&]() -> const FileEntry * {
@ -300,12 +300,12 @@ bool ModuleMap::resolveAsBuiltinHeader(
// supplied by Clang. Find that builtin header.
SmallString<128> Path;
llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
auto *File = SourceMgr.getFileManager().getFile(Path);
auto File = SourceMgr.getFileManager().getFile(Path);
if (!File)
return false;
auto Role = headerKindToRole(Header.Kind);
Module::Header H = {Path.str(), File};
Module::Header H = {Path.str(), *File};
addHeader(Mod, H, Role);
return true;
}
@ -430,7 +430,10 @@ ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
break;
// Resolve the parent path to a directory entry.
Dir = SourceMgr.getFileManager().getDirectory(DirName);
if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
Dir = *DirEntry;
else
Dir = nullptr;
} while (Dir);
return {};
}
@ -755,7 +758,10 @@ ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header,
break;
// Resolve the parent path to a directory entry.
Dir = SourceMgr.getFileManager().getDirectory(DirName);
if (auto DirEntry = SourceMgr.getFileManager().getDirectory(DirName))
Dir = *DirEntry;
else
Dir = nullptr;
} while (Dir);
return false;
@ -938,24 +944,24 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
// Figure out the parent path.
StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
if (auto ParentDir = FileMgr.getDirectory(Parent)) {
// Check whether we have already looked into the parent directory
// for a module map.
llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
inferred = InferredDirectories.find(ParentDir);
inferred = InferredDirectories.find(*ParentDir);
if (inferred == InferredDirectories.end()) {
// We haven't looked here before. Load a module map, if there is
// one.
bool IsFrameworkDir = Parent.endswith(".framework");
if (const FileEntry *ModMapFile =
HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
inferred = InferredDirectories.find(ParentDir);
HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) {
parseModuleMapFile(ModMapFile, Attrs.IsSystem, *ParentDir);
inferred = InferredDirectories.find(*ParentDir);
}
if (inferred == InferredDirectories.end())
inferred = InferredDirectories.insert(
std::make_pair(ParentDir, InferredDirectory())).first;
std::make_pair(*ParentDir, InferredDirectory())).first;
}
if (inferred->second.InferModules) {
@ -986,7 +992,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
// Look for an umbrella header.
SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
auto UmbrellaHeader = FileMgr.getFile(UmbrellaName);
// FIXME: If there's no umbrella header, we could probably scan the
// framework to load *everything*. But, it's not clear that this is a good
@ -1016,7 +1022,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
//
// The "Headers/" component of the name is implied because this is
// a framework module.
setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
setUmbrellaHeader(Result, *UmbrellaHeader, ModuleName + ".h");
// export *
Result->Exports.push_back(Module::ExportDecl(nullptr, true));
@ -1039,13 +1045,14 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
if (!StringRef(Dir->path()).endswith(".framework"))
continue;
if (const DirectoryEntry *SubframeworkDir =
if (auto SubframeworkDir =
FileMgr.getDirectory(Dir->path())) {
// Note: as an egregious but useful hack, we use the real path here and
// check whether it is actually a subdirectory of the parent directory.
// This will not be the case if the 'subframework' is actually a symlink
// out to a top-level framework.
StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
StringRef SubframeworkDirName =
FileMgr.getCanonicalName(*SubframeworkDir);
bool FoundParent = false;
do {
// Get the parent directory name.
@ -1054,9 +1061,11 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
if (SubframeworkDirName.empty())
break;
if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
FoundParent = true;
break;
if (auto SubDir = FileMgr.getDirectory(SubframeworkDirName)) {
if (*SubDir == FrameworkDir) {
FoundParent = true;
break;
}
}
} while (true);
@ -1064,7 +1073,7 @@ Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
continue;
// FIXME: Do we want to warn about subframeworks without umbrella headers?
inferFrameworkModule(SubframeworkDir, Attrs, Result);
inferFrameworkModule(*SubframeworkDir, Attrs, Result);
}
}
@ -2130,12 +2139,12 @@ void ModuleMapParser::parseExternModuleDecl() {
llvm::sys::path::append(ModuleMapFileName, FileName);
FileNameRef = ModuleMapFileName;
}
if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
if (auto File = SourceMgr.getFileManager().getFile(FileNameRef))
Map.parseModuleMapFile(
File, /*IsSystem=*/false,
*File, /*IsSystem=*/false,
Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
? Directory
: File->getDir(),
: (*File)->getDir(),
FileID(), nullptr, ExternLoc);
}
@ -2384,13 +2393,15 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
// Look for this file.
const DirectoryEntry *Dir = nullptr;
if (llvm::sys::path::is_absolute(DirName))
Dir = SourceMgr.getFileManager().getDirectory(DirName);
else {
if (llvm::sys::path::is_absolute(DirName)) {
if (auto D = SourceMgr.getFileManager().getDirectory(DirName))
Dir = *D;
} else {
SmallString<128> PathName;
PathName = Directory->getName();
llvm::sys::path::append(PathName, DirName);
Dir = SourceMgr.getFileManager().getDirectory(PathName);
if (auto D = SourceMgr.getFileManager().getDirectory(PathName))
Dir = *D;
}
if (!Dir) {
@ -2410,9 +2421,9 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
SourceMgr.getFileManager().getVirtualFileSystem();
for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
I != E && !EC; I.increment(EC)) {
if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
if (auto FE = SourceMgr.getFileManager().getFile(I->path())) {
Module::Header Header = {I->path(), FE};
Module::Header Header = {I->path(), *FE};
Headers.push_back(std::move(Header));
}
}

View File

@ -716,7 +716,7 @@ const FileEntry *Preprocessor::LookupFile(
BuildSystemModule = getCurrentModule()->IsSystem;
} else if ((FileEnt =
SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
} else {
Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
}
@ -1765,9 +1765,9 @@ Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
// Give the clients a chance to recover.
SmallString<128> RecoveryPath;
if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
if (auto DE = FileMgr.getDirectory(RecoveryPath)) {
// Add the recovery path to the list of search paths.
DirectoryLookup DL(DE, SrcMgr::C_User, false);
DirectoryLookup DL(*DE, SrcMgr::C_User, false);
HeaderInfo.AddSearchPath(DL, isAngled);
// Try the lookup again, skipping the cache.

View File

@ -206,8 +206,8 @@ static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
StringRef FilePath = File->getDir()->getName();
StringRef Path = FilePath;
while (!Path.empty()) {
if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
if (CurDir == Dir) {
if (auto CurDir = FM.getDirectory(Path)) {
if (*CurDir == Dir) {
Result = FilePath.substr(Path.size());
llvm::sys::path::append(Result,
llvm::sys::path::filename(File->getName()));
@ -287,12 +287,12 @@ void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
.Default(false))
continue;
if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
if (!getSourceManager().hasFileInfo(Header)) {
if (!ModMap.isHeaderInUnavailableModule(Header)) {
if (auto Header = getFileManager().getFile(Entry->path()))
if (!getSourceManager().hasFileInfo(*Header)) {
if (!ModMap.isHeaderInUnavailableModule(*Header)) {
// Find the relative path that would access this header.
SmallString<128> RelativePath;
computeRelativePath(FileMgr, Dir, Header, RelativePath);
computeRelativePath(FileMgr, Dir, *Header, RelativePath);
Diag(StartLoc, diag::warn_uncovered_module_header)
<< Mod.getFullModuleName() << RelativePath;
}

View File

@ -1822,12 +1822,17 @@ bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
// Determine whether the actual files are equivalent.
FileManager &FileMgr = Reader.getFileManager();
auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
if (!Key.Imported)
return FileMgr.getFile(Key.Filename);
if (!Key.Imported) {
if (auto File = FileMgr.getFile(Key.Filename))
return *File;
return nullptr;
}
std::string Resolved = Key.Filename;
Reader.ResolveImportedPath(M, Resolved);
return FileMgr.getFile(Resolved);
if (auto File = FileMgr.getFile(Resolved))
return *File;
return nullptr;
};
const FileEntry *FEA = GetFile(a);
@ -1904,7 +1909,7 @@ HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
// FIXME: This is not always the right filename-as-written, but we're not
// going to use this information to rebuild the module, so it doesn't make
// a lot of difference.
Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
}
@ -2266,7 +2271,10 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
bool Transient = FI.Transient;
StringRef Filename = FI.Filename;
const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
const FileEntry *File = nullptr;
if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
File = *FE;
// If we didn't find the file, resolve it relative to the
// original directory from which this AST file was created.
if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
@ -2274,7 +2282,8 @@ InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
std::string Resolved = resolveFileRelativeToOriginalDir(
Filename, F.OriginalDir, F.BaseDirectory);
if (!Resolved.empty())
File = FileMgr.getFile(Resolved);
if (auto FE = FileMgr.getFile(Resolved))
File = *FE;
}
// For an overridden file, create a virtual file with the stored
@ -2820,9 +2829,8 @@ ASTReader::ReadControlBlock(ModuleFile &F,
// Don't emit module relocation error if we have -fno-validate-pch
if (!PP.getPreprocessorOpts().DisablePCHValidation &&
F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
const DirectoryEntry *BuildDir =
PP.getFileManager().getDirectory(Blob);
if (!BuildDir || BuildDir != M->Directory) {
auto BuildDir = PP.getFileManager().getDirectory(Blob);
if (!BuildDir || *BuildDir != M->Directory) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Diag(diag::err_imported_module_relocated)
<< F.ModuleName << Blob << M->Directory->getName();
@ -3839,8 +3847,8 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
assert(M->Name == F.ModuleName && "found module with different name");
// Check the primary module map file.
const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
if (StoredModMap == nullptr || StoredModMap != ModMap) {
auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
if (!StoredModMap || *StoredModMap != ModMap) {
assert(ModMap && "found module is missing module map file");
assert(ImportedBy && "top-level import should be verified");
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
@ -3854,14 +3862,13 @@ ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
// FIXME: we should use input files rather than storing names.
std::string Filename = ReadPath(F, Record, Idx);
const FileEntry *F =
FileMgr.getFile(Filename, false, false);
if (F == nullptr) {
auto F = FileMgr.getFile(Filename, false, false);
if (!F) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("could not find file '" + Filename +"' referenced by AST file");
return OutOfDate;
}
AdditionalStoredMaps.insert(F);
AdditionalStoredMaps.insert(*F);
}
// Check any additional module map files (e.g. module.private.modulemap)
@ -5459,10 +5466,10 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
case SUBMODULE_UMBRELLA_HEADER: {
std::string Filename = Blob;
ResolveImportedPath(F, Filename);
if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
if (!CurrentModule->getUmbrellaHeader())
ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("mismatched umbrella headers in submodule");
return OutOfDate;
@ -5492,10 +5499,10 @@ ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
case SUBMODULE_UMBRELLA_DIR: {
std::string Dirname = Blob;
ResolveImportedPath(F, Dirname);
if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
if (!CurrentModule->getUmbrellaDir())
ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
Error("mismatched umbrella directories in submodule");
return OutOfDate;
@ -5890,7 +5897,8 @@ PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
const FileEntry *File = nullptr;
if (!FullFileName.empty())
File = PP.getFileManager().getFile(FullFileName);
if (auto FE = PP.getFileManager().getFile(FullFileName))
File = *FE;
// FIXME: Stable encoding
InclusionDirective::InclusionKind Kind

View File

@ -657,7 +657,7 @@ llvm::Error GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
Idx += Length;
// Find the imported module file.
const FileEntry *DependsOnFile
auto DependsOnFile
= FileMgr.getFile(ImportedFile, /*OpenFile=*/false,
/*CacheFailure=*/false);
@ -669,11 +669,11 @@ llvm::Error GlobalModuleIndexBuilder::loadModuleFile(const FileEntry *File) {
// Save the information in ImportedModuleFileInfo so we can verify after
// loading all pcms.
ImportedModuleFiles.insert(std::make_pair(
DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
StoredSignature)));
*DependsOnFile, ImportedModuleFileInfo(StoredSize, StoredModTime,
StoredSignature)));
// Record the dependency.
unsigned DependsOnID = getModuleFileInfo(DependsOnFile).ID;
unsigned DependsOnID = getModuleFileInfo(*DependsOnFile).ID;
getModuleFileInfo(File).Dependencies.push_back(DependsOnID);
}
@ -894,12 +894,12 @@ GlobalModuleIndex::writeIndex(FileManager &FileMgr,
}
// If we can't find the module file, skip it.
const FileEntry *ModuleFile = FileMgr.getFile(D->path());
auto ModuleFile = FileMgr.getFile(D->path());
if (!ModuleFile)
continue;
// Load this module file.
if (llvm::Error Err = Builder.loadModuleFile(ModuleFile))
if (llvm::Error Err = Builder.loadModuleFile(*ModuleFile))
return Err;
}

View File

@ -42,10 +42,10 @@ using namespace clang;
using namespace serialization;
ModuleFile *ModuleManager::lookupByFileName(StringRef Name) const {
const FileEntry *Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
/*CacheFailure=*/false);
auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
/*CacheFailure=*/false);
if (Entry)
return lookup(Entry);
return lookup(*Entry);
return nullptr;
}
@ -68,9 +68,11 @@ ModuleFile *ModuleManager::lookup(const FileEntry *File) const {
std::unique_ptr<llvm::MemoryBuffer>
ModuleManager::lookupBuffer(StringRef Name) {
const FileEntry *Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
/*CacheFailure=*/false);
return std::move(InMemoryBuffers[Entry]);
auto Entry = FileMgr.getFile(Name, /*OpenFile=*/false,
/*CacheFailure=*/false);
if (!Entry)
return nullptr;
return std::move(InMemoryBuffers[*Entry]);
}
static bool checkSignature(ASTFileSignature Signature,
@ -447,9 +449,13 @@ bool ModuleManager::lookupModuleFile(StringRef FileName,
// Open the file immediately to ensure there is no race between stat'ing and
// opening the file.
File = FileMgr.getFile(FileName, /*OpenFile=*/true, /*CacheFailure=*/false);
if (!File)
auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
/*CacheFailure=*/false);
if (!FileOrErr) {
File = nullptr;
return false;
}
File = *FileOrErr;
if ((ExpectedSize && ExpectedSize != File->getSize()) ||
(ExpectedModTime && ExpectedModTime != File->getModificationTime()))

View File

@ -67,11 +67,11 @@ bool Replacement::isApplicable() const {
bool Replacement::apply(Rewriter &Rewrite) const {
SourceManager &SM = Rewrite.getSourceMgr();
const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
auto Entry = SM.getFileManager().getFile(FilePath);
if (!Entry)
return false;
FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
const SourceLocation Start =
SM.getLocForStartOfFile(ID).
getLocWithOffset(ReplacementRange.getOffset());
@ -591,7 +591,8 @@ llvm::Expected<std::string> applyAllReplacements(StringRef Code,
Rewriter Rewrite(SourceMgr, LangOptions());
InMemoryFileSystem->addFile(
"<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(),
FileID ID = SourceMgr.createFileID(*Files.getFile("<stdin>"),
SourceLocation(),
clang::SrcMgr::C_User);
for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
@ -613,10 +614,10 @@ std::map<std::string, Replacements> groupReplacementsByFile(
std::map<std::string, Replacements> Result;
llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
for (const auto &Entry : FileToReplaces) {
const FileEntry *FE = FileMgr.getFile(Entry.first);
auto FE = FileMgr.getFile(Entry.first);
if (!FE)
llvm::errs() << "File path " << Entry.first << " is invalid.\n";
else if (ProcessedFileEntries.insert(FE).second)
else if (ProcessedFileEntries.insert(*FE).second)
Result[Entry.first] = std::move(Entry.second);
}
return Result;

View File

@ -78,7 +78,10 @@ bool formatAndApplyAllReplacements(
const std::string &FilePath = FileAndReplaces.first;
auto &CurReplaces = FileAndReplaces.second;
const FileEntry *Entry = Files.getFile(FilePath);
const FileEntry *Entry = nullptr;
if (auto File = Files.getFile(FilePath))
Entry = *File;
FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
StringRef Code = SM.getBufferData(ID);

View File

@ -117,7 +117,8 @@ static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
SourceManager &Sources, FileManager &Files,
llvm::vfs::InMemoryFileSystem *MemFS) {
MemFS->addFileNoOwn(FileName, 0, Source);
return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
auto File = Files.getFile(FileName);
return Sources.createFileID(File ? *File : nullptr, SourceLocation(),
SrcMgr::C_User);
}

View File

@ -286,12 +286,12 @@ CIAndOrigins BuildIndirect(CIAndOrigins &CI) {
llvm::Error ParseSource(const std::string &Path, CompilerInstance &CI,
ASTConsumer &Consumer) {
SourceManager &SM = CI.getSourceManager();
const FileEntry *FE = CI.getFileManager().getFile(Path);
auto FE = CI.getFileManager().getFile(Path);
if (!FE) {
return llvm::make_error<llvm::StringError>(
llvm::Twine("Couldn't open ", Path), std::error_code());
}
SM.setMainFileID(SM.createFileID(FE, SourceLocation(), SrcMgr::C_User));
SM.setMainFileID(SM.createFileID(*FE, SourceLocation(), SrcMgr::C_User));
ParseAST(CI.getPreprocessor(), &Consumer, CI.getASTContext());
return llvm::Error::success();
}

View File

@ -116,8 +116,8 @@ public:
bool forAllRanges(const SourceManager &SM,
llvm::function_ref<void(SourceRange R)> Callback) override {
const FileEntry *FE = SM.getFileManager().getFile(Range.FileName);
FileID FID = FE ? SM.translateFile(FE) : FileID();
auto FE = SM.getFileManager().getFile(Range.FileName);
FileID FID = FE ? SM.translateFile(*FE) : FileID();
if (!FE || FID.isInvalid()) {
llvm::errs() << "error: -selection=" << Range.FileName
<< ":... : given file is not in the target TU\n";

View File

@ -41,8 +41,8 @@ void TestSelectionRangesInFile::dump(raw_ostream &OS) const {
bool TestSelectionRangesInFile::foreachRange(
const SourceManager &SM,
llvm::function_ref<void(SourceRange)> Callback) const {
const FileEntry *FE = SM.getFileManager().getFile(Filename);
FileID FID = FE ? SM.translateFile(FE) : FileID();
auto FE = SM.getFileManager().getFile(Filename);
FileID FID = FE ? SM.translateFile(*FE) : FileID();
if (!FE || FID.isInvalid()) {
llvm::errs() << "error: -selection=test:" << Filename
<< " : given file is not in the target TU";

View File

@ -222,8 +222,8 @@ int main(int argc, const char **argv) {
Tool.applyAllReplacements(Rewrite);
for (const auto &File : Files) {
const auto *Entry = FileMgr.getFile(File);
const auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
auto Entry = FileMgr.getFile(File);
const auto ID = Sources.getOrCreateFileID(*Entry, SrcMgr::C_User);
Rewrite.getEditBuffer(ID).write(outs());
}
}

View File

@ -4232,7 +4232,10 @@ CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
FileManager &FMgr = CXXUnit->getFileManager();
return const_cast<FileEntry *>(FMgr.getFile(file_name));
auto File = FMgr.getFile(file_name);
if (!File)
return nullptr;
return const_cast<FileEntry *>(*File);
}
const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,

View File

@ -363,8 +363,9 @@ public:
PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
if (!PPOpts.ImplicitPCHInclude.empty()) {
DataConsumer->importedPCH(
CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude));
auto File = CI.getFileManager().getFile(PPOpts.ImplicitPCHInclude);
if (File)
DataConsumer->importedPCH(*File);
}
DataConsumer->setASTContext(CI.getASTContext());
@ -677,9 +678,10 @@ static CXErrorCode clang_indexTranslationUnit_Impl(
if (Unit->getOriginalSourceFileName().empty())
DataConsumer.enteredMainFile(nullptr);
else if (auto MainFile = FileMgr.getFile(Unit->getOriginalSourceFileName()))
DataConsumer.enteredMainFile(*MainFile);
else
DataConsumer.enteredMainFile(
FileMgr.getFile(Unit->getOriginalSourceFileName()));
DataConsumer.enteredMainFile(nullptr);
DataConsumer.setASTContext(Unit->getASTContext());
DataConsumer.startedTranslationUnit();

View File

@ -205,9 +205,9 @@ TEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {
EXPECT_NE(*fileFoo, *fileBar);
}
// getFile() returns NULL if neither a real file nor a virtual file
// getFile() returns an error if neither a real file nor a virtual file
// exists at the given path.
TEST_F(FileManagerTest, getFileReturnsNULLForNonexistentFile) {
TEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {
// Inject a fake foo.cpp into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
@ -219,6 +219,16 @@ TEST_F(FileManagerTest, getFileReturnsNULLForNonexistentFile) {
auto file = manager.getFile("xyz.txt");
ASSERT_FALSE(file);
ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);
statCache->InjectDirectory("MyDirectory", 49);
auto readingDirAsFile = manager.getFile("MyDirectory");
ASSERT_FALSE(readingDirAsFile);
ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);
auto readingFileAsDir = manager.getDirectory("foo.cpp");
ASSERT_FALSE(readingFileAsDir);
ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);
}
// The following tests apply to Unix-like system only.
@ -378,13 +388,13 @@ TEST_F(FileManagerTest, getFileDontOpenRealPath) {
Manager.setStatCache(std::move(statCache));
// Check for real path.
const FileEntry *file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
ASSERT_TRUE(file != nullptr);
ASSERT_TRUE(file->isValid());
auto file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);
}
} // anonymous namespace

View File

@ -39,9 +39,9 @@ protected:
void addSearchDir(llvm::StringRef Dir) {
VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
/*Group=*/None, llvm::sys::fs::file_type::directory_file);
const DirectoryEntry *DE = FileMgr.getDirectory(Dir);
auto DE = FileMgr.getDirectory(Dir);
assert(DE);
auto DL = DirectoryLookup(DE, SrcMgr::C_User, /*isFramework=*/false);
auto DL = DirectoryLookup(*DE, SrcMgr::C_User, /*isFramework=*/false);
Search.AddSearchPath(DL, /*isAngled=*/false);
}

View File

@ -145,8 +145,8 @@ protected:
// Add header's parent path to search path.
StringRef SearchPath = llvm::sys::path::parent_path(HeaderPath);
const DirectoryEntry *DE = FileMgr.getDirectory(SearchPath);
DirectoryLookup DL(DE, SrcMgr::C_User, false);
auto DE = FileMgr.getDirectory(SearchPath);
DirectoryLookup DL(*DE, SrcMgr::C_User, false);
HeaderInfo.AddSearchPath(DL, IsSystemHeader);
}

View File

@ -608,14 +608,15 @@ public:
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
const FileEntry *File = Context.Files.getFile(Path);
assert(File != nullptr);
auto File = Context.Files.getFile(Path);
assert(File);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
return Context.Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
return Context.Sources.createFileID(*File, SourceLocation(),
SrcMgr::C_User);
}
std::string getFileContentFromDisk(llvm::StringRef Name) {

View File

@ -56,9 +56,9 @@ class RewriterTestContext {
llvm::MemoryBuffer::getMemBuffer(Content);
InMemoryFileSystem->addFile(Name, 0, std::move(Source));
const FileEntry *Entry = Files.getFile(Name);
assert(Entry != nullptr);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
auto Entry = Files.getFile(Name);
assert(Entry);
return Sources.createFileID(*Entry, SourceLocation(), SrcMgr::C_User);
}
// FIXME: this code is mostly a duplicate of
@ -73,14 +73,14 @@ class RewriterTestContext {
llvm::raw_fd_ostream OutStream(FD, true);
OutStream << Content;
OutStream.close();
const FileEntry *File = Files.getFile(Path);
assert(File != nullptr);
auto File = Files.getFile(Path);
assert(File);
StringRef Found =
TemporaryFiles.insert(std::make_pair(Name, Path.str())).first->second;
assert(Found == Path);
(void)Found;
return Sources.createFileID(File, SourceLocation(), SrcMgr::C_User);
return Sources.createFileID(*File, SourceLocation(), SrcMgr::C_User);
}
SourceLocation getLocation(FileID ID, unsigned Line, unsigned Column) {