[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Frontend / CompilerInstance.cpp
blobd749195585eca5b46f3542dc77ee14946f1588d5
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "clang/Frontend/CompilerInstance.h"
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangStandard.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/Stack.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Basic/Version.h"
22 #include "clang/Config/config.h"
23 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendPluginRegistry.h"
28 #include "clang/Frontend/LogDiagnosticPrinter.h"
29 #include "clang/Frontend/SARIFDiagnosticPrinter.h"
30 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
31 #include "clang/Frontend/TextDiagnosticPrinter.h"
32 #include "clang/Frontend/Utils.h"
33 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Lex/PreprocessorOptions.h"
37 #include "clang/Sema/CodeCompleteConsumer.h"
38 #include "clang/Sema/Sema.h"
39 #include "clang/Serialization/ASTReader.h"
40 #include "clang/Serialization/GlobalModuleIndex.h"
41 #include "clang/Serialization/InMemoryModuleCache.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/ScopeExit.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Config/llvm-config.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CrashRecoveryContext.h"
48 #include "llvm/Support/Errc.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/LockFileManager.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/Signals.h"
55 #include "llvm/Support/TimeProfiler.h"
56 #include "llvm/Support/Timer.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/TargetParser/Host.h"
59 #include <optional>
60 #include <time.h>
61 #include <utility>
63 using namespace clang;
65 CompilerInstance::CompilerInstance(
66 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
67 InMemoryModuleCache *SharedModuleCache)
68 : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
69 Invocation(new CompilerInvocation()),
70 ModuleCache(SharedModuleCache ? SharedModuleCache
71 : new InMemoryModuleCache),
72 ThePCHContainerOperations(std::move(PCHContainerOps)) {}
74 CompilerInstance::~CompilerInstance() {
75 assert(OutputFiles.empty() && "Still output files in flight?");
78 void CompilerInstance::setInvocation(
79 std::shared_ptr<CompilerInvocation> Value) {
80 Invocation = std::move(Value);
83 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
84 return (BuildGlobalModuleIndex ||
85 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
86 getFrontendOpts().GenerateGlobalModuleIndex)) &&
87 !DisableGeneratingGlobalModuleIndex;
90 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
91 Diagnostics = Value;
94 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
95 OwnedVerboseOutputStream.reset();
96 VerboseOutputStream = &Value;
99 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
100 OwnedVerboseOutputStream.swap(Value);
101 VerboseOutputStream = OwnedVerboseOutputStream.get();
104 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
105 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
107 bool CompilerInstance::createTarget() {
108 // Create the target instance.
109 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
110 getInvocation().TargetOpts));
111 if (!hasTarget())
112 return false;
114 // Check whether AuxTarget exists, if not, then create TargetInfo for the
115 // other side of CUDA/OpenMP/SYCL compilation.
116 if (!getAuxTarget() &&
117 (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
118 getLangOpts().SYCLIsDevice) &&
119 !getFrontendOpts().AuxTriple.empty()) {
120 auto TO = std::make_shared<TargetOptions>();
121 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
122 if (getFrontendOpts().AuxTargetCPU)
123 TO->CPU = *getFrontendOpts().AuxTargetCPU;
124 if (getFrontendOpts().AuxTargetFeatures)
125 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
126 TO->HostTriple = getTarget().getTriple().str();
127 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
130 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
131 if (getLangOpts().RoundingMath) {
132 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
133 getLangOpts().RoundingMath = false;
135 auto FPExc = getLangOpts().getFPExceptionMode();
136 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
137 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
138 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
140 // FIXME: can we disable FEnvAccess?
143 // We should do it here because target knows nothing about
144 // language options when it's being created.
145 if (getLangOpts().OpenCL &&
146 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
147 return false;
149 // Inform the target of the language options.
150 // FIXME: We shouldn't need to do this, the target should be immutable once
151 // created. This complexity should be lifted elsewhere.
152 getTarget().adjust(getDiagnostics(), getLangOpts());
154 if (auto *Aux = getAuxTarget())
155 getTarget().setAuxTarget(Aux);
157 return true;
160 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
161 return getFileManager().getVirtualFileSystem();
164 void CompilerInstance::setFileManager(FileManager *Value) {
165 FileMgr = Value;
168 void CompilerInstance::setSourceManager(SourceManager *Value) {
169 SourceMgr = Value;
172 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
173 PP = std::move(Value);
176 void CompilerInstance::setASTContext(ASTContext *Value) {
177 Context = Value;
179 if (Context && Consumer)
180 getASTConsumer().Initialize(getASTContext());
183 void CompilerInstance::setSema(Sema *S) {
184 TheSema.reset(S);
187 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
188 Consumer = std::move(Value);
190 if (Context && Consumer)
191 getASTConsumer().Initialize(getASTContext());
194 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
195 CompletionConsumer.reset(Value);
198 std::unique_ptr<Sema> CompilerInstance::takeSema() {
199 return std::move(TheSema);
202 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
203 return TheASTReader;
205 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
206 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
207 "Expected ASTReader to use the same PCM cache");
208 TheASTReader = std::move(Reader);
211 std::shared_ptr<ModuleDependencyCollector>
212 CompilerInstance::getModuleDepCollector() const {
213 return ModuleDepCollector;
216 void CompilerInstance::setModuleDepCollector(
217 std::shared_ptr<ModuleDependencyCollector> Collector) {
218 ModuleDepCollector = std::move(Collector);
221 static void collectHeaderMaps(const HeaderSearch &HS,
222 std::shared_ptr<ModuleDependencyCollector> MDC) {
223 SmallVector<std::string, 4> HeaderMapFileNames;
224 HS.getHeaderMapFileNames(HeaderMapFileNames);
225 for (auto &Name : HeaderMapFileNames)
226 MDC->addFile(Name);
229 static void collectIncludePCH(CompilerInstance &CI,
230 std::shared_ptr<ModuleDependencyCollector> MDC) {
231 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
232 if (PPOpts.ImplicitPCHInclude.empty())
233 return;
235 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
236 FileManager &FileMgr = CI.getFileManager();
237 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
238 if (!PCHDir) {
239 MDC->addFile(PCHInclude);
240 return;
243 std::error_code EC;
244 SmallString<128> DirNative;
245 llvm::sys::path::native(PCHDir->getName(), DirNative);
246 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
247 SimpleASTReaderListener Validator(CI.getPreprocessor());
248 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
249 Dir != DirEnd && !EC; Dir.increment(EC)) {
250 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
251 // used here since we're not interested in validating the PCH at this time,
252 // but only to check whether this is a file containing an AST.
253 if (!ASTReader::readASTFileControlBlock(
254 Dir->path(), FileMgr, CI.getModuleCache(),
255 CI.getPCHContainerReader(),
256 /*FindModuleFileExtensions=*/false, Validator,
257 /*ValidateDiagnosticOptions=*/false))
258 MDC->addFile(Dir->path());
262 static void collectVFSEntries(CompilerInstance &CI,
263 std::shared_ptr<ModuleDependencyCollector> MDC) {
264 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
265 return;
267 // Collect all VFS found.
268 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
269 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
270 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
271 llvm::MemoryBuffer::getFile(VFSFile);
272 if (!Buffer)
273 return;
274 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
275 /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
278 for (auto &E : VFSEntries)
279 MDC->addFile(E.VPath, E.RPath);
282 // Diagnostics
283 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
284 const CodeGenOptions *CodeGenOpts,
285 DiagnosticsEngine &Diags) {
286 std::error_code EC;
287 std::unique_ptr<raw_ostream> StreamOwner;
288 raw_ostream *OS = &llvm::errs();
289 if (DiagOpts->DiagnosticLogFile != "-") {
290 // Create the output stream.
291 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
292 DiagOpts->DiagnosticLogFile, EC,
293 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
294 if (EC) {
295 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
296 << DiagOpts->DiagnosticLogFile << EC.message();
297 } else {
298 FileOS->SetUnbuffered();
299 OS = FileOS.get();
300 StreamOwner = std::move(FileOS);
304 // Chain in the diagnostic client which will log the diagnostics.
305 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
306 std::move(StreamOwner));
307 if (CodeGenOpts)
308 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
309 if (Diags.ownsClient()) {
310 Diags.setClient(
311 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
312 } else {
313 Diags.setClient(
314 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
318 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
319 DiagnosticsEngine &Diags,
320 StringRef OutputFile) {
321 auto SerializedConsumer =
322 clang::serialized_diags::create(OutputFile, DiagOpts);
324 if (Diags.ownsClient()) {
325 Diags.setClient(new ChainedDiagnosticConsumer(
326 Diags.takeClient(), std::move(SerializedConsumer)));
327 } else {
328 Diags.setClient(new ChainedDiagnosticConsumer(
329 Diags.getClient(), std::move(SerializedConsumer)));
333 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
334 bool ShouldOwnClient) {
335 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
336 ShouldOwnClient, &getCodeGenOpts());
339 IntrusiveRefCntPtr<DiagnosticsEngine>
340 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
341 DiagnosticConsumer *Client,
342 bool ShouldOwnClient,
343 const CodeGenOptions *CodeGenOpts) {
344 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
345 IntrusiveRefCntPtr<DiagnosticsEngine>
346 Diags(new DiagnosticsEngine(DiagID, Opts));
348 // Create the diagnostic client for reporting errors or for
349 // implementing -verify.
350 if (Client) {
351 Diags->setClient(Client, ShouldOwnClient);
352 } else if (Opts->getFormat() == DiagnosticOptions::SARIF) {
353 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
354 } else
355 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
357 // Chain in -verify checker, if requested.
358 if (Opts->VerifyDiagnostics)
359 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
361 // Chain in -diagnostic-log-file dumper, if requested.
362 if (!Opts->DiagnosticLogFile.empty())
363 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
365 if (!Opts->DiagnosticSerializationFile.empty())
366 SetupSerializedDiagnostics(Opts, *Diags,
367 Opts->DiagnosticSerializationFile);
369 // Configure our handling of diagnostics.
370 ProcessWarningOptions(*Diags, *Opts);
372 return Diags;
375 // File Manager
377 FileManager *CompilerInstance::createFileManager(
378 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
379 if (!VFS)
380 VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
381 : createVFSFromCompilerInvocation(getInvocation(),
382 getDiagnostics());
383 assert(VFS && "FileManager has no VFS?");
384 FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
385 return FileMgr.get();
388 // Source Manager
390 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
391 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
394 // Initialize the remapping of files to alternative contents, e.g.,
395 // those specified through other files.
396 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
397 SourceManager &SourceMgr,
398 FileManager &FileMgr,
399 const PreprocessorOptions &InitOpts) {
400 // Remap files in the source manager (with buffers).
401 for (const auto &RB : InitOpts.RemappedFileBuffers) {
402 // Create the file entry for the file that we're mapping from.
403 FileEntryRef FromFile =
404 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
406 // Override the contents of the "from" file with the contents of the
407 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
408 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
409 // to the SourceManager.
410 if (InitOpts.RetainRemappedFileBuffers)
411 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
412 else
413 SourceMgr.overrideFileContents(
414 FromFile, std::unique_ptr<llvm::MemoryBuffer>(
415 const_cast<llvm::MemoryBuffer *>(RB.second)));
418 // Remap files in the source manager (with other files).
419 for (const auto &RF : InitOpts.RemappedFiles) {
420 // Find the file that we're mapping to.
421 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
422 if (!ToFile) {
423 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
424 continue;
427 // Create the file entry for the file that we're mapping from.
428 const FileEntry *FromFile =
429 FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
430 if (!FromFile) {
431 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
432 continue;
435 // Override the contents of the "from" file with the contents of
436 // the "to" file.
437 SourceMgr.overrideFileContents(FromFile, *ToFile);
440 SourceMgr.setOverridenFilesKeepOriginalName(
441 InitOpts.RemappedFilesKeepOriginalName);
444 // Preprocessor
446 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
447 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
449 // The AST reader holds a reference to the old preprocessor (if any).
450 TheASTReader.reset();
452 // Create the Preprocessor.
453 HeaderSearch *HeaderInfo =
454 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
455 getDiagnostics(), getLangOpts(), &getTarget());
456 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
457 getDiagnostics(), getLangOpts(),
458 getSourceManager(), *HeaderInfo, *this,
459 /*IdentifierInfoLookup=*/nullptr,
460 /*OwnsHeaderSearch=*/true, TUKind);
461 getTarget().adjust(getDiagnostics(), getLangOpts());
462 PP->Initialize(getTarget(), getAuxTarget());
464 if (PPOpts.DetailedRecord)
465 PP->createPreprocessingRecord();
467 // Apply remappings to the source manager.
468 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
469 PP->getFileManager(), PPOpts);
471 // Predefine macros and configure the preprocessor.
472 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
473 getFrontendOpts());
475 // Initialize the header search object. In CUDA compilations, we use the aux
476 // triple (the host triple) to initialize our header search, since we need to
477 // find the host headers in order to compile the CUDA code.
478 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
479 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
480 PP->getAuxTargetInfo())
481 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
483 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
484 PP->getLangOpts(), *HeaderSearchTriple);
486 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
488 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
489 std::string ModuleHash = getInvocation().getModuleHash();
490 PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
491 PP->getHeaderSearchInfo().setModuleCachePath(
492 getSpecificModuleCachePath(ModuleHash));
495 // Handle generating dependencies, if requested.
496 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
497 if (!DepOpts.OutputFile.empty())
498 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
499 if (!DepOpts.DOTOutputFile.empty())
500 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
501 getHeaderSearchOpts().Sysroot);
503 // If we don't have a collector, but we are collecting module dependencies,
504 // then we're the top level compiler instance and need to create one.
505 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
506 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
507 DepOpts.ModuleDependencyOutputDir);
510 // If there is a module dep collector, register with other dep collectors
511 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
512 if (ModuleDepCollector) {
513 addDependencyCollector(ModuleDepCollector);
514 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
515 collectIncludePCH(*this, ModuleDepCollector);
516 collectVFSEntries(*this, ModuleDepCollector);
519 for (auto &Listener : DependencyCollectors)
520 Listener->attachToPreprocessor(*PP);
522 // Handle generating header include information, if requested.
523 if (DepOpts.ShowHeaderIncludes)
524 AttachHeaderIncludeGen(*PP, DepOpts);
525 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
526 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
527 if (OutputPath == "-")
528 OutputPath = "";
529 AttachHeaderIncludeGen(*PP, DepOpts,
530 /*ShowAllHeaders=*/true, OutputPath,
531 /*ShowDepth=*/false);
534 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
535 AttachHeaderIncludeGen(*PP, DepOpts,
536 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
537 /*ShowDepth=*/true, /*MSStyle=*/true);
541 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
542 // Set up the module path, including the hash for the module-creation options.
543 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
544 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
545 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
546 return std::string(SpecificModuleCache.str());
549 // ASTContext
551 void CompilerInstance::createASTContext() {
552 Preprocessor &PP = getPreprocessor();
553 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
554 PP.getIdentifierTable(), PP.getSelectorTable(),
555 PP.getBuiltinInfo(), PP.TUKind);
556 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
557 setASTContext(Context);
560 // ExternalASTSource
562 namespace {
563 // Helper to recursively read the module names for all modules we're adding.
564 // We mark these as known and redirect any attempt to load that module to
565 // the files we were handed.
566 struct ReadModuleNames : ASTReaderListener {
567 Preprocessor &PP;
568 llvm::SmallVector<std::string, 8> LoadedModules;
570 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
572 void ReadModuleName(StringRef ModuleName) override {
573 // Keep the module name as a string for now. It's not safe to create a new
574 // IdentifierInfo from an ASTReader callback.
575 LoadedModules.push_back(ModuleName.str());
578 void registerAll() {
579 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
580 for (const std::string &LoadedModule : LoadedModules)
581 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
582 MM.findModule(LoadedModule));
583 LoadedModules.clear();
586 void markAllUnavailable() {
587 for (const std::string &LoadedModule : LoadedModules) {
588 if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
589 LoadedModule)) {
590 M->HasIncompatibleModuleFile = true;
592 // Mark module as available if the only reason it was unavailable
593 // was missing headers.
594 SmallVector<Module *, 2> Stack;
595 Stack.push_back(M);
596 while (!Stack.empty()) {
597 Module *Current = Stack.pop_back_val();
598 if (Current->IsUnimportable) continue;
599 Current->IsAvailable = true;
600 auto SubmodulesRange = Current->submodules();
601 Stack.insert(Stack.end(), SubmodulesRange.begin(),
602 SubmodulesRange.end());
606 LoadedModules.clear();
609 } // namespace
611 void CompilerInstance::createPCHExternalASTSource(
612 StringRef Path, DisableValidationForModuleKind DisableValidation,
613 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
614 bool OwnDeserializationListener) {
615 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
616 TheASTReader = createPCHExternalASTSource(
617 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
618 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
619 getASTContext(), getPCHContainerReader(),
620 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
621 DeserializationListener, OwnDeserializationListener, Preamble,
622 getFrontendOpts().UseGlobalModuleIndex);
625 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
626 StringRef Path, StringRef Sysroot,
627 DisableValidationForModuleKind DisableValidation,
628 bool AllowPCHWithCompilerErrors, Preprocessor &PP,
629 InMemoryModuleCache &ModuleCache, ASTContext &Context,
630 const PCHContainerReader &PCHContainerRdr,
631 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
632 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
633 void *DeserializationListener, bool OwnDeserializationListener,
634 bool Preamble, bool UseGlobalModuleIndex) {
635 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
637 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
638 PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
639 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
640 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
641 HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
642 UseGlobalModuleIndex));
644 // We need the external source to be set up before we read the AST, because
645 // eagerly-deserialized declarations may use it.
646 Context.setExternalSource(Reader.get());
648 Reader->setDeserializationListener(
649 static_cast<ASTDeserializationListener *>(DeserializationListener),
650 /*TakeOwnership=*/OwnDeserializationListener);
652 for (auto &Listener : DependencyCollectors)
653 Listener->attachToASTReader(*Reader);
655 auto Listener = std::make_unique<ReadModuleNames>(PP);
656 auto &ListenerRef = *Listener;
657 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
658 std::move(Listener));
660 switch (Reader->ReadAST(Path,
661 Preamble ? serialization::MK_Preamble
662 : serialization::MK_PCH,
663 SourceLocation(),
664 ASTReader::ARR_None)) {
665 case ASTReader::Success:
666 // Set the predefines buffer as suggested by the PCH reader. Typically, the
667 // predefines buffer will be empty.
668 PP.setPredefines(Reader->getSuggestedPredefines());
669 ListenerRef.registerAll();
670 return Reader;
672 case ASTReader::Failure:
673 // Unrecoverable failure: don't even try to process the input file.
674 break;
676 case ASTReader::Missing:
677 case ASTReader::OutOfDate:
678 case ASTReader::VersionMismatch:
679 case ASTReader::ConfigurationMismatch:
680 case ASTReader::HadErrors:
681 // No suitable PCH file could be found. Return an error.
682 break;
685 ListenerRef.markAllUnavailable();
686 Context.setExternalSource(nullptr);
687 return nullptr;
690 // Code Completion
692 static bool EnableCodeCompletion(Preprocessor &PP,
693 StringRef Filename,
694 unsigned Line,
695 unsigned Column) {
696 // Tell the source manager to chop off the given file at a specific
697 // line and column.
698 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
699 if (!Entry) {
700 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
701 << Filename;
702 return true;
705 // Truncate the named file at the given line/column.
706 PP.SetCodeCompletionPoint(*Entry, Line, Column);
707 return false;
710 void CompilerInstance::createCodeCompletionConsumer() {
711 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
712 if (!CompletionConsumer) {
713 setCodeCompletionConsumer(createCodeCompletionConsumer(
714 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
715 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
716 return;
717 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
718 Loc.Line, Loc.Column)) {
719 setCodeCompletionConsumer(nullptr);
720 return;
724 void CompilerInstance::createFrontendTimer() {
725 FrontendTimerGroup.reset(
726 new llvm::TimerGroup("frontend", "Clang front-end time report"));
727 FrontendTimer.reset(
728 new llvm::Timer("frontend", "Clang front-end timer",
729 *FrontendTimerGroup));
732 CodeCompleteConsumer *
733 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
734 StringRef Filename,
735 unsigned Line,
736 unsigned Column,
737 const CodeCompleteOptions &Opts,
738 raw_ostream &OS) {
739 if (EnableCodeCompletion(PP, Filename, Line, Column))
740 return nullptr;
742 // Set up the creation routine for code-completion.
743 return new PrintingCodeCompleteConsumer(Opts, OS);
746 void CompilerInstance::createSema(TranslationUnitKind TUKind,
747 CodeCompleteConsumer *CompletionConsumer) {
748 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
749 TUKind, CompletionConsumer));
750 // Attach the external sema source if there is any.
751 if (ExternalSemaSrc) {
752 TheSema->addExternalSource(ExternalSemaSrc.get());
753 ExternalSemaSrc->InitializeSema(*TheSema);
757 // Output Files
759 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
760 // The ASTConsumer can own streams that write to the output files.
761 assert(!hasASTConsumer() && "ASTConsumer should be reset");
762 // Ignore errors that occur when trying to discard the temp file.
763 for (OutputFile &OF : OutputFiles) {
764 if (EraseFiles) {
765 if (OF.File)
766 consumeError(OF.File->discard());
767 if (!OF.Filename.empty())
768 llvm::sys::fs::remove(OF.Filename);
769 continue;
772 if (!OF.File)
773 continue;
775 if (OF.File->TmpName.empty()) {
776 consumeError(OF.File->discard());
777 continue;
780 llvm::Error E = OF.File->keep(OF.Filename);
781 if (!E)
782 continue;
784 getDiagnostics().Report(diag::err_unable_to_rename_temp)
785 << OF.File->TmpName << OF.Filename << std::move(E);
787 llvm::sys::fs::remove(OF.File->TmpName);
789 OutputFiles.clear();
790 if (DeleteBuiltModules) {
791 for (auto &Module : BuiltModules)
792 llvm::sys::fs::remove(Module.second);
793 BuiltModules.clear();
797 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
798 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
799 bool CreateMissingDirectories, bool ForceUseTemporary) {
800 StringRef OutputPath = getFrontendOpts().OutputFile;
801 std::optional<SmallString<128>> PathStorage;
802 if (OutputPath.empty()) {
803 if (InFile == "-" || Extension.empty()) {
804 OutputPath = "-";
805 } else {
806 PathStorage.emplace(InFile);
807 llvm::sys::path::replace_extension(*PathStorage, Extension);
808 OutputPath = *PathStorage;
812 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
813 getFrontendOpts().UseTemporary || ForceUseTemporary,
814 CreateMissingDirectories);
817 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
818 return std::make_unique<llvm::raw_null_ostream>();
821 std::unique_ptr<raw_pwrite_stream>
822 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
823 bool RemoveFileOnSignal, bool UseTemporary,
824 bool CreateMissingDirectories) {
825 Expected<std::unique_ptr<raw_pwrite_stream>> OS =
826 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
827 CreateMissingDirectories);
828 if (OS)
829 return std::move(*OS);
830 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
831 << OutputPath << errorToErrorCode(OS.takeError()).message();
832 return nullptr;
835 Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
836 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
837 bool RemoveFileOnSignal,
838 bool UseTemporary,
839 bool CreateMissingDirectories) {
840 assert((!CreateMissingDirectories || UseTemporary) &&
841 "CreateMissingDirectories is only allowed when using temporary files");
843 // If '-working-directory' was passed, the output filename should be
844 // relative to that.
845 std::optional<SmallString<128>> AbsPath;
846 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
847 assert(hasFileManager() &&
848 "File Manager is required to fix up relative path.\n");
850 AbsPath.emplace(OutputPath);
851 FileMgr->FixupRelativePath(*AbsPath);
852 OutputPath = *AbsPath;
855 std::unique_ptr<llvm::raw_fd_ostream> OS;
856 std::optional<StringRef> OSFile;
858 if (UseTemporary) {
859 if (OutputPath == "-")
860 UseTemporary = false;
861 else {
862 llvm::sys::fs::file_status Status;
863 llvm::sys::fs::status(OutputPath, Status);
864 if (llvm::sys::fs::exists(Status)) {
865 // Fail early if we can't write to the final destination.
866 if (!llvm::sys::fs::can_write(OutputPath))
867 return llvm::errorCodeToError(
868 make_error_code(llvm::errc::operation_not_permitted));
870 // Don't use a temporary if the output is a special file. This handles
871 // things like '-o /dev/null'
872 if (!llvm::sys::fs::is_regular_file(Status))
873 UseTemporary = false;
878 std::optional<llvm::sys::fs::TempFile> Temp;
879 if (UseTemporary) {
880 // Create a temporary file.
881 // Insert -%%%%%%%% before the extension (if any), and because some tools
882 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
883 // artifacts, also append .tmp.
884 StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
885 SmallString<128> TempPath =
886 StringRef(OutputPath).drop_back(OutputExtension.size());
887 TempPath += "-%%%%%%%%";
888 TempPath += OutputExtension;
889 TempPath += ".tmp";
890 llvm::sys::fs::OpenFlags BinaryFlags =
891 Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text;
892 Expected<llvm::sys::fs::TempFile> ExpectedFile =
893 llvm::sys::fs::TempFile::create(
894 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
895 BinaryFlags);
897 llvm::Error E = handleErrors(
898 ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
899 std::error_code EC = E.convertToErrorCode();
900 if (CreateMissingDirectories &&
901 EC == llvm::errc::no_such_file_or_directory) {
902 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
903 EC = llvm::sys::fs::create_directories(Parent);
904 if (!EC) {
905 ExpectedFile = llvm::sys::fs::TempFile::create(
906 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
907 BinaryFlags);
908 if (!ExpectedFile)
909 return llvm::errorCodeToError(
910 llvm::errc::no_such_file_or_directory);
913 return llvm::errorCodeToError(EC);
916 if (E) {
917 consumeError(std::move(E));
918 } else {
919 Temp = std::move(ExpectedFile.get());
920 OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false));
921 OSFile = Temp->TmpName;
923 // If we failed to create the temporary, fallback to writing to the file
924 // directly. This handles the corner case where we cannot write to the
925 // directory, but can write to the file.
928 if (!OS) {
929 OSFile = OutputPath;
930 std::error_code EC;
931 OS.reset(new llvm::raw_fd_ostream(
932 *OSFile, EC,
933 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
934 if (EC)
935 return llvm::errorCodeToError(EC);
938 // Add the output file -- but don't try to remove "-", since this means we are
939 // using stdin.
940 OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
941 std::move(Temp));
943 if (!Binary || OS->supportsSeeking())
944 return std::move(OS);
946 return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
949 // Initialization Utilities
951 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
952 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
953 getSourceManager());
956 // static
957 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
958 DiagnosticsEngine &Diags,
959 FileManager &FileMgr,
960 SourceManager &SourceMgr) {
961 SrcMgr::CharacteristicKind Kind =
962 Input.getKind().getFormat() == InputKind::ModuleMap
963 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
964 : SrcMgr::C_User_ModuleMap
965 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
967 if (Input.isBuffer()) {
968 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
969 assert(SourceMgr.getMainFileID().isValid() &&
970 "Couldn't establish MainFileID!");
971 return true;
974 StringRef InputFile = Input.getFile();
976 // Figure out where to get and map in the main file.
977 auto FileOrErr = InputFile == "-"
978 ? FileMgr.getSTDIN()
979 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
980 if (!FileOrErr) {
981 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
982 if (InputFile != "-")
983 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
984 else
985 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
986 return false;
989 SourceMgr.setMainFileID(
990 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
992 assert(SourceMgr.getMainFileID().isValid() &&
993 "Couldn't establish MainFileID!");
994 return true;
997 // High-Level Operations
999 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
1000 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1001 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
1002 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
1004 // Mark this point as the bottom of the stack if we don't have somewhere
1005 // better. We generally expect frontend actions to be invoked with (nearly)
1006 // DesiredStackSpace available.
1007 noteBottomOfStack();
1009 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
1010 // Notify the diagnostic client that all files were processed.
1011 getDiagnosticClient().finish();
1014 raw_ostream &OS = getVerboseOutputStream();
1016 if (!Act.PrepareToExecute(*this))
1017 return false;
1019 if (!createTarget())
1020 return false;
1022 // rewriter project will change target built-in bool type from its default.
1023 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1024 getTarget().noSignedCharForObjCBool();
1026 // Validate/process some options.
1027 if (getHeaderSearchOpts().Verbose)
1028 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
1029 << LLVM_VERSION_STRING << " default target "
1030 << llvm::sys::getDefaultTargetTriple() << "\n";
1032 if (getCodeGenOpts().TimePasses)
1033 createFrontendTimer();
1035 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
1036 llvm::EnableStatistics(false);
1038 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1039 // Reset the ID tables if we are reusing the SourceManager and parsing
1040 // regular files.
1041 if (hasSourceManager() && !Act.isModelParsingAction())
1042 getSourceManager().clearIDTables();
1044 if (Act.BeginSourceFile(*this, FIF)) {
1045 if (llvm::Error Err = Act.Execute()) {
1046 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1048 Act.EndSourceFile();
1052 if (getDiagnosticOpts().ShowCarets) {
1053 // We can have multiple diagnostics sharing one diagnostic client.
1054 // Get the total number of warnings/errors from the client.
1055 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1056 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1058 if (NumWarnings)
1059 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1060 if (NumWarnings && NumErrors)
1061 OS << " and ";
1062 if (NumErrors)
1063 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1064 if (NumWarnings || NumErrors) {
1065 OS << " generated";
1066 if (getLangOpts().CUDA) {
1067 if (!getLangOpts().CUDAIsDevice) {
1068 OS << " when compiling for host";
1069 } else {
1070 OS << " when compiling for " << getTargetOpts().CPU;
1073 OS << ".\n";
1077 if (getFrontendOpts().ShowStats) {
1078 if (hasFileManager()) {
1079 getFileManager().PrintStats();
1080 OS << '\n';
1082 llvm::PrintStatistics(OS);
1084 StringRef StatsFile = getFrontendOpts().StatsFile;
1085 if (!StatsFile.empty()) {
1086 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1087 if (getFrontendOpts().AppendStats)
1088 FileFlags |= llvm::sys::fs::OF_Append;
1089 std::error_code EC;
1090 auto StatS =
1091 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1092 if (EC) {
1093 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1094 << StatsFile << EC.message();
1095 } else {
1096 llvm::PrintStatisticsJSON(*StatS);
1100 return !getDiagnostics().getClient()->getNumErrors();
1103 void CompilerInstance::LoadRequestedPlugins() {
1104 // Load any requested plugins.
1105 for (const std::string &Path : getFrontendOpts().Plugins) {
1106 std::string Error;
1107 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1108 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1109 << Path << Error;
1112 // Check if any of the loaded plugins replaces the main AST action
1113 for (const FrontendPluginRegistry::entry &Plugin :
1114 FrontendPluginRegistry::entries()) {
1115 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1116 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1117 getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
1118 getFrontendOpts().ActionName = Plugin.getName().str();
1119 break;
1124 /// Determine the appropriate source input kind based on language
1125 /// options.
1126 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1127 if (LangOpts.OpenCL)
1128 return Language::OpenCL;
1129 if (LangOpts.CUDA)
1130 return Language::CUDA;
1131 if (LangOpts.ObjC)
1132 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1133 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1136 /// Compile a module file for the given module, using the options
1137 /// provided by the importing compiler instance. Returns true if the module
1138 /// was built without errors.
1139 static bool
1140 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1141 StringRef ModuleName, FrontendInputFile Input,
1142 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1143 llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1144 [](CompilerInstance &) {},
1145 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1146 [](CompilerInstance &) {}) {
1147 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1149 // Never compile a module that's already finalized - this would cause the
1150 // existing module to be freed, causing crashes if it is later referenced
1151 if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
1152 ImportingInstance.getDiagnostics().Report(
1153 ImportLoc, diag::err_module_rebuild_finalized)
1154 << ModuleName;
1155 return false;
1158 // Construct a compiler invocation for creating this module.
1159 auto Invocation =
1160 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1162 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1164 // For any options that aren't intended to affect how a module is built,
1165 // reset them to their default values.
1166 Invocation->resetNonModularOptions();
1168 // Remove any macro definitions that are explicitly ignored by the module.
1169 // They aren't supposed to affect how the module is built anyway.
1170 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1171 llvm::erase_if(PPOpts.Macros,
1172 [&HSOpts](const std::pair<std::string, bool> &def) {
1173 StringRef MacroDef = def.first;
1174 return HSOpts.ModulesIgnoreMacros.contains(
1175 llvm::CachedHashString(MacroDef.split('=').first));
1178 // If the original compiler invocation had -fmodule-name, pass it through.
1179 Invocation->getLangOpts().ModuleName =
1180 ImportingInstance.getInvocation().getLangOpts().ModuleName;
1182 // Note the name of the module we're building.
1183 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1185 // Make sure that the failed-module structure has been allocated in
1186 // the importing instance, and propagate the pointer to the newly-created
1187 // instance.
1188 PreprocessorOptions &ImportingPPOpts
1189 = ImportingInstance.getInvocation().getPreprocessorOpts();
1190 if (!ImportingPPOpts.FailedModules)
1191 ImportingPPOpts.FailedModules =
1192 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1193 PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1195 // If there is a module map file, build the module using the module map.
1196 // Set up the inputs/outputs so that we build the module from its umbrella
1197 // header.
1198 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1199 FrontendOpts.OutputFile = ModuleFileName.str();
1200 FrontendOpts.DisableFree = false;
1201 FrontendOpts.GenerateGlobalModuleIndex = false;
1202 FrontendOpts.BuildingImplicitModule = true;
1203 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1204 // Force implicitly-built modules to hash the content of the module file.
1205 HSOpts.ModulesHashContent = true;
1206 FrontendOpts.Inputs = {Input};
1208 // Don't free the remapped file buffers; they are owned by our caller.
1209 PPOpts.RetainRemappedFileBuffers = true;
1211 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1213 DiagOpts.VerifyDiagnostics = 0;
1214 assert(ImportingInstance.getInvocation().getModuleHash() ==
1215 Invocation->getModuleHash() && "Module hash mismatch!");
1217 // Construct a compiler instance that will be used to actually create the
1218 // module. Since we're sharing an in-memory module cache,
1219 // CompilerInstance::CompilerInstance is responsible for finalizing the
1220 // buffers to prevent use-after-frees.
1221 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1222 &ImportingInstance.getModuleCache());
1223 auto &Inv = *Invocation;
1224 Instance.setInvocation(std::move(Invocation));
1226 Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1227 ImportingInstance.getDiagnosticClient()),
1228 /*ShouldOwnClient=*/true);
1230 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1231 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1233 if (FrontendOpts.ModulesShareFileManager) {
1234 Instance.setFileManager(&ImportingInstance.getFileManager());
1235 } else {
1236 Instance.createFileManager(&ImportingInstance.getVirtualFileSystem());
1238 Instance.createSourceManager(Instance.getFileManager());
1239 SourceManager &SourceMgr = Instance.getSourceManager();
1241 // Note that this module is part of the module build stack, so that we
1242 // can detect cycles in the module graph.
1243 SourceMgr.setModuleBuildStack(
1244 ImportingInstance.getSourceManager().getModuleBuildStack());
1245 SourceMgr.pushModuleBuildStack(ModuleName,
1246 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1248 // If we're collecting module dependencies, we need to share a collector
1249 // between all of the module CompilerInstances. Other than that, we don't
1250 // want to produce any dependency output from the module build.
1251 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1252 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1254 ImportingInstance.getDiagnostics().Report(ImportLoc,
1255 diag::remark_module_build)
1256 << ModuleName << ModuleFileName;
1258 PreBuildStep(Instance);
1260 // Execute the action to actually build the module in-place. Use a separate
1261 // thread so that we get a stack large enough.
1262 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
1263 [&]() {
1264 GenerateModuleFromModuleMapAction Action;
1265 Instance.ExecuteAction(Action);
1267 DesiredStackSize);
1269 PostBuildStep(Instance);
1271 ImportingInstance.getDiagnostics().Report(ImportLoc,
1272 diag::remark_module_build_done)
1273 << ModuleName;
1275 if (Crashed) {
1276 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1277 // that must be closed before clearing output files.
1278 Instance.setSema(nullptr);
1279 Instance.setASTConsumer(nullptr);
1281 // Delete any remaining temporary files related to Instance.
1282 Instance.clearOutputFiles(/*EraseFiles=*/true);
1285 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1286 // occurred.
1287 return !Instance.getDiagnostics().hasErrorOccurred() ||
1288 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1291 static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
1292 FileManager &FileMgr) {
1293 StringRef Filename = llvm::sys::path::filename(File.getName());
1294 SmallString<128> PublicFilename(File.getDir().getName());
1295 if (Filename == "module_private.map")
1296 llvm::sys::path::append(PublicFilename, "module.map");
1297 else if (Filename == "module.private.modulemap")
1298 llvm::sys::path::append(PublicFilename, "module.modulemap");
1299 else
1300 return std::nullopt;
1301 return FileMgr.getOptionalFileRef(PublicFilename);
1304 /// Compile a module file for the given module in a separate compiler instance,
1305 /// using the options provided by the importing compiler instance. Returns true
1306 /// if the module was built without errors.
1307 static bool compileModule(CompilerInstance &ImportingInstance,
1308 SourceLocation ImportLoc, Module *Module,
1309 StringRef ModuleFileName) {
1310 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1311 InputKind::ModuleMap);
1313 // Get or create the module map that we'll use to build this module.
1314 ModuleMap &ModMap
1315 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1316 bool Result;
1317 if (OptionalFileEntryRef ModuleMapFile =
1318 ModMap.getContainingModuleMapFile(Module)) {
1319 // Canonicalize compilation to start with the public module map. This is
1320 // vital for submodules declarations in the private module maps to be
1321 // correctly parsed when depending on a top level module in the public one.
1322 if (OptionalFileEntryRef PublicMMFile = getPublicModuleMap(
1323 *ModuleMapFile, ImportingInstance.getFileManager()))
1324 ModuleMapFile = PublicMMFile;
1326 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1328 // Use the module map where this module resides.
1329 Result = compileModuleImpl(
1330 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1331 FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem),
1332 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName);
1333 } else {
1334 // FIXME: We only need to fake up an input file here as a way of
1335 // transporting the module's directory to the module map parser. We should
1336 // be able to do that more directly, and parse from a memory buffer without
1337 // inventing this file.
1338 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1339 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1341 std::string InferredModuleMapContent;
1342 llvm::raw_string_ostream OS(InferredModuleMapContent);
1343 Module->print(OS);
1344 OS.flush();
1346 Result = compileModuleImpl(
1347 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1348 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1349 ModMap.getModuleMapFileForUniquing(Module)->getName(),
1350 ModuleFileName,
1351 [&](CompilerInstance &Instance) {
1352 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1353 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1354 FileEntryRef ModuleMapFile = Instance.getFileManager().getVirtualFileRef(
1355 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1356 Instance.getSourceManager().overrideFileContents(
1357 ModuleMapFile, std::move(ModuleMapBuffer));
1361 // We've rebuilt a module. If we're allowed to generate or update the global
1362 // module index, record that fact in the importing compiler instance.
1363 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1364 ImportingInstance.setBuildGlobalModuleIndex(true);
1367 return Result;
1370 /// Read the AST right after compiling the module.
1371 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1372 SourceLocation ImportLoc,
1373 SourceLocation ModuleNameLoc,
1374 Module *Module, StringRef ModuleFileName,
1375 bool *OutOfDate) {
1376 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1378 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1379 if (OutOfDate)
1380 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1382 // Try to read the module file, now that we've compiled it.
1383 ASTReader::ASTReadResult ReadResult =
1384 ImportingInstance.getASTReader()->ReadAST(
1385 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1386 ModuleLoadCapabilities);
1387 if (ReadResult == ASTReader::Success)
1388 return true;
1390 // The caller wants to handle out-of-date failures.
1391 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1392 *OutOfDate = true;
1393 return false;
1396 // The ASTReader didn't diagnose the error, so conservatively report it.
1397 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1398 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1399 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1401 return false;
1404 /// Compile a module in a separate compiler instance and read the AST,
1405 /// returning true if the module compiles without errors.
1406 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1407 SourceLocation ImportLoc,
1408 SourceLocation ModuleNameLoc,
1409 Module *Module,
1410 StringRef ModuleFileName) {
1411 if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
1412 ModuleFileName)) {
1413 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1414 diag::err_module_not_built)
1415 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1416 return false;
1419 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1420 Module, ModuleFileName,
1421 /*OutOfDate=*/nullptr);
1424 /// Compile a module in a separate compiler instance and read the AST,
1425 /// returning true if the module compiles without errors, using a lock manager
1426 /// to avoid building the same module in multiple compiler instances.
1428 /// Uses a lock file manager and exponential backoff to reduce the chances that
1429 /// multiple instances will compete to create the same module. On timeout,
1430 /// deletes the lock file in order to avoid deadlock from crashing processes or
1431 /// bugs in the lock file manager.
1432 static bool compileModuleAndReadASTBehindLock(
1433 CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1434 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1435 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1437 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1438 << ModuleFileName << Module->Name;
1440 // FIXME: have LockFileManager return an error_code so that we can
1441 // avoid the mkdir when the directory already exists.
1442 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1443 llvm::sys::fs::create_directories(Dir);
1445 while (true) {
1446 llvm::LockFileManager Locked(ModuleFileName);
1447 switch (Locked) {
1448 case llvm::LockFileManager::LFS_Error:
1449 // ModuleCache takes care of correctness and locks are only necessary for
1450 // performance. Fallback to building the module in case of any lock
1451 // related errors.
1452 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1453 << Module->Name << Locked.getErrorMessage();
1454 // Clear out any potential leftover.
1455 Locked.unsafeRemoveLockFile();
1456 [[fallthrough]];
1457 case llvm::LockFileManager::LFS_Owned:
1458 // We're responsible for building the module ourselves.
1459 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1460 ModuleNameLoc, Module, ModuleFileName);
1462 case llvm::LockFileManager::LFS_Shared:
1463 break; // The interesting case.
1466 // Someone else is responsible for building the module. Wait for them to
1467 // finish.
1468 switch (Locked.waitForUnlock()) {
1469 case llvm::LockFileManager::Res_Success:
1470 break; // The interesting case.
1471 case llvm::LockFileManager::Res_OwnerDied:
1472 continue; // try again to get the lock.
1473 case llvm::LockFileManager::Res_Timeout:
1474 // Since ModuleCache takes care of correctness, we try waiting for
1475 // another process to complete the build so clang does not do it done
1476 // twice. If case of timeout, build it ourselves.
1477 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1478 << Module->Name;
1479 // Clear the lock file so that future invocations can make progress.
1480 Locked.unsafeRemoveLockFile();
1481 continue;
1484 // Read the module that was just written by someone else.
1485 bool OutOfDate = false;
1486 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1487 Module, ModuleFileName, &OutOfDate))
1488 return true;
1489 if (!OutOfDate)
1490 return false;
1492 // The module may be out of date in the presence of file system races,
1493 // or if one of its imports depends on header search paths that are not
1494 // consistent with this ImportingInstance. Try again...
1498 /// Compile a module in a separate compiler instance and read the AST,
1499 /// returning true if the module compiles without errors, potentially using a
1500 /// lock manager to avoid building the same module in multiple compiler
1501 /// instances.
1502 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1503 SourceLocation ImportLoc,
1504 SourceLocation ModuleNameLoc,
1505 Module *Module, StringRef ModuleFileName) {
1506 return ImportingInstance.getInvocation()
1507 .getFrontendOpts()
1508 .BuildingImplicitModuleUsesLock
1509 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1510 ModuleNameLoc, Module,
1511 ModuleFileName)
1512 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1513 ModuleNameLoc, Module,
1514 ModuleFileName);
1517 /// Diagnose differences between the current definition of the given
1518 /// configuration macro and the definition provided on the command line.
1519 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1520 Module *Mod, SourceLocation ImportLoc) {
1521 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1522 SourceManager &SourceMgr = PP.getSourceManager();
1524 // If this identifier has never had a macro definition, then it could
1525 // not have changed.
1526 if (!Id->hadMacroDefinition())
1527 return;
1528 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1530 // Find the macro definition from the command line.
1531 MacroInfo *CmdLineDefinition = nullptr;
1532 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1533 // We only care about the predefines buffer.
1534 FileID FID = SourceMgr.getFileID(MD->getLocation());
1535 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1536 continue;
1537 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1538 CmdLineDefinition = DMD->getMacroInfo();
1539 break;
1542 auto *CurrentDefinition = PP.getMacroInfo(Id);
1543 if (CurrentDefinition == CmdLineDefinition) {
1544 // Macro matches. Nothing to do.
1545 } else if (!CurrentDefinition) {
1546 // This macro was defined on the command line, then #undef'd later.
1547 // Complain.
1548 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1549 << true << ConfigMacro << Mod->getFullModuleName();
1550 auto LatestDef = LatestLocalMD->getDefinition();
1551 assert(LatestDef.isUndefined() &&
1552 "predefined macro went away with no #undef?");
1553 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1554 << true;
1555 return;
1556 } else if (!CmdLineDefinition) {
1557 // There was no definition for this macro in the predefines buffer,
1558 // but there was a local definition. Complain.
1559 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1560 << false << ConfigMacro << Mod->getFullModuleName();
1561 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1562 diag::note_module_def_undef_here)
1563 << false;
1564 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1565 /*Syntactically=*/true)) {
1566 // The macro definitions differ.
1567 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1568 << false << ConfigMacro << Mod->getFullModuleName();
1569 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1570 diag::note_module_def_undef_here)
1571 << false;
1575 /// Write a new timestamp file with the given path.
1576 static void writeTimestampFile(StringRef TimestampFile) {
1577 std::error_code EC;
1578 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1581 /// Prune the module cache of modules that haven't been accessed in
1582 /// a long time.
1583 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1584 llvm::sys::fs::file_status StatBuf;
1585 llvm::SmallString<128> TimestampFile;
1586 TimestampFile = HSOpts.ModuleCachePath;
1587 assert(!TimestampFile.empty());
1588 llvm::sys::path::append(TimestampFile, "modules.timestamp");
1590 // Try to stat() the timestamp file.
1591 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1592 // If the timestamp file wasn't there, create one now.
1593 if (EC == std::errc::no_such_file_or_directory) {
1594 writeTimestampFile(TimestampFile);
1596 return;
1599 // Check whether the time stamp is older than our pruning interval.
1600 // If not, do nothing.
1601 time_t TimeStampModTime =
1602 llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1603 time_t CurrentTime = time(nullptr);
1604 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1605 return;
1607 // Write a new timestamp file so that nobody else attempts to prune.
1608 // There is a benign race condition here, if two Clang instances happen to
1609 // notice at the same time that the timestamp is out-of-date.
1610 writeTimestampFile(TimestampFile);
1612 // Walk the entire module cache, looking for unused module files and module
1613 // indices.
1614 std::error_code EC;
1615 SmallString<128> ModuleCachePathNative;
1616 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1617 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1618 Dir != DirEnd && !EC; Dir.increment(EC)) {
1619 // If we don't have a directory, there's nothing to look into.
1620 if (!llvm::sys::fs::is_directory(Dir->path()))
1621 continue;
1623 // Walk all of the files within this directory.
1624 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1625 File != FileEnd && !EC; File.increment(EC)) {
1626 // We only care about module and global module index files.
1627 StringRef Extension = llvm::sys::path::extension(File->path());
1628 if (Extension != ".pcm" && Extension != ".timestamp" &&
1629 llvm::sys::path::filename(File->path()) != "modules.idx")
1630 continue;
1632 // Look at this file. If we can't stat it, there's nothing interesting
1633 // there.
1634 if (llvm::sys::fs::status(File->path(), StatBuf))
1635 continue;
1637 // If the file has been used recently enough, leave it there.
1638 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1639 if (CurrentTime - FileAccessTime <=
1640 time_t(HSOpts.ModuleCachePruneAfter)) {
1641 continue;
1644 // Remove the file.
1645 llvm::sys::fs::remove(File->path());
1647 // Remove the timestamp file.
1648 std::string TimpestampFilename = File->path() + ".timestamp";
1649 llvm::sys::fs::remove(TimpestampFilename);
1652 // If we removed all of the files in the directory, remove the directory
1653 // itself.
1654 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1655 llvm::sys::fs::directory_iterator() && !EC)
1656 llvm::sys::fs::remove(Dir->path());
1660 void CompilerInstance::createASTReader() {
1661 if (TheASTReader)
1662 return;
1664 if (!hasASTContext())
1665 createASTContext();
1667 // If we're implicitly building modules but not currently recursively
1668 // building a module, check whether we need to prune the module cache.
1669 if (getSourceManager().getModuleBuildStack().empty() &&
1670 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1671 getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1672 getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1673 pruneModuleCache(getHeaderSearchOpts());
1676 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1677 std::string Sysroot = HSOpts.Sysroot;
1678 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1679 const FrontendOptions &FEOpts = getFrontendOpts();
1680 std::unique_ptr<llvm::Timer> ReadTimer;
1682 if (FrontendTimerGroup)
1683 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1684 "Reading modules",
1685 *FrontendTimerGroup);
1686 TheASTReader = new ASTReader(
1687 getPreprocessor(), getModuleCache(), &getASTContext(),
1688 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1689 Sysroot.empty() ? "" : Sysroot.c_str(),
1690 PPOpts.DisablePCHOrModuleValidation,
1691 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1692 /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
1693 HSOpts.ValidateASTInputFilesContent,
1694 getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1695 if (hasASTConsumer()) {
1696 TheASTReader->setDeserializationListener(
1697 getASTConsumer().GetASTDeserializationListener());
1698 getASTContext().setASTMutationListener(
1699 getASTConsumer().GetASTMutationListener());
1701 getASTContext().setExternalSource(TheASTReader);
1702 if (hasSema())
1703 TheASTReader->InitializeSema(getSema());
1704 if (hasASTConsumer())
1705 TheASTReader->StartTranslationUnit(&getASTConsumer());
1707 for (auto &Listener : DependencyCollectors)
1708 Listener->attachToASTReader(*TheASTReader);
1711 bool CompilerInstance::loadModuleFile(
1712 StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1713 llvm::Timer Timer;
1714 if (FrontendTimerGroup)
1715 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1716 *FrontendTimerGroup);
1717 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1719 // If we don't already have an ASTReader, create one now.
1720 if (!TheASTReader)
1721 createASTReader();
1723 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1724 // ASTReader to diagnose it, since it can produce better errors that we can.
1725 bool ConfigMismatchIsRecoverable =
1726 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1727 SourceLocation())
1728 <= DiagnosticsEngine::Warning;
1730 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1731 auto &ListenerRef = *Listener;
1732 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1733 std::move(Listener));
1735 // Try to load the module file.
1736 switch (TheASTReader->ReadAST(
1737 FileName, serialization::MK_ExplicitModule, SourceLocation(),
1738 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1739 &LoadedModuleFile)) {
1740 case ASTReader::Success:
1741 // We successfully loaded the module file; remember the set of provided
1742 // modules so that we don't try to load implicit modules for them.
1743 ListenerRef.registerAll();
1744 return true;
1746 case ASTReader::ConfigurationMismatch:
1747 // Ignore unusable module files.
1748 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1749 << FileName;
1750 // All modules provided by any files we tried and failed to load are now
1751 // unavailable; includes of those modules should now be handled textually.
1752 ListenerRef.markAllUnavailable();
1753 return true;
1755 default:
1756 return false;
1760 namespace {
1761 enum ModuleSource {
1762 MS_ModuleNotFound,
1763 MS_ModuleCache,
1764 MS_PrebuiltModulePath,
1765 MS_ModuleBuildPragma
1767 } // end namespace
1769 /// Select a source for loading the named module and compute the filename to
1770 /// load it from.
1771 static ModuleSource selectModuleSource(
1772 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1773 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1774 HeaderSearch &HS) {
1775 assert(ModuleFilename.empty() && "Already has a module source?");
1777 // Check to see if the module has been built as part of this compilation
1778 // via a module build pragma.
1779 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1780 if (BuiltModuleIt != BuiltModules.end()) {
1781 ModuleFilename = BuiltModuleIt->second;
1782 return MS_ModuleBuildPragma;
1785 // Try to load the module from the prebuilt module path.
1786 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1787 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1788 !HSOpts.PrebuiltModulePaths.empty()) {
1789 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1790 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1791 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1792 if (!ModuleFilename.empty())
1793 return MS_PrebuiltModulePath;
1796 // Try to load the module from the module cache.
1797 if (M) {
1798 ModuleFilename = HS.getCachedModuleFileName(M);
1799 return MS_ModuleCache;
1802 return MS_ModuleNotFound;
1805 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1806 StringRef ModuleName, SourceLocation ImportLoc,
1807 SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1808 // Search for a module with the given name.
1809 HeaderSearch &HS = PP->getHeaderSearchInfo();
1810 Module *M =
1811 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1813 // Select the source and filename for loading the named module.
1814 std::string ModuleFilename;
1815 ModuleSource Source =
1816 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1817 if (Source == MS_ModuleNotFound) {
1818 // We can't find a module, error out here.
1819 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1820 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1821 return nullptr;
1823 if (ModuleFilename.empty()) {
1824 if (M && M->HasIncompatibleModuleFile) {
1825 // We tried and failed to load a module file for this module. Fall
1826 // back to textual inclusion for its headers.
1827 return ModuleLoadResult::ConfigMismatch;
1830 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1831 << ModuleName;
1832 return nullptr;
1835 // Create an ASTReader on demand.
1836 if (!getASTReader())
1837 createASTReader();
1839 // Time how long it takes to load the module.
1840 llvm::Timer Timer;
1841 if (FrontendTimerGroup)
1842 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1843 *FrontendTimerGroup);
1844 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1845 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1847 // Try to load the module file. If we are not trying to load from the
1848 // module cache, we don't know how to rebuild modules.
1849 unsigned ARRFlags = Source == MS_ModuleCache
1850 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1851 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1852 : Source == MS_PrebuiltModulePath
1854 : ASTReader::ARR_ConfigurationMismatch;
1855 switch (getASTReader()->ReadAST(ModuleFilename,
1856 Source == MS_PrebuiltModulePath
1857 ? serialization::MK_PrebuiltModule
1858 : Source == MS_ModuleBuildPragma
1859 ? serialization::MK_ExplicitModule
1860 : serialization::MK_ImplicitModule,
1861 ImportLoc, ARRFlags)) {
1862 case ASTReader::Success: {
1863 if (M)
1864 return M;
1865 assert(Source != MS_ModuleCache &&
1866 "missing module, but file loaded from cache");
1868 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1869 // until the first call to ReadAST. Look it up now.
1870 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1872 // Check whether M refers to the file in the prebuilt module path.
1873 if (M && M->getASTFile())
1874 if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1875 if (*ModuleFile == M->getASTFile())
1876 return M;
1878 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1879 << ModuleName;
1880 return ModuleLoadResult();
1883 case ASTReader::OutOfDate:
1884 case ASTReader::Missing:
1885 // The most interesting case.
1886 break;
1888 case ASTReader::ConfigurationMismatch:
1889 if (Source == MS_PrebuiltModulePath)
1890 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1891 // produce a warning here!
1892 getDiagnostics().Report(SourceLocation(),
1893 diag::warn_module_config_mismatch)
1894 << ModuleFilename;
1895 // Fall through to error out.
1896 [[fallthrough]];
1897 case ASTReader::VersionMismatch:
1898 case ASTReader::HadErrors:
1899 ModuleLoader::HadFatalFailure = true;
1900 // FIXME: The ASTReader will already have complained, but can we shoehorn
1901 // that diagnostic information into a more useful form?
1902 return ModuleLoadResult();
1904 case ASTReader::Failure:
1905 ModuleLoader::HadFatalFailure = true;
1906 return ModuleLoadResult();
1909 // ReadAST returned Missing or OutOfDate.
1910 if (Source != MS_ModuleCache) {
1911 // We don't know the desired configuration for this module and don't
1912 // necessarily even have a module map. Since ReadAST already produces
1913 // diagnostics for these two cases, we simply error out here.
1914 return ModuleLoadResult();
1917 // The module file is missing or out-of-date. Build it.
1918 assert(M && "missing module, but trying to compile for cache");
1920 // Check whether there is a cycle in the module graph.
1921 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1922 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1923 for (; Pos != PosEnd; ++Pos) {
1924 if (Pos->first == ModuleName)
1925 break;
1928 if (Pos != PosEnd) {
1929 SmallString<256> CyclePath;
1930 for (; Pos != PosEnd; ++Pos) {
1931 CyclePath += Pos->first;
1932 CyclePath += " -> ";
1934 CyclePath += ModuleName;
1936 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1937 << ModuleName << CyclePath;
1938 return nullptr;
1941 // Check whether we have already attempted to build this module (but
1942 // failed).
1943 if (getPreprocessorOpts().FailedModules &&
1944 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1945 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1946 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1947 return nullptr;
1950 // Try to compile and then read the AST.
1951 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1952 ModuleFilename)) {
1953 assert(getDiagnostics().hasErrorOccurred() &&
1954 "undiagnosed error in compileModuleAndReadAST");
1955 if (getPreprocessorOpts().FailedModules)
1956 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1957 return nullptr;
1960 // Okay, we've rebuilt and now loaded the module.
1961 return M;
1964 ModuleLoadResult
1965 CompilerInstance::loadModule(SourceLocation ImportLoc,
1966 ModuleIdPath Path,
1967 Module::NameVisibilityKind Visibility,
1968 bool IsInclusionDirective) {
1969 // Determine what file we're searching from.
1970 StringRef ModuleName = Path[0].first->getName();
1971 SourceLocation ModuleNameLoc = Path[0].second;
1973 // If we've already handled this import, just return the cached result.
1974 // This one-element cache is important to eliminate redundant diagnostics
1975 // when both the preprocessor and parser see the same import declaration.
1976 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1977 // Make the named module visible.
1978 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1979 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1980 ImportLoc);
1981 return LastModuleImportResult;
1984 // If we don't already have information on this module, load the module now.
1985 Module *Module = nullptr;
1986 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1987 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
1988 // Use the cached result, which may be nullptr.
1989 Module = *MaybeModule;
1990 } else if (ModuleName == getLangOpts().CurrentModule) {
1991 // This is the module we're building.
1992 Module = PP->getHeaderSearchInfo().lookupModule(
1993 ModuleName, ImportLoc, /*AllowSearch*/ true,
1994 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1996 MM.cacheModuleLoad(*Path[0].first, Module);
1997 } else {
1998 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1999 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
2000 if (!Result.isNormal())
2001 return Result;
2002 if (!Result)
2003 DisableGeneratingGlobalModuleIndex = true;
2004 Module = Result;
2005 MM.cacheModuleLoad(*Path[0].first, Module);
2008 // If we never found the module, fail. Otherwise, verify the module and link
2009 // it up.
2010 if (!Module)
2011 return ModuleLoadResult();
2013 // Verify that the rest of the module path actually corresponds to
2014 // a submodule.
2015 bool MapPrivateSubModToTopLevel = false;
2016 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2017 StringRef Name = Path[I].first->getName();
2018 clang::Module *Sub = Module->findSubmodule(Name);
2020 // If the user is requesting Foo.Private and it doesn't exist, try to
2021 // match Foo_Private and emit a warning asking for the user to write
2022 // @import Foo_Private instead. FIXME: remove this when existing clients
2023 // migrate off of Foo.Private syntax.
2024 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2025 SmallString<128> PrivateModule(Module->Name);
2026 PrivateModule.append("_Private");
2028 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
2029 auto &II = PP->getIdentifierTable().get(
2030 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2031 PrivPath.push_back(std::make_pair(&II, Path[0].second));
2033 std::string FileName;
2034 // If there is a modulemap module or prebuilt module, load it.
2035 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2036 !IsInclusionDirective) ||
2037 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2038 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2039 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2040 if (Sub) {
2041 MapPrivateSubModToTopLevel = true;
2042 PP->markClangModuleAsAffecting(Module);
2043 if (!getDiagnostics().isIgnored(
2044 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2045 getDiagnostics().Report(Path[I].second,
2046 diag::warn_no_priv_submodule_use_toplevel)
2047 << Path[I].first << Module->getFullModuleName() << PrivateModule
2048 << SourceRange(Path[0].second, Path[I].second)
2049 << FixItHint::CreateReplacement(SourceRange(Path[0].second),
2050 PrivateModule);
2051 getDiagnostics().Report(Sub->DefinitionLoc,
2052 diag::note_private_top_level_defined);
2057 if (!Sub) {
2058 // Attempt to perform typo correction to find a module name that works.
2059 SmallVector<StringRef, 2> Best;
2060 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2062 for (class Module *SubModule : Module->submodules()) {
2063 unsigned ED =
2064 Name.edit_distance(SubModule->Name,
2065 /*AllowReplacements=*/true, BestEditDistance);
2066 if (ED <= BestEditDistance) {
2067 if (ED < BestEditDistance) {
2068 Best.clear();
2069 BestEditDistance = ED;
2072 Best.push_back(SubModule->Name);
2076 // If there was a clear winner, user it.
2077 if (Best.size() == 1) {
2078 getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
2079 << Path[I].first << Module->getFullModuleName() << Best[0]
2080 << SourceRange(Path[0].second, Path[I - 1].second)
2081 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
2082 Best[0]);
2084 Sub = Module->findSubmodule(Best[0]);
2088 if (!Sub) {
2089 // No submodule by this name. Complain, and don't look for further
2090 // submodules.
2091 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
2092 << Path[I].first << Module->getFullModuleName()
2093 << SourceRange(Path[0].second, Path[I - 1].second);
2094 break;
2097 Module = Sub;
2100 // Make the named module visible, if it's not already part of the module
2101 // we are parsing.
2102 if (ModuleName != getLangOpts().CurrentModule) {
2103 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2104 // We have an umbrella header or directory that doesn't actually include
2105 // all of the headers within the directory it covers. Complain about
2106 // this missing submodule and recover by forgetting that we ever saw
2107 // this submodule.
2108 // FIXME: Should we detect this at module load time? It seems fairly
2109 // expensive (and rare).
2110 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2111 << Module->getFullModuleName()
2112 << SourceRange(Path.front().second, Path.back().second);
2114 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
2117 // Check whether this module is available.
2118 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2119 *Module, getDiagnostics())) {
2120 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2121 << SourceRange(Path.front().second, Path.back().second);
2122 LastModuleImportLoc = ImportLoc;
2123 LastModuleImportResult = ModuleLoadResult();
2124 return ModuleLoadResult();
2127 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2130 // Check for any configuration macros that have changed.
2131 clang::Module *TopModule = Module->getTopLevelModule();
2132 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
2133 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
2134 Module, ImportLoc);
2137 // Resolve any remaining module using export_as for this one.
2138 getPreprocessor()
2139 .getHeaderSearchInfo()
2140 .getModuleMap()
2141 .resolveLinkAsDependencies(TopModule);
2143 LastModuleImportLoc = ImportLoc;
2144 LastModuleImportResult = ModuleLoadResult(Module);
2145 return LastModuleImportResult;
2148 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2149 StringRef ModuleName,
2150 StringRef Source) {
2151 // Avoid creating filenames with special characters.
2152 SmallString<128> CleanModuleName(ModuleName);
2153 for (auto &C : CleanModuleName)
2154 if (!isAlphanumeric(C))
2155 C = '_';
2157 // FIXME: Using a randomized filename here means that our intermediate .pcm
2158 // output is nondeterministic (as .pcm files refer to each other by name).
2159 // Can this affect the output in any way?
2160 SmallString<128> ModuleFileName;
2161 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2162 CleanModuleName, "pcm", ModuleFileName)) {
2163 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2164 << ModuleFileName << EC.message();
2165 return;
2167 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2169 FrontendInputFile Input(
2170 ModuleMapFileName,
2171 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2172 InputKind::ModuleMap, /*Preprocessed*/true));
2174 std::string NullTerminatedSource(Source.str());
2176 auto PreBuildStep = [&](CompilerInstance &Other) {
2177 // Create a virtual file containing our desired source.
2178 // FIXME: We shouldn't need to do this.
2179 FileEntryRef ModuleMapFile = Other.getFileManager().getVirtualFileRef(
2180 ModuleMapFileName, NullTerminatedSource.size(), 0);
2181 Other.getSourceManager().overrideFileContents(
2182 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2184 Other.BuiltModules = std::move(BuiltModules);
2185 Other.DeleteBuiltModules = false;
2188 auto PostBuildStep = [this](CompilerInstance &Other) {
2189 BuiltModules = std::move(Other.BuiltModules);
2192 // Build the module, inheriting any modules that we've built locally.
2193 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2194 ModuleFileName, PreBuildStep, PostBuildStep)) {
2195 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
2196 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2200 void CompilerInstance::makeModuleVisible(Module *Mod,
2201 Module::NameVisibilityKind Visibility,
2202 SourceLocation ImportLoc) {
2203 if (!TheASTReader)
2204 createASTReader();
2205 if (!TheASTReader)
2206 return;
2208 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2211 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2212 SourceLocation TriggerLoc) {
2213 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2214 return nullptr;
2215 if (!TheASTReader)
2216 createASTReader();
2217 // Can't do anything if we don't have the module manager.
2218 if (!TheASTReader)
2219 return nullptr;
2220 // Get an existing global index. This loads it if not already
2221 // loaded.
2222 TheASTReader->loadGlobalIndex();
2223 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2224 // If the global index doesn't exist, create it.
2225 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2226 hasPreprocessor()) {
2227 llvm::sys::fs::create_directories(
2228 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2229 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2230 getFileManager(), getPCHContainerReader(),
2231 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2232 // FIXME this drops the error on the floor. This code is only used for
2233 // typo correction and drops more than just this one source of errors
2234 // (such as the directory creation failure above). It should handle the
2235 // error.
2236 consumeError(std::move(Err));
2237 return nullptr;
2239 TheASTReader->resetForReload();
2240 TheASTReader->loadGlobalIndex();
2241 GlobalIndex = TheASTReader->getGlobalIndex();
2243 // For finding modules needing to be imported for fixit messages,
2244 // we need to make the global index cover all modules, so we do that here.
2245 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2246 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2247 bool RecreateIndex = false;
2248 for (ModuleMap::module_iterator I = MMap.module_begin(),
2249 E = MMap.module_end(); I != E; ++I) {
2250 Module *TheModule = I->second;
2251 const FileEntry *Entry = TheModule->getASTFile();
2252 if (!Entry) {
2253 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2254 Path.push_back(std::make_pair(
2255 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2256 std::reverse(Path.begin(), Path.end());
2257 // Load a module as hidden. This also adds it to the global index.
2258 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2259 RecreateIndex = true;
2262 if (RecreateIndex) {
2263 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2264 getFileManager(), getPCHContainerReader(),
2265 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2266 // FIXME As above, this drops the error on the floor.
2267 consumeError(std::move(Err));
2268 return nullptr;
2270 TheASTReader->resetForReload();
2271 TheASTReader->loadGlobalIndex();
2272 GlobalIndex = TheASTReader->getGlobalIndex();
2274 HaveFullGlobalModuleIndex = true;
2276 return GlobalIndex;
2279 // Check global module index for missing imports.
2280 bool
2281 CompilerInstance::lookupMissingImports(StringRef Name,
2282 SourceLocation TriggerLoc) {
2283 // Look for the symbol in non-imported modules, but only if an error
2284 // actually occurred.
2285 if (!buildingModule()) {
2286 // Load global module index, or retrieve a previously loaded one.
2287 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2288 TriggerLoc);
2290 // Only if we have a global index.
2291 if (GlobalIndex) {
2292 GlobalModuleIndex::HitSet FoundModules;
2294 // Find the modules that reference the identifier.
2295 // Note that this only finds top-level modules.
2296 // We'll let diagnoseTypo find the actual declaration module.
2297 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2298 return true;
2302 return false;
2304 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2306 void CompilerInstance::setExternalSemaSource(
2307 IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2308 ExternalSemaSrc = std::move(ESS);