1 //===- ModuleDepCollector.cpp - Callbacks to collect deps -------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h" 10 11 #include "clang/Frontend/CompilerInstance.h" 12 #include "clang/Lex/Preprocessor.h" 13 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h" 14 #include "llvm/Support/StringSaver.h" 15 16 using namespace clang; 17 using namespace tooling; 18 using namespace dependencies; 19 20 static void optimizeHeaderSearchOpts(HeaderSearchOptions &Opts, 21 ASTReader &Reader, 22 const serialization::ModuleFile &MF) { 23 // Only preserve search paths that were used during the dependency scan. 24 std::vector<HeaderSearchOptions::Entry> Entries = Opts.UserEntries; 25 Opts.UserEntries.clear(); 26 for (unsigned I = 0; I < Entries.size(); ++I) 27 if (MF.SearchPathUsage[I]) 28 Opts.UserEntries.push_back(Entries[I]); 29 } 30 31 CompilerInvocation ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths( 32 const ModuleDeps &Deps, 33 llvm::function_ref<void(CompilerInvocation &)> Optimize) const { 34 // Make a deep copy of the original Clang invocation. 35 CompilerInvocation CI(OriginalInvocation); 36 37 CI.getLangOpts()->resetNonModularOptions(); 38 CI.getPreprocessorOpts().resetNonModularOptions(); 39 40 // Remove options incompatible with explicit module build or are likely to 41 // differ between identical modules discovered from different translation 42 // units. 43 CI.getFrontendOpts().Inputs.clear(); 44 CI.getFrontendOpts().OutputFile.clear(); 45 CI.getCodeGenOpts().MainFileName.clear(); 46 CI.getCodeGenOpts().DwarfDebugFlags.clear(); 47 48 CI.getFrontendOpts().ProgramAction = frontend::GenerateModule; 49 CI.getLangOpts()->ModuleName = Deps.ID.ModuleName; 50 CI.getFrontendOpts().IsSystemModule = Deps.IsSystem; 51 52 CI.getLangOpts()->ImplicitModules = false; 53 CI.getHeaderSearchOpts().ImplicitModuleMaps = false; 54 55 // Report the prebuilt modules this module uses. 56 for (const auto &PrebuiltModule : Deps.PrebuiltModuleDeps) 57 CI.getFrontendOpts().ModuleFiles.push_back(PrebuiltModule.PCMFile); 58 59 CI.getFrontendOpts().ModuleMapFiles = Deps.ModuleMapFileDeps; 60 61 Optimize(CI); 62 63 // The original invocation probably didn't have strict context hash enabled. 64 // We will use the context hash of this invocation to distinguish between 65 // multiple incompatible versions of the same module and will use it when 66 // reporting dependencies to the clients. Let's make sure we're using 67 // **strict** context hash in order to prevent accidental sharing of 68 // incompatible modules (e.g. with differences in search paths). 69 CI.getHeaderSearchOpts().ModulesStrictContextHash = true; 70 71 return CI; 72 } 73 74 static std::vector<std::string> 75 serializeCompilerInvocation(const CompilerInvocation &CI) { 76 // Set up string allocator. 77 llvm::BumpPtrAllocator Alloc; 78 llvm::StringSaver Strings(Alloc); 79 auto SA = [&Strings](const Twine &Arg) { return Strings.save(Arg).data(); }; 80 81 // Synthesize full command line from the CompilerInvocation, including "-cc1". 82 SmallVector<const char *, 32> Args{"-cc1"}; 83 CI.generateCC1CommandLine(Args, SA); 84 85 // Convert arguments to the return type. 86 return std::vector<std::string>{Args.begin(), Args.end()}; 87 } 88 89 std::vector<std::string> ModuleDeps::getCanonicalCommandLine( 90 std::function<StringRef(ModuleID)> LookupPCMPath) const { 91 CompilerInvocation CI(BuildInvocation); 92 FrontendOptions &FrontendOpts = CI.getFrontendOpts(); 93 94 InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(), 95 InputKind::Format::ModuleMap); 96 FrontendOpts.Inputs.emplace_back(ClangModuleMapFile, ModuleMapInputKind); 97 FrontendOpts.OutputFile = std::string(LookupPCMPath(ID)); 98 99 for (ModuleID MID : ClangModuleDeps) 100 FrontendOpts.ModuleFiles.emplace_back(LookupPCMPath(MID)); 101 102 return serializeCompilerInvocation(CI); 103 } 104 105 std::vector<std::string> 106 ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const { 107 return serializeCompilerInvocation(BuildInvocation); 108 } 109 110 void ModuleDepCollectorPP::FileChanged(SourceLocation Loc, 111 FileChangeReason Reason, 112 SrcMgr::CharacteristicKind FileType, 113 FileID PrevFID) { 114 if (Reason != PPCallbacks::EnterFile) 115 return; 116 117 // This has to be delayed as the context hash can change at the start of 118 // `CompilerInstance::ExecuteAction`. 119 if (MDC.ContextHash.empty()) { 120 MDC.ContextHash = MDC.ScanInstance.getInvocation().getModuleHash(); 121 MDC.Consumer.handleContextHash(MDC.ContextHash); 122 } 123 124 SourceManager &SM = MDC.ScanInstance.getSourceManager(); 125 126 // Dependency generation really does want to go all the way to the 127 // file entry for a source location to find out what is depended on. 128 // We do not want #line markers to affect dependency generation! 129 if (Optional<StringRef> Filename = 130 SM.getNonBuiltinFilenameForID(SM.getFileID(SM.getExpansionLoc(Loc)))) 131 MDC.FileDeps.push_back( 132 std::string(llvm::sys::path::remove_leading_dotslash(*Filename))); 133 } 134 135 void ModuleDepCollectorPP::InclusionDirective( 136 SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName, 137 bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, 138 StringRef SearchPath, StringRef RelativePath, const Module *Imported, 139 SrcMgr::CharacteristicKind FileType) { 140 if (!File && !Imported) { 141 // This is a non-modular include that HeaderSearch failed to find. Add it 142 // here as `FileChanged` will never see it. 143 MDC.FileDeps.push_back(std::string(FileName)); 144 } 145 handleImport(Imported); 146 } 147 148 void ModuleDepCollectorPP::moduleImport(SourceLocation ImportLoc, 149 ModuleIdPath Path, 150 const Module *Imported) { 151 handleImport(Imported); 152 } 153 154 void ModuleDepCollectorPP::handleImport(const Module *Imported) { 155 if (!Imported) 156 return; 157 158 const Module *TopLevelModule = Imported->getTopLevelModule(); 159 160 if (MDC.isPrebuiltModule(TopLevelModule)) 161 DirectPrebuiltModularDeps.insert(TopLevelModule); 162 else 163 DirectModularDeps.insert(TopLevelModule); 164 } 165 166 void ModuleDepCollectorPP::EndOfMainFile() { 167 FileID MainFileID = MDC.ScanInstance.getSourceManager().getMainFileID(); 168 MDC.MainFile = std::string(MDC.ScanInstance.getSourceManager() 169 .getFileEntryForID(MainFileID) 170 ->getName()); 171 172 if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty()) 173 MDC.FileDeps.push_back( 174 MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude); 175 176 for (const Module *M : DirectModularDeps) { 177 // A top-level module might not be actually imported as a module when 178 // -fmodule-name is used to compile a translation unit that imports this 179 // module. In that case it can be skipped. The appropriate header 180 // dependencies will still be reported as expected. 181 if (!M->getASTFile()) 182 continue; 183 handleTopLevelModule(M); 184 } 185 186 MDC.Consumer.handleDependencyOutputOpts(*MDC.Opts); 187 188 for (auto &&I : MDC.ModularDeps) 189 MDC.Consumer.handleModuleDependency(I.second); 190 191 for (auto &&I : MDC.FileDeps) 192 MDC.Consumer.handleFileDependency(I); 193 194 for (auto &&I : DirectPrebuiltModularDeps) 195 MDC.Consumer.handlePrebuiltModuleDependency(PrebuiltModuleDep{I}); 196 } 197 198 ModuleID ModuleDepCollectorPP::handleTopLevelModule(const Module *M) { 199 assert(M == M->getTopLevelModule() && "Expected top level module!"); 200 201 // If this module has been handled already, just return its ID. 202 auto ModI = MDC.ModularDeps.insert({M, ModuleDeps{}}); 203 if (!ModI.second) 204 return ModI.first->second.ID; 205 206 ModuleDeps &MD = ModI.first->second; 207 208 MD.ID.ModuleName = M->getFullModuleName(); 209 MD.ImportedByMainFile = DirectModularDeps.contains(M); 210 MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName()); 211 MD.IsSystem = M->IsSystem; 212 213 const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor() 214 .getHeaderSearchInfo() 215 .getModuleMap() 216 .getModuleMapFileForUniquing(M); 217 218 if (ModuleMap) { 219 StringRef Path = ModuleMap->tryGetRealPathName(); 220 if (Path.empty()) 221 Path = ModuleMap->getName(); 222 MD.ClangModuleMapFile = std::string(Path); 223 } 224 225 serialization::ModuleFile *MF = 226 MDC.ScanInstance.getASTReader()->getModuleManager().lookup( 227 M->getASTFile()); 228 MDC.ScanInstance.getASTReader()->visitInputFiles( 229 *MF, true, true, [&](const serialization::InputFile &IF, bool isSystem) { 230 // __inferred_module.map is the result of the way in which an implicit 231 // module build handles inferred modules. It adds an overlay VFS with 232 // this file in the proper directory and relies on the rest of Clang to 233 // handle it like normal. With explicitly built modules we don't need 234 // to play VFS tricks, so replace it with the correct module map. 235 if (IF.getFile()->getName().endswith("__inferred_module.map")) { 236 MD.FileDeps.insert(ModuleMap->getName()); 237 return; 238 } 239 MD.FileDeps.insert(IF.getFile()->getName()); 240 }); 241 242 // We usually don't need to list the module map files of our dependencies when 243 // building a module explicitly: their semantics will be deserialized from PCM 244 // files. 245 // 246 // However, some module maps loaded implicitly during the dependency scan can 247 // describe anti-dependencies. That happens when this module, let's call it 248 // M1, is marked as '[no_undeclared_includes]' and tries to access a header 249 // "M2/M2.h" from another module, M2, but doesn't have a 'use M2;' 250 // declaration. The explicit build needs the module map for M2 so that it 251 // knows that textually including "M2/M2.h" is not allowed. 252 // E.g., '__has_include("M2/M2.h")' should return false, but without M2's 253 // module map the explicit build would return true. 254 // 255 // An alternative approach would be to tell the explicit build what its 256 // textual dependencies are, instead of having it re-discover its 257 // anti-dependencies. For example, we could create and use an `-ivfs-overlay` 258 // with `fall-through: false` that explicitly listed the dependencies. 259 // However, that's more complicated to implement and harder to reason about. 260 if (M->NoUndeclaredIncludes) { 261 // We don't have a good way to determine which module map described the 262 // anti-dependency (let alone what's the corresponding top-level module 263 // map). We simply specify all the module maps in the order they were loaded 264 // during the implicit build during scan. 265 // TODO: Resolve this by serializing and only using Module::UndeclaredUses. 266 MDC.ScanInstance.getASTReader()->visitTopLevelModuleMaps( 267 *MF, [&](const FileEntry *FE) { 268 if (FE->getName().endswith("__inferred_module.map")) 269 return; 270 // The top-level modulemap of this module will be the input file. We 271 // don't need to specify it as a module map. 272 if (FE == ModuleMap) 273 return; 274 MD.ModuleMapFileDeps.push_back(FE->getName().str()); 275 }); 276 } 277 278 // Add direct prebuilt module dependencies now, so that we can use them when 279 // creating a CompilerInvocation and computing context hash for this 280 // ModuleDeps instance. 281 llvm::DenseSet<const Module *> SeenModules; 282 addAllSubmodulePrebuiltDeps(M, MD, SeenModules); 283 284 MD.BuildInvocation = MDC.makeInvocationForModuleBuildWithoutPaths( 285 MD, [&](CompilerInvocation &BuildInvocation) { 286 if (MDC.OptimizeArgs) 287 optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(), 288 *MDC.ScanInstance.getASTReader(), *MF); 289 }); 290 MD.ID.ContextHash = MD.BuildInvocation.getModuleHash(); 291 292 llvm::DenseSet<const Module *> AddedModules; 293 addAllSubmoduleDeps(M, MD, AddedModules); 294 295 return MD.ID; 296 } 297 298 void ModuleDepCollectorPP::addAllSubmodulePrebuiltDeps( 299 const Module *M, ModuleDeps &MD, 300 llvm::DenseSet<const Module *> &SeenSubmodules) { 301 addModulePrebuiltDeps(M, MD, SeenSubmodules); 302 303 for (const Module *SubM : M->submodules()) 304 addAllSubmodulePrebuiltDeps(SubM, MD, SeenSubmodules); 305 } 306 307 void ModuleDepCollectorPP::addModulePrebuiltDeps( 308 const Module *M, ModuleDeps &MD, 309 llvm::DenseSet<const Module *> &SeenSubmodules) { 310 for (const Module *Import : M->Imports) 311 if (Import->getTopLevelModule() != M->getTopLevelModule()) 312 if (MDC.isPrebuiltModule(Import->getTopLevelModule())) 313 if (SeenSubmodules.insert(Import->getTopLevelModule()).second) 314 MD.PrebuiltModuleDeps.emplace_back(Import->getTopLevelModule()); 315 } 316 317 void ModuleDepCollectorPP::addAllSubmoduleDeps( 318 const Module *M, ModuleDeps &MD, 319 llvm::DenseSet<const Module *> &AddedModules) { 320 addModuleDep(M, MD, AddedModules); 321 322 for (const Module *SubM : M->submodules()) 323 addAllSubmoduleDeps(SubM, MD, AddedModules); 324 } 325 326 void ModuleDepCollectorPP::addModuleDep( 327 const Module *M, ModuleDeps &MD, 328 llvm::DenseSet<const Module *> &AddedModules) { 329 for (const Module *Import : M->Imports) { 330 if (Import->getTopLevelModule() != M->getTopLevelModule() && 331 !MDC.isPrebuiltModule(Import)) { 332 ModuleID ImportID = handleTopLevelModule(Import->getTopLevelModule()); 333 if (AddedModules.insert(Import->getTopLevelModule()).second) 334 MD.ClangModuleDeps.push_back(ImportID); 335 } 336 } 337 } 338 339 ModuleDepCollector::ModuleDepCollector( 340 std::unique_ptr<DependencyOutputOptions> Opts, 341 CompilerInstance &ScanInstance, DependencyConsumer &C, 342 CompilerInvocation &&OriginalCI, bool OptimizeArgs) 343 : ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opts)), 344 OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {} 345 346 void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) { 347 PP.addPPCallbacks(std::make_unique<ModuleDepCollectorPP>(*this)); 348 } 349 350 void ModuleDepCollector::attachToASTReader(ASTReader &R) {} 351 352 bool ModuleDepCollector::isPrebuiltModule(const Module *M) { 353 std::string Name(M->getTopLevelModuleName()); 354 const auto &PrebuiltModuleFiles = 355 ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles; 356 auto PrebuiltModuleFileIt = PrebuiltModuleFiles.find(Name); 357 if (PrebuiltModuleFileIt == PrebuiltModuleFiles.end()) 358 return false; 359 assert("Prebuilt module came from the expected AST file" && 360 PrebuiltModuleFileIt->second == M->getASTFile()->getName()); 361 return true; 362 } 363