1 //===--- CompilerInstance.cpp ---------------------------------------------===//
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
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/IntrusiveRefCntPtr.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/ScopeExit.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Config/llvm-config.h"
47 #include "llvm/Support/BuryPointer.h"
48 #include "llvm/Support/CrashRecoveryContext.h"
49 #include "llvm/Support/Errc.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/LockFileManager.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Program.h"
55 #include "llvm/Support/Signals.h"
56 #include "llvm/Support/TimeProfiler.h"
57 #include "llvm/Support/Timer.h"
58 #include "llvm/Support/VirtualFileSystem.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/TargetParser/Host.h"
65 using namespace clang
;
67 CompilerInstance::CompilerInstance(
68 std::shared_ptr
<PCHContainerOperations
> PCHContainerOps
,
69 InMemoryModuleCache
*SharedModuleCache
)
70 : ModuleLoader(/* BuildingModule = */ SharedModuleCache
),
71 Invocation(new CompilerInvocation()),
72 ModuleCache(SharedModuleCache
? SharedModuleCache
73 : new InMemoryModuleCache
),
74 ThePCHContainerOperations(std::move(PCHContainerOps
)) {}
76 CompilerInstance::~CompilerInstance() {
77 assert(OutputFiles
.empty() && "Still output files in flight?");
80 void CompilerInstance::setInvocation(
81 std::shared_ptr
<CompilerInvocation
> Value
) {
82 Invocation
= std::move(Value
);
85 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
86 return (BuildGlobalModuleIndex
||
87 (TheASTReader
&& TheASTReader
->isGlobalIndexUnavailable() &&
88 getFrontendOpts().GenerateGlobalModuleIndex
)) &&
89 !DisableGeneratingGlobalModuleIndex
;
92 void CompilerInstance::setDiagnostics(DiagnosticsEngine
*Value
) {
96 void CompilerInstance::setVerboseOutputStream(raw_ostream
&Value
) {
97 OwnedVerboseOutputStream
.reset();
98 VerboseOutputStream
= &Value
;
101 void CompilerInstance::setVerboseOutputStream(std::unique_ptr
<raw_ostream
> Value
) {
102 OwnedVerboseOutputStream
.swap(Value
);
103 VerboseOutputStream
= OwnedVerboseOutputStream
.get();
106 void CompilerInstance::setTarget(TargetInfo
*Value
) { Target
= Value
; }
107 void CompilerInstance::setAuxTarget(TargetInfo
*Value
) { AuxTarget
= Value
; }
109 bool CompilerInstance::createTarget() {
110 // Create the target instance.
111 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
112 getInvocation().TargetOpts
));
116 // Check whether AuxTarget exists, if not, then create TargetInfo for the
117 // other side of CUDA/OpenMP/SYCL compilation.
118 if (!getAuxTarget() &&
119 (getLangOpts().CUDA
|| getLangOpts().OpenMPIsTargetDevice
||
120 getLangOpts().SYCLIsDevice
) &&
121 !getFrontendOpts().AuxTriple
.empty()) {
122 auto TO
= std::make_shared
<TargetOptions
>();
123 TO
->Triple
= llvm::Triple::normalize(getFrontendOpts().AuxTriple
);
124 if (getFrontendOpts().AuxTargetCPU
)
125 TO
->CPU
= *getFrontendOpts().AuxTargetCPU
;
126 if (getFrontendOpts().AuxTargetFeatures
)
127 TO
->FeaturesAsWritten
= *getFrontendOpts().AuxTargetFeatures
;
128 TO
->HostTriple
= getTarget().getTriple().str();
129 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO
));
132 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP
) {
133 if (getLangOpts().RoundingMath
) {
134 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding
);
135 getLangOpts().RoundingMath
= false;
137 auto FPExc
= getLangOpts().getFPExceptionMode();
138 if (FPExc
!= LangOptions::FPE_Default
&& FPExc
!= LangOptions::FPE_Ignore
) {
139 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions
);
140 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore
);
142 // FIXME: can we disable FEnvAccess?
145 // We should do it here because target knows nothing about
146 // language options when it's being created.
147 if (getLangOpts().OpenCL
&&
148 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
151 // Inform the target of the language options.
152 // FIXME: We shouldn't need to do this, the target should be immutable once
153 // created. This complexity should be lifted elsewhere.
154 getTarget().adjust(getDiagnostics(), getLangOpts());
156 if (auto *Aux
= getAuxTarget())
157 getTarget().setAuxTarget(Aux
);
162 llvm::vfs::FileSystem
&CompilerInstance::getVirtualFileSystem() const {
163 return getFileManager().getVirtualFileSystem();
166 void CompilerInstance::setFileManager(FileManager
*Value
) {
170 void CompilerInstance::setSourceManager(SourceManager
*Value
) {
174 void CompilerInstance::setPreprocessor(std::shared_ptr
<Preprocessor
> Value
) {
175 PP
= std::move(Value
);
178 void CompilerInstance::setASTContext(ASTContext
*Value
) {
181 if (Context
&& Consumer
)
182 getASTConsumer().Initialize(getASTContext());
185 void CompilerInstance::setSema(Sema
*S
) {
189 void CompilerInstance::setASTConsumer(std::unique_ptr
<ASTConsumer
> Value
) {
190 Consumer
= std::move(Value
);
192 if (Context
&& Consumer
)
193 getASTConsumer().Initialize(getASTContext());
196 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer
*Value
) {
197 CompletionConsumer
.reset(Value
);
200 std::unique_ptr
<Sema
> CompilerInstance::takeSema() {
201 return std::move(TheSema
);
204 IntrusiveRefCntPtr
<ASTReader
> CompilerInstance::getASTReader() const {
207 void CompilerInstance::setASTReader(IntrusiveRefCntPtr
<ASTReader
> Reader
) {
208 assert(ModuleCache
.get() == &Reader
->getModuleManager().getModuleCache() &&
209 "Expected ASTReader to use the same PCM cache");
210 TheASTReader
= std::move(Reader
);
213 std::shared_ptr
<ModuleDependencyCollector
>
214 CompilerInstance::getModuleDepCollector() const {
215 return ModuleDepCollector
;
218 void CompilerInstance::setModuleDepCollector(
219 std::shared_ptr
<ModuleDependencyCollector
> Collector
) {
220 ModuleDepCollector
= std::move(Collector
);
223 static void collectHeaderMaps(const HeaderSearch
&HS
,
224 std::shared_ptr
<ModuleDependencyCollector
> MDC
) {
225 SmallVector
<std::string
, 4> HeaderMapFileNames
;
226 HS
.getHeaderMapFileNames(HeaderMapFileNames
);
227 for (auto &Name
: HeaderMapFileNames
)
231 static void collectIncludePCH(CompilerInstance
&CI
,
232 std::shared_ptr
<ModuleDependencyCollector
> MDC
) {
233 const PreprocessorOptions
&PPOpts
= CI
.getPreprocessorOpts();
234 if (PPOpts
.ImplicitPCHInclude
.empty())
237 StringRef PCHInclude
= PPOpts
.ImplicitPCHInclude
;
238 FileManager
&FileMgr
= CI
.getFileManager();
239 auto PCHDir
= FileMgr
.getOptionalDirectoryRef(PCHInclude
);
241 MDC
->addFile(PCHInclude
);
246 SmallString
<128> DirNative
;
247 llvm::sys::path::native(PCHDir
->getName(), DirNative
);
248 llvm::vfs::FileSystem
&FS
= FileMgr
.getVirtualFileSystem();
249 SimpleASTReaderListener
Validator(CI
.getPreprocessor());
250 for (llvm::vfs::directory_iterator Dir
= FS
.dir_begin(DirNative
, EC
), DirEnd
;
251 Dir
!= DirEnd
&& !EC
; Dir
.increment(EC
)) {
252 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
253 // used here since we're not interested in validating the PCH at this time,
254 // but only to check whether this is a file containing an AST.
255 if (!ASTReader::readASTFileControlBlock(
256 Dir
->path(), FileMgr
, CI
.getModuleCache(),
257 CI
.getPCHContainerReader(),
258 /*FindModuleFileExtensions=*/false, Validator
,
259 /*ValidateDiagnosticOptions=*/false))
260 MDC
->addFile(Dir
->path());
264 static void collectVFSEntries(CompilerInstance
&CI
,
265 std::shared_ptr
<ModuleDependencyCollector
> MDC
) {
266 if (CI
.getHeaderSearchOpts().VFSOverlayFiles
.empty())
269 // Collect all VFS found.
270 SmallVector
<llvm::vfs::YAMLVFSEntry
, 16> VFSEntries
;
271 for (const std::string
&VFSFile
: CI
.getHeaderSearchOpts().VFSOverlayFiles
) {
272 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> Buffer
=
273 llvm::MemoryBuffer::getFile(VFSFile
);
276 llvm::vfs::collectVFSFromYAML(std::move(Buffer
.get()),
277 /*DiagHandler*/ nullptr, VFSFile
, VFSEntries
);
280 for (auto &E
: VFSEntries
)
281 MDC
->addFile(E
.VPath
, E
.RPath
);
285 static void SetUpDiagnosticLog(DiagnosticOptions
*DiagOpts
,
286 const CodeGenOptions
*CodeGenOpts
,
287 DiagnosticsEngine
&Diags
) {
289 std::unique_ptr
<raw_ostream
> StreamOwner
;
290 raw_ostream
*OS
= &llvm::errs();
291 if (DiagOpts
->DiagnosticLogFile
!= "-") {
292 // Create the output stream.
293 auto FileOS
= std::make_unique
<llvm::raw_fd_ostream
>(
294 DiagOpts
->DiagnosticLogFile
, EC
,
295 llvm::sys::fs::OF_Append
| llvm::sys::fs::OF_TextWithCRLF
);
297 Diags
.Report(diag::warn_fe_cc_log_diagnostics_failure
)
298 << DiagOpts
->DiagnosticLogFile
<< EC
.message();
300 FileOS
->SetUnbuffered();
302 StreamOwner
= std::move(FileOS
);
306 // Chain in the diagnostic client which will log the diagnostics.
307 auto Logger
= std::make_unique
<LogDiagnosticPrinter
>(*OS
, DiagOpts
,
308 std::move(StreamOwner
));
310 Logger
->setDwarfDebugFlags(CodeGenOpts
->DwarfDebugFlags
);
311 if (Diags
.ownsClient()) {
313 new ChainedDiagnosticConsumer(Diags
.takeClient(), std::move(Logger
)));
316 new ChainedDiagnosticConsumer(Diags
.getClient(), std::move(Logger
)));
320 static void SetupSerializedDiagnostics(DiagnosticOptions
*DiagOpts
,
321 DiagnosticsEngine
&Diags
,
322 StringRef OutputFile
) {
323 auto SerializedConsumer
=
324 clang::serialized_diags::create(OutputFile
, DiagOpts
);
326 if (Diags
.ownsClient()) {
327 Diags
.setClient(new ChainedDiagnosticConsumer(
328 Diags
.takeClient(), std::move(SerializedConsumer
)));
330 Diags
.setClient(new ChainedDiagnosticConsumer(
331 Diags
.getClient(), std::move(SerializedConsumer
)));
335 void CompilerInstance::createDiagnostics(llvm::vfs::FileSystem
&VFS
,
336 DiagnosticConsumer
*Client
,
337 bool ShouldOwnClient
) {
338 Diagnostics
= createDiagnostics(VFS
, &getDiagnosticOpts(), Client
,
339 ShouldOwnClient
, &getCodeGenOpts());
342 IntrusiveRefCntPtr
<DiagnosticsEngine
> CompilerInstance::createDiagnostics(
343 llvm::vfs::FileSystem
&VFS
, DiagnosticOptions
*Opts
,
344 DiagnosticConsumer
*Client
, bool ShouldOwnClient
,
345 const CodeGenOptions
*CodeGenOpts
) {
346 IntrusiveRefCntPtr
<DiagnosticIDs
> DiagID(new DiagnosticIDs());
347 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags(
348 new DiagnosticsEngine(DiagID
, Opts
));
350 // Create the diagnostic client for reporting errors or for
351 // implementing -verify.
353 Diags
->setClient(Client
, ShouldOwnClient
);
354 } else if (Opts
->getFormat() == DiagnosticOptions::SARIF
) {
355 Diags
->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts
));
357 Diags
->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts
));
359 // Chain in -verify checker, if requested.
360 if (Opts
->VerifyDiagnostics
)
361 Diags
->setClient(new VerifyDiagnosticConsumer(*Diags
));
363 // Chain in -diagnostic-log-file dumper, if requested.
364 if (!Opts
->DiagnosticLogFile
.empty())
365 SetUpDiagnosticLog(Opts
, CodeGenOpts
, *Diags
);
367 if (!Opts
->DiagnosticSerializationFile
.empty())
368 SetupSerializedDiagnostics(Opts
, *Diags
,
369 Opts
->DiagnosticSerializationFile
);
371 // Configure our handling of diagnostics.
372 ProcessWarningOptions(*Diags
, *Opts
, VFS
);
379 FileManager
*CompilerInstance::createFileManager(
380 IntrusiveRefCntPtr
<llvm::vfs::FileSystem
> VFS
) {
382 VFS
= FileMgr
? &FileMgr
->getVirtualFileSystem()
383 : createVFSFromCompilerInvocation(getInvocation(),
385 assert(VFS
&& "FileManager has no VFS?");
386 if (getFrontendOpts().ShowStats
)
388 llvm::makeIntrusiveRefCnt
<llvm::vfs::TracingFileSystem
>(std::move(VFS
));
389 FileMgr
= new FileManager(getFileSystemOpts(), std::move(VFS
));
390 return FileMgr
.get();
395 void CompilerInstance::createSourceManager(FileManager
&FileMgr
) {
396 SourceMgr
= new SourceManager(getDiagnostics(), FileMgr
);
399 // Initialize the remapping of files to alternative contents, e.g.,
400 // those specified through other files.
401 static void InitializeFileRemapping(DiagnosticsEngine
&Diags
,
402 SourceManager
&SourceMgr
,
403 FileManager
&FileMgr
,
404 const PreprocessorOptions
&InitOpts
) {
405 // Remap files in the source manager (with buffers).
406 for (const auto &RB
: InitOpts
.RemappedFileBuffers
) {
407 // Create the file entry for the file that we're mapping from.
408 FileEntryRef FromFile
=
409 FileMgr
.getVirtualFileRef(RB
.first
, RB
.second
->getBufferSize(), 0);
411 // Override the contents of the "from" file with the contents of the
412 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
413 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
414 // to the SourceManager.
415 if (InitOpts
.RetainRemappedFileBuffers
)
416 SourceMgr
.overrideFileContents(FromFile
, RB
.second
->getMemBufferRef());
418 SourceMgr
.overrideFileContents(
419 FromFile
, std::unique_ptr
<llvm::MemoryBuffer
>(RB
.second
));
422 // Remap files in the source manager (with other files).
423 for (const auto &RF
: InitOpts
.RemappedFiles
) {
424 // Find the file that we're mapping to.
425 OptionalFileEntryRef ToFile
= FileMgr
.getOptionalFileRef(RF
.second
);
427 Diags
.Report(diag::err_fe_remap_missing_to_file
) << RF
.first
<< RF
.second
;
431 // Create the file entry for the file that we're mapping from.
432 FileEntryRef FromFile
=
433 FileMgr
.getVirtualFileRef(RF
.first
, ToFile
->getSize(), 0);
435 // Override the contents of the "from" file with the contents of
437 SourceMgr
.overrideFileContents(FromFile
, *ToFile
);
440 SourceMgr
.setOverridenFilesKeepOriginalName(
441 InitOpts
.RemappedFilesKeepOriginalName
);
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(), getCodeGenOpts());
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
== "-")
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
);
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
);
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
{
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());
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(
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
;
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();
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
,
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();
672 case ASTReader::Failure
:
673 // Unrecoverable failure: don't even try to process the input file.
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.
685 ListenerRef
.markAllUnavailable();
686 Context
.setExternalSource(nullptr);
692 static bool EnableCodeCompletion(Preprocessor
&PP
,
696 // Tell the source manager to chop off the given file at a specific
698 auto Entry
= PP
.getFileManager().getOptionalFileRef(Filename
);
700 PP
.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file
)
705 // Truncate the named file at the given line/column.
706 PP
.SetCodeCompletionPoint(*Entry
, Line
, Column
);
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()));
717 } else if (EnableCodeCompletion(getPreprocessor(), Loc
.FileName
,
718 Loc
.Line
, Loc
.Column
)) {
719 setCodeCompletionConsumer(nullptr);
724 void CompilerInstance::createFrontendTimer() {
725 FrontendTimerGroup
.reset(
726 new llvm::TimerGroup("frontend", "Clang front-end time report"));
728 new llvm::Timer("frontend", "Clang front-end timer",
729 *FrontendTimerGroup
));
732 CodeCompleteConsumer
*
733 CompilerInstance::createCodeCompletionConsumer(Preprocessor
&PP
,
737 const CodeCompleteOptions
&Opts
,
739 if (EnableCodeCompletion(PP
, Filename
, Line
, Column
))
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
));
752 TheSema
->APINotes
.setSwiftVersion(getAPINotesOpts().SwiftVersion
);
754 // Attach the external sema source if there is any.
755 if (ExternalSemaSrc
) {
756 TheSema
->addExternalSource(ExternalSemaSrc
.get());
757 ExternalSemaSrc
->InitializeSema(*TheSema
);
760 // If we're building a module and are supposed to load API notes,
761 // notify the API notes manager.
762 if (auto *currentModule
= getPreprocessor().getCurrentModule()) {
763 (void)TheSema
->APINotes
.loadCurrentModuleAPINotes(
764 currentModule
, getLangOpts().APINotesModules
,
765 getAPINotesOpts().ModuleSearchPaths
);
771 void CompilerInstance::clearOutputFiles(bool EraseFiles
) {
772 // The ASTConsumer can own streams that write to the output files.
773 assert(!hasASTConsumer() && "ASTConsumer should be reset");
774 // Ignore errors that occur when trying to discard the temp file.
775 for (OutputFile
&OF
: OutputFiles
) {
778 consumeError(OF
.File
->discard());
779 if (!OF
.Filename
.empty())
780 llvm::sys::fs::remove(OF
.Filename
);
787 if (OF
.File
->TmpName
.empty()) {
788 consumeError(OF
.File
->discard());
792 llvm::Error E
= OF
.File
->keep(OF
.Filename
);
796 getDiagnostics().Report(diag::err_unable_to_rename_temp
)
797 << OF
.File
->TmpName
<< OF
.Filename
<< std::move(E
);
799 llvm::sys::fs::remove(OF
.File
->TmpName
);
802 if (DeleteBuiltModules
) {
803 for (auto &Module
: BuiltModules
)
804 llvm::sys::fs::remove(Module
.second
);
805 BuiltModules
.clear();
809 std::unique_ptr
<raw_pwrite_stream
> CompilerInstance::createDefaultOutputFile(
810 bool Binary
, StringRef InFile
, StringRef Extension
, bool RemoveFileOnSignal
,
811 bool CreateMissingDirectories
, bool ForceUseTemporary
) {
812 StringRef OutputPath
= getFrontendOpts().OutputFile
;
813 std::optional
<SmallString
<128>> PathStorage
;
814 if (OutputPath
.empty()) {
815 if (InFile
== "-" || Extension
.empty()) {
818 PathStorage
.emplace(InFile
);
819 llvm::sys::path::replace_extension(*PathStorage
, Extension
);
820 OutputPath
= *PathStorage
;
824 return createOutputFile(OutputPath
, Binary
, RemoveFileOnSignal
,
825 getFrontendOpts().UseTemporary
|| ForceUseTemporary
,
826 CreateMissingDirectories
);
829 std::unique_ptr
<raw_pwrite_stream
> CompilerInstance::createNullOutputFile() {
830 return std::make_unique
<llvm::raw_null_ostream
>();
833 std::unique_ptr
<raw_pwrite_stream
>
834 CompilerInstance::createOutputFile(StringRef OutputPath
, bool Binary
,
835 bool RemoveFileOnSignal
, bool UseTemporary
,
836 bool CreateMissingDirectories
) {
837 Expected
<std::unique_ptr
<raw_pwrite_stream
>> OS
=
838 createOutputFileImpl(OutputPath
, Binary
, RemoveFileOnSignal
, UseTemporary
,
839 CreateMissingDirectories
);
841 return std::move(*OS
);
842 getDiagnostics().Report(diag::err_fe_unable_to_open_output
)
843 << OutputPath
<< errorToErrorCode(OS
.takeError()).message();
847 Expected
<std::unique_ptr
<llvm::raw_pwrite_stream
>>
848 CompilerInstance::createOutputFileImpl(StringRef OutputPath
, bool Binary
,
849 bool RemoveFileOnSignal
,
851 bool CreateMissingDirectories
) {
852 assert((!CreateMissingDirectories
|| UseTemporary
) &&
853 "CreateMissingDirectories is only allowed when using temporary files");
855 // If '-working-directory' was passed, the output filename should be
857 std::optional
<SmallString
<128>> AbsPath
;
858 if (OutputPath
!= "-" && !llvm::sys::path::is_absolute(OutputPath
)) {
859 assert(hasFileManager() &&
860 "File Manager is required to fix up relative path.\n");
862 AbsPath
.emplace(OutputPath
);
863 FileMgr
->FixupRelativePath(*AbsPath
);
864 OutputPath
= *AbsPath
;
867 std::unique_ptr
<llvm::raw_fd_ostream
> OS
;
868 std::optional
<StringRef
> OSFile
;
871 if (OutputPath
== "-")
872 UseTemporary
= false;
874 llvm::sys::fs::file_status Status
;
875 llvm::sys::fs::status(OutputPath
, Status
);
876 if (llvm::sys::fs::exists(Status
)) {
877 // Fail early if we can't write to the final destination.
878 if (!llvm::sys::fs::can_write(OutputPath
))
879 return llvm::errorCodeToError(
880 make_error_code(llvm::errc::operation_not_permitted
));
882 // Don't use a temporary if the output is a special file. This handles
883 // things like '-o /dev/null'
884 if (!llvm::sys::fs::is_regular_file(Status
))
885 UseTemporary
= false;
890 std::optional
<llvm::sys::fs::TempFile
> Temp
;
892 // Create a temporary file.
893 // Insert -%%%%%%%% before the extension (if any), and because some tools
894 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
895 // artifacts, also append .tmp.
896 StringRef OutputExtension
= llvm::sys::path::extension(OutputPath
);
897 SmallString
<128> TempPath
=
898 StringRef(OutputPath
).drop_back(OutputExtension
.size());
899 TempPath
+= "-%%%%%%%%";
900 TempPath
+= OutputExtension
;
902 llvm::sys::fs::OpenFlags BinaryFlags
=
903 Binary
? llvm::sys::fs::OF_None
: llvm::sys::fs::OF_Text
;
904 Expected
<llvm::sys::fs::TempFile
> ExpectedFile
=
905 llvm::sys::fs::TempFile::create(
906 TempPath
, llvm::sys::fs::all_read
| llvm::sys::fs::all_write
,
909 llvm::Error E
= handleErrors(
910 ExpectedFile
.takeError(), [&](const llvm::ECError
&E
) -> llvm::Error
{
911 std::error_code EC
= E
.convertToErrorCode();
912 if (CreateMissingDirectories
&&
913 EC
== llvm::errc::no_such_file_or_directory
) {
914 StringRef Parent
= llvm::sys::path::parent_path(OutputPath
);
915 EC
= llvm::sys::fs::create_directories(Parent
);
917 ExpectedFile
= llvm::sys::fs::TempFile::create(
918 TempPath
, llvm::sys::fs::all_read
| llvm::sys::fs::all_write
,
921 return llvm::errorCodeToError(
922 llvm::errc::no_such_file_or_directory
);
925 return llvm::errorCodeToError(EC
);
929 consumeError(std::move(E
));
931 Temp
= std::move(ExpectedFile
.get());
932 OS
.reset(new llvm::raw_fd_ostream(Temp
->FD
, /*shouldClose=*/false));
933 OSFile
= Temp
->TmpName
;
935 // If we failed to create the temporary, fallback to writing to the file
936 // directly. This handles the corner case where we cannot write to the
937 // directory, but can write to the file.
943 OS
.reset(new llvm::raw_fd_ostream(
945 (Binary
? llvm::sys::fs::OF_None
: llvm::sys::fs::OF_TextWithCRLF
)));
947 return llvm::errorCodeToError(EC
);
950 // Add the output file -- but don't try to remove "-", since this means we are
952 OutputFiles
.emplace_back(((OutputPath
!= "-") ? OutputPath
: "").str(),
955 if (!Binary
|| OS
->supportsSeeking())
956 return std::move(OS
);
958 return std::make_unique
<llvm::buffer_unique_ostream
>(std::move(OS
));
961 // Initialization Utilities
963 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile
&Input
){
964 return InitializeSourceManager(Input
, getDiagnostics(), getFileManager(),
969 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile
&Input
,
970 DiagnosticsEngine
&Diags
,
971 FileManager
&FileMgr
,
972 SourceManager
&SourceMgr
) {
973 SrcMgr::CharacteristicKind Kind
=
974 Input
.getKind().getFormat() == InputKind::ModuleMap
975 ? Input
.isSystem() ? SrcMgr::C_System_ModuleMap
976 : SrcMgr::C_User_ModuleMap
977 : Input
.isSystem() ? SrcMgr::C_System
: SrcMgr::C_User
;
979 if (Input
.isBuffer()) {
980 SourceMgr
.setMainFileID(SourceMgr
.createFileID(Input
.getBuffer(), Kind
));
981 assert(SourceMgr
.getMainFileID().isValid() &&
982 "Couldn't establish MainFileID!");
986 StringRef InputFile
= Input
.getFile();
988 // Figure out where to get and map in the main file.
989 auto FileOrErr
= InputFile
== "-"
991 : FileMgr
.getFileRef(InputFile
, /*OpenFile=*/true);
993 auto EC
= llvm::errorToErrorCode(FileOrErr
.takeError());
994 if (InputFile
!= "-")
995 Diags
.Report(diag::err_fe_error_reading
) << InputFile
<< EC
.message();
997 Diags
.Report(diag::err_fe_error_reading_stdin
) << EC
.message();
1001 SourceMgr
.setMainFileID(
1002 SourceMgr
.createFileID(*FileOrErr
, SourceLocation(), Kind
));
1004 assert(SourceMgr
.getMainFileID().isValid() &&
1005 "Couldn't establish MainFileID!");
1009 // High-Level Operations
1011 bool CompilerInstance::ExecuteAction(FrontendAction
&Act
) {
1012 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1013 assert(!getFrontendOpts().ShowHelp
&& "Client must handle '-help'!");
1014 assert(!getFrontendOpts().ShowVersion
&& "Client must handle '-version'!");
1016 // Mark this point as the bottom of the stack if we don't have somewhere
1017 // better. We generally expect frontend actions to be invoked with (nearly)
1018 // DesiredStackSpace available.
1019 noteBottomOfStack();
1021 auto FinishDiagnosticClient
= llvm::make_scope_exit([&]() {
1022 // Notify the diagnostic client that all files were processed.
1023 getDiagnosticClient().finish();
1026 raw_ostream
&OS
= getVerboseOutputStream();
1028 if (!Act
.PrepareToExecute(*this))
1031 if (!createTarget())
1034 // rewriter project will change target built-in bool type from its default.
1035 if (getFrontendOpts().ProgramAction
== frontend::RewriteObjC
)
1036 getTarget().noSignedCharForObjCBool();
1038 // Validate/process some options.
1039 if (getHeaderSearchOpts().Verbose
)
1040 OS
<< "clang -cc1 version " CLANG_VERSION_STRING
<< " based upon LLVM "
1041 << LLVM_VERSION_STRING
<< " default target "
1042 << llvm::sys::getDefaultTargetTriple() << "\n";
1044 if (getCodeGenOpts().TimePasses
)
1045 createFrontendTimer();
1047 if (getFrontendOpts().ShowStats
|| !getFrontendOpts().StatsFile
.empty())
1048 llvm::EnableStatistics(false);
1050 // Sort vectors containing toc data and no toc data variables to facilitate
1051 // binary search later.
1052 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified
);
1053 llvm::sort(getCodeGenOpts().NoTocDataVars
);
1055 for (const FrontendInputFile
&FIF
: getFrontendOpts().Inputs
) {
1056 // Reset the ID tables if we are reusing the SourceManager and parsing
1058 if (hasSourceManager() && !Act
.isModelParsingAction())
1059 getSourceManager().clearIDTables();
1061 if (Act
.BeginSourceFile(*this, FIF
)) {
1062 if (llvm::Error Err
= Act
.Execute()) {
1063 consumeError(std::move(Err
)); // FIXME this drops errors on the floor.
1065 Act
.EndSourceFile();
1069 printDiagnosticStats();
1071 if (getFrontendOpts().ShowStats
) {
1072 if (hasFileManager()) {
1073 getFileManager().PrintStats();
1076 llvm::PrintStatistics(OS
);
1078 StringRef StatsFile
= getFrontendOpts().StatsFile
;
1079 if (!StatsFile
.empty()) {
1080 llvm::sys::fs::OpenFlags FileFlags
= llvm::sys::fs::OF_TextWithCRLF
;
1081 if (getFrontendOpts().AppendStats
)
1082 FileFlags
|= llvm::sys::fs::OF_Append
;
1085 std::make_unique
<llvm::raw_fd_ostream
>(StatsFile
, EC
, FileFlags
);
1087 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file
)
1088 << StatsFile
<< EC
.message();
1090 llvm::PrintStatisticsJSON(*StatS
);
1094 return !getDiagnostics().getClient()->getNumErrors();
1097 void CompilerInstance::printDiagnosticStats() {
1098 if (!getDiagnosticOpts().ShowCarets
)
1101 raw_ostream
&OS
= getVerboseOutputStream();
1103 // We can have multiple diagnostics sharing one diagnostic client.
1104 // Get the total number of warnings/errors from the client.
1105 unsigned NumWarnings
= getDiagnostics().getClient()->getNumWarnings();
1106 unsigned NumErrors
= getDiagnostics().getClient()->getNumErrors();
1109 OS
<< NumWarnings
<< " warning" << (NumWarnings
== 1 ? "" : "s");
1110 if (NumWarnings
&& NumErrors
)
1113 OS
<< NumErrors
<< " error" << (NumErrors
== 1 ? "" : "s");
1114 if (NumWarnings
|| NumErrors
) {
1116 if (getLangOpts().CUDA
) {
1117 if (!getLangOpts().CUDAIsDevice
) {
1118 OS
<< " when compiling for host";
1120 OS
<< " when compiling for " << getTargetOpts().CPU
;
1127 void CompilerInstance::LoadRequestedPlugins() {
1128 // Load any requested plugins.
1129 for (const std::string
&Path
: getFrontendOpts().Plugins
) {
1131 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path
.c_str(), &Error
))
1132 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin
)
1136 // Check if any of the loaded plugins replaces the main AST action
1137 for (const FrontendPluginRegistry::entry
&Plugin
:
1138 FrontendPluginRegistry::entries()) {
1139 std::unique_ptr
<PluginASTAction
> P(Plugin
.instantiate());
1140 if (P
->getActionType() == PluginASTAction::ReplaceAction
) {
1141 getFrontendOpts().ProgramAction
= clang::frontend::PluginAction
;
1142 getFrontendOpts().ActionName
= Plugin
.getName().str();
1148 /// Determine the appropriate source input kind based on language
1150 static Language
getLanguageFromOptions(const LangOptions
&LangOpts
) {
1151 if (LangOpts
.OpenCL
)
1152 return Language::OpenCL
;
1154 return Language::CUDA
;
1156 return LangOpts
.CPlusPlus
? Language::ObjCXX
: Language::ObjC
;
1157 return LangOpts
.CPlusPlus
? Language::CXX
: Language::C
;
1160 /// Compile a module file for the given module, using the options
1161 /// provided by the importing compiler instance. Returns true if the module
1162 /// was built without errors.
1164 compileModuleImpl(CompilerInstance
&ImportingInstance
, SourceLocation ImportLoc
,
1165 StringRef ModuleName
, FrontendInputFile Input
,
1166 StringRef OriginalModuleMapFile
, StringRef ModuleFileName
,
1167 llvm::function_ref
<void(CompilerInstance
&)> PreBuildStep
=
1168 [](CompilerInstance
&) {},
1169 llvm::function_ref
<void(CompilerInstance
&)> PostBuildStep
=
1170 [](CompilerInstance
&) {}) {
1171 llvm::TimeTraceScope
TimeScope("Module Compile", ModuleName
);
1173 // Never compile a module that's already finalized - this would cause the
1174 // existing module to be freed, causing crashes if it is later referenced
1175 if (ImportingInstance
.getModuleCache().isPCMFinal(ModuleFileName
)) {
1176 ImportingInstance
.getDiagnostics().Report(
1177 ImportLoc
, diag::err_module_rebuild_finalized
)
1182 // Construct a compiler invocation for creating this module.
1184 std::make_shared
<CompilerInvocation
>(ImportingInstance
.getInvocation());
1186 PreprocessorOptions
&PPOpts
= Invocation
->getPreprocessorOpts();
1188 // For any options that aren't intended to affect how a module is built,
1189 // reset them to their default values.
1190 Invocation
->resetNonModularOptions();
1192 // Remove any macro definitions that are explicitly ignored by the module.
1193 // They aren't supposed to affect how the module is built anyway.
1194 HeaderSearchOptions
&HSOpts
= Invocation
->getHeaderSearchOpts();
1195 llvm::erase_if(PPOpts
.Macros
,
1196 [&HSOpts
](const std::pair
<std::string
, bool> &def
) {
1197 StringRef MacroDef
= def
.first
;
1198 return HSOpts
.ModulesIgnoreMacros
.contains(
1199 llvm::CachedHashString(MacroDef
.split('=').first
));
1202 // If the original compiler invocation had -fmodule-name, pass it through.
1203 Invocation
->getLangOpts().ModuleName
=
1204 ImportingInstance
.getInvocation().getLangOpts().ModuleName
;
1206 // Note the name of the module we're building.
1207 Invocation
->getLangOpts().CurrentModule
= std::string(ModuleName
);
1209 // If there is a module map file, build the module using the module map.
1210 // Set up the inputs/outputs so that we build the module from its umbrella
1212 FrontendOptions
&FrontendOpts
= Invocation
->getFrontendOpts();
1213 FrontendOpts
.OutputFile
= ModuleFileName
.str();
1214 FrontendOpts
.DisableFree
= false;
1215 FrontendOpts
.GenerateGlobalModuleIndex
= false;
1216 FrontendOpts
.BuildingImplicitModule
= true;
1217 FrontendOpts
.OriginalModuleMap
= std::string(OriginalModuleMapFile
);
1218 // Force implicitly-built modules to hash the content of the module file.
1219 HSOpts
.ModulesHashContent
= true;
1220 FrontendOpts
.Inputs
= {Input
};
1222 // Don't free the remapped file buffers; they are owned by our caller.
1223 PPOpts
.RetainRemappedFileBuffers
= true;
1225 DiagnosticOptions
&DiagOpts
= Invocation
->getDiagnosticOpts();
1227 DiagOpts
.VerifyDiagnostics
= 0;
1228 assert(ImportingInstance
.getInvocation().getModuleHash() ==
1229 Invocation
->getModuleHash() && "Module hash mismatch!");
1231 // Construct a compiler instance that will be used to actually create the
1232 // module. Since we're sharing an in-memory module cache,
1233 // CompilerInstance::CompilerInstance is responsible for finalizing the
1234 // buffers to prevent use-after-frees.
1235 CompilerInstance
Instance(ImportingInstance
.getPCHContainerOperations(),
1236 &ImportingInstance
.getModuleCache());
1237 auto &Inv
= *Invocation
;
1238 Instance
.setInvocation(std::move(Invocation
));
1240 Instance
.createDiagnostics(
1241 ImportingInstance
.getVirtualFileSystem(),
1242 new ForwardingDiagnosticConsumer(ImportingInstance
.getDiagnosticClient()),
1243 /*ShouldOwnClient=*/true);
1245 if (llvm::is_contained(DiagOpts
.SystemHeaderWarningsModules
, ModuleName
))
1246 Instance
.getDiagnostics().setSuppressSystemWarnings(false);
1248 if (FrontendOpts
.ModulesShareFileManager
) {
1249 Instance
.setFileManager(&ImportingInstance
.getFileManager());
1251 Instance
.createFileManager(&ImportingInstance
.getVirtualFileSystem());
1253 Instance
.createSourceManager(Instance
.getFileManager());
1254 SourceManager
&SourceMgr
= Instance
.getSourceManager();
1256 // Note that this module is part of the module build stack, so that we
1257 // can detect cycles in the module graph.
1258 SourceMgr
.setModuleBuildStack(
1259 ImportingInstance
.getSourceManager().getModuleBuildStack());
1260 SourceMgr
.pushModuleBuildStack(ModuleName
,
1261 FullSourceLoc(ImportLoc
, ImportingInstance
.getSourceManager()));
1263 // Make sure that the failed-module structure has been allocated in
1264 // the importing instance, and propagate the pointer to the newly-created
1266 if (!ImportingInstance
.hasFailedModulesSet())
1267 ImportingInstance
.createFailedModulesSet();
1268 Instance
.setFailedModulesSet(ImportingInstance
.getFailedModulesSetPtr());
1270 // If we're collecting module dependencies, we need to share a collector
1271 // between all of the module CompilerInstances. Other than that, we don't
1272 // want to produce any dependency output from the module build.
1273 Instance
.setModuleDepCollector(ImportingInstance
.getModuleDepCollector());
1274 Inv
.getDependencyOutputOpts() = DependencyOutputOptions();
1276 ImportingInstance
.getDiagnostics().Report(ImportLoc
,
1277 diag::remark_module_build
)
1278 << ModuleName
<< ModuleFileName
;
1280 PreBuildStep(Instance
);
1282 // Execute the action to actually build the module in-place. Use a separate
1283 // thread so that we get a stack large enough.
1284 bool Crashed
= !llvm::CrashRecoveryContext().RunSafelyOnThread(
1286 GenerateModuleFromModuleMapAction Action
;
1287 Instance
.ExecuteAction(Action
);
1291 PostBuildStep(Instance
);
1293 ImportingInstance
.getDiagnostics().Report(ImportLoc
,
1294 diag::remark_module_build_done
)
1297 // Propagate the statistics to the parent FileManager.
1298 if (!FrontendOpts
.ModulesShareFileManager
)
1299 ImportingInstance
.getFileManager().AddStats(Instance
.getFileManager());
1302 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1303 // that must be closed before clearing output files.
1304 Instance
.setSema(nullptr);
1305 Instance
.setASTConsumer(nullptr);
1307 // Delete any remaining temporary files related to Instance.
1308 Instance
.clearOutputFiles(/*EraseFiles=*/true);
1311 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1313 return !Instance
.getDiagnostics().hasErrorOccurred() ||
1314 Instance
.getFrontendOpts().AllowPCMWithCompilerErrors
;
1317 static OptionalFileEntryRef
getPublicModuleMap(FileEntryRef File
,
1318 FileManager
&FileMgr
) {
1319 StringRef Filename
= llvm::sys::path::filename(File
.getName());
1320 SmallString
<128> PublicFilename(File
.getDir().getName());
1321 if (Filename
== "module_private.map")
1322 llvm::sys::path::append(PublicFilename
, "module.map");
1323 else if (Filename
== "module.private.modulemap")
1324 llvm::sys::path::append(PublicFilename
, "module.modulemap");
1326 return std::nullopt
;
1327 return FileMgr
.getOptionalFileRef(PublicFilename
);
1330 /// Compile a module file for the given module in a separate compiler instance,
1331 /// using the options provided by the importing compiler instance. Returns true
1332 /// if the module was built without errors.
1333 static bool compileModule(CompilerInstance
&ImportingInstance
,
1334 SourceLocation ImportLoc
, Module
*Module
,
1335 StringRef ModuleFileName
) {
1336 InputKind
IK(getLanguageFromOptions(ImportingInstance
.getLangOpts()),
1337 InputKind::ModuleMap
);
1339 // Get or create the module map that we'll use to build this module.
1341 = ImportingInstance
.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1342 SourceManager
&SourceMgr
= ImportingInstance
.getSourceManager();
1344 if (FileID ModuleMapFID
= ModMap
.getContainingModuleMapFileID(Module
);
1345 ModuleMapFID
.isValid()) {
1346 // We want to use the top-level module map. If we don't, the compiling
1347 // instance may think the containing module map is a top-level one, while
1348 // the importing instance knows it's included from a parent module map via
1349 // the extern directive. This mismatch could bite us later.
1350 SourceLocation Loc
= SourceMgr
.getIncludeLoc(ModuleMapFID
);
1351 while (Loc
.isValid() && isModuleMap(SourceMgr
.getFileCharacteristic(Loc
))) {
1352 ModuleMapFID
= SourceMgr
.getFileID(Loc
);
1353 Loc
= SourceMgr
.getIncludeLoc(ModuleMapFID
);
1356 OptionalFileEntryRef ModuleMapFile
=
1357 SourceMgr
.getFileEntryRefForID(ModuleMapFID
);
1358 assert(ModuleMapFile
&& "Top-level module map with no FileID");
1360 // Canonicalize compilation to start with the public module map. This is
1361 // vital for submodules declarations in the private module maps to be
1362 // correctly parsed when depending on a top level module in the public one.
1363 if (OptionalFileEntryRef PublicMMFile
= getPublicModuleMap(
1364 *ModuleMapFile
, ImportingInstance
.getFileManager()))
1365 ModuleMapFile
= PublicMMFile
;
1367 StringRef ModuleMapFilePath
= ModuleMapFile
->getNameAsRequested();
1369 // Use the module map where this module resides.
1370 Result
= compileModuleImpl(
1371 ImportingInstance
, ImportLoc
, Module
->getTopLevelModuleName(),
1372 FrontendInputFile(ModuleMapFilePath
, IK
, +Module
->IsSystem
),
1373 ModMap
.getModuleMapFileForUniquing(Module
)->getName(), ModuleFileName
);
1375 // FIXME: We only need to fake up an input file here as a way of
1376 // transporting the module's directory to the module map parser. We should
1377 // be able to do that more directly, and parse from a memory buffer without
1378 // inventing this file.
1379 SmallString
<128> FakeModuleMapFile(Module
->Directory
->getName());
1380 llvm::sys::path::append(FakeModuleMapFile
, "__inferred_module.map");
1382 std::string InferredModuleMapContent
;
1383 llvm::raw_string_ostream
OS(InferredModuleMapContent
);
1386 Result
= compileModuleImpl(
1387 ImportingInstance
, ImportLoc
, Module
->getTopLevelModuleName(),
1388 FrontendInputFile(FakeModuleMapFile
, IK
, +Module
->IsSystem
),
1389 ModMap
.getModuleMapFileForUniquing(Module
)->getName(),
1391 [&](CompilerInstance
&Instance
) {
1392 std::unique_ptr
<llvm::MemoryBuffer
> ModuleMapBuffer
=
1393 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent
);
1394 FileEntryRef ModuleMapFile
= Instance
.getFileManager().getVirtualFileRef(
1395 FakeModuleMapFile
, InferredModuleMapContent
.size(), 0);
1396 Instance
.getSourceManager().overrideFileContents(
1397 ModuleMapFile
, std::move(ModuleMapBuffer
));
1401 // We've rebuilt a module. If we're allowed to generate or update the global
1402 // module index, record that fact in the importing compiler instance.
1403 if (ImportingInstance
.getFrontendOpts().GenerateGlobalModuleIndex
) {
1404 ImportingInstance
.setBuildGlobalModuleIndex(true);
1410 /// Read the AST right after compiling the module.
1411 static bool readASTAfterCompileModule(CompilerInstance
&ImportingInstance
,
1412 SourceLocation ImportLoc
,
1413 SourceLocation ModuleNameLoc
,
1414 Module
*Module
, StringRef ModuleFileName
,
1416 DiagnosticsEngine
&Diags
= ImportingInstance
.getDiagnostics();
1418 unsigned ModuleLoadCapabilities
= ASTReader::ARR_Missing
;
1420 ModuleLoadCapabilities
|= ASTReader::ARR_OutOfDate
;
1422 // Try to read the module file, now that we've compiled it.
1423 ASTReader::ASTReadResult ReadResult
=
1424 ImportingInstance
.getASTReader()->ReadAST(
1425 ModuleFileName
, serialization::MK_ImplicitModule
, ImportLoc
,
1426 ModuleLoadCapabilities
);
1427 if (ReadResult
== ASTReader::Success
)
1430 // The caller wants to handle out-of-date failures.
1431 if (OutOfDate
&& ReadResult
== ASTReader::OutOfDate
) {
1436 // The ASTReader didn't diagnose the error, so conservatively report it.
1437 if (ReadResult
== ASTReader::Missing
|| !Diags
.hasErrorOccurred())
1438 Diags
.Report(ModuleNameLoc
, diag::err_module_not_built
)
1439 << Module
->Name
<< SourceRange(ImportLoc
, ModuleNameLoc
);
1444 /// Compile a module in a separate compiler instance and read the AST,
1445 /// returning true if the module compiles without errors.
1446 static bool compileModuleAndReadASTImpl(CompilerInstance
&ImportingInstance
,
1447 SourceLocation ImportLoc
,
1448 SourceLocation ModuleNameLoc
,
1450 StringRef ModuleFileName
) {
1451 if (!compileModule(ImportingInstance
, ModuleNameLoc
, Module
,
1453 ImportingInstance
.getDiagnostics().Report(ModuleNameLoc
,
1454 diag::err_module_not_built
)
1455 << Module
->Name
<< SourceRange(ImportLoc
, ModuleNameLoc
);
1459 return readASTAfterCompileModule(ImportingInstance
, ImportLoc
, ModuleNameLoc
,
1460 Module
, ModuleFileName
,
1461 /*OutOfDate=*/nullptr);
1464 /// Compile a module in a separate compiler instance and read the AST,
1465 /// returning true if the module compiles without errors, using a lock manager
1466 /// to avoid building the same module in multiple compiler instances.
1468 /// Uses a lock file manager and exponential backoff to reduce the chances that
1469 /// multiple instances will compete to create the same module. On timeout,
1470 /// deletes the lock file in order to avoid deadlock from crashing processes or
1471 /// bugs in the lock file manager.
1472 static bool compileModuleAndReadASTBehindLock(
1473 CompilerInstance
&ImportingInstance
, SourceLocation ImportLoc
,
1474 SourceLocation ModuleNameLoc
, Module
*Module
, StringRef ModuleFileName
) {
1475 DiagnosticsEngine
&Diags
= ImportingInstance
.getDiagnostics();
1477 Diags
.Report(ModuleNameLoc
, diag::remark_module_lock
)
1478 << ModuleFileName
<< Module
->Name
;
1480 // FIXME: have LockFileManager return an error_code so that we can
1481 // avoid the mkdir when the directory already exists.
1482 StringRef Dir
= llvm::sys::path::parent_path(ModuleFileName
);
1483 llvm::sys::fs::create_directories(Dir
);
1486 llvm::LockFileManager
Locked(ModuleFileName
);
1488 case llvm::LockFileManager::LFS_Error
:
1489 // ModuleCache takes care of correctness and locks are only necessary for
1490 // performance. Fallback to building the module in case of any lock
1492 Diags
.Report(ModuleNameLoc
, diag::remark_module_lock_failure
)
1493 << Module
->Name
<< Locked
.getErrorMessage();
1494 // Clear out any potential leftover.
1495 Locked
.unsafeRemoveLockFile();
1497 case llvm::LockFileManager::LFS_Owned
:
1498 // We're responsible for building the module ourselves.
1499 return compileModuleAndReadASTImpl(ImportingInstance
, ImportLoc
,
1500 ModuleNameLoc
, Module
, ModuleFileName
);
1502 case llvm::LockFileManager::LFS_Shared
:
1503 break; // The interesting case.
1506 // Someone else is responsible for building the module. Wait for them to
1508 switch (Locked
.waitForUnlock()) {
1509 case llvm::LockFileManager::Res_Success
:
1510 break; // The interesting case.
1511 case llvm::LockFileManager::Res_OwnerDied
:
1512 continue; // try again to get the lock.
1513 case llvm::LockFileManager::Res_Timeout
:
1514 // Since ModuleCache takes care of correctness, we try waiting for
1515 // another process to complete the build so clang does not do it done
1516 // twice. If case of timeout, build it ourselves.
1517 Diags
.Report(ModuleNameLoc
, diag::remark_module_lock_timeout
)
1519 // Clear the lock file so that future invocations can make progress.
1520 Locked
.unsafeRemoveLockFile();
1524 // Read the module that was just written by someone else.
1525 bool OutOfDate
= false;
1526 if (readASTAfterCompileModule(ImportingInstance
, ImportLoc
, ModuleNameLoc
,
1527 Module
, ModuleFileName
, &OutOfDate
))
1532 // The module may be out of date in the presence of file system races,
1533 // or if one of its imports depends on header search paths that are not
1534 // consistent with this ImportingInstance. Try again...
1538 /// Compile a module in a separate compiler instance and read the AST,
1539 /// returning true if the module compiles without errors, potentially using a
1540 /// lock manager to avoid building the same module in multiple compiler
1542 static bool compileModuleAndReadAST(CompilerInstance
&ImportingInstance
,
1543 SourceLocation ImportLoc
,
1544 SourceLocation ModuleNameLoc
,
1545 Module
*Module
, StringRef ModuleFileName
) {
1546 return ImportingInstance
.getInvocation()
1548 .BuildingImplicitModuleUsesLock
1549 ? compileModuleAndReadASTBehindLock(ImportingInstance
, ImportLoc
,
1550 ModuleNameLoc
, Module
,
1552 : compileModuleAndReadASTImpl(ImportingInstance
, ImportLoc
,
1553 ModuleNameLoc
, Module
,
1557 /// Diagnose differences between the current definition of the given
1558 /// configuration macro and the definition provided on the command line.
1559 static void checkConfigMacro(Preprocessor
&PP
, StringRef ConfigMacro
,
1560 Module
*Mod
, SourceLocation ImportLoc
) {
1561 IdentifierInfo
*Id
= PP
.getIdentifierInfo(ConfigMacro
);
1562 SourceManager
&SourceMgr
= PP
.getSourceManager();
1564 // If this identifier has never had a macro definition, then it could
1565 // not have changed.
1566 if (!Id
->hadMacroDefinition())
1568 auto *LatestLocalMD
= PP
.getLocalMacroDirectiveHistory(Id
);
1570 // Find the macro definition from the command line.
1571 MacroInfo
*CmdLineDefinition
= nullptr;
1572 for (auto *MD
= LatestLocalMD
; MD
; MD
= MD
->getPrevious()) {
1573 // We only care about the predefines buffer.
1574 FileID FID
= SourceMgr
.getFileID(MD
->getLocation());
1575 if (FID
.isInvalid() || FID
!= PP
.getPredefinesFileID())
1577 if (auto *DMD
= dyn_cast
<DefMacroDirective
>(MD
))
1578 CmdLineDefinition
= DMD
->getMacroInfo();
1582 auto *CurrentDefinition
= PP
.getMacroInfo(Id
);
1583 if (CurrentDefinition
== CmdLineDefinition
) {
1584 // Macro matches. Nothing to do.
1585 } else if (!CurrentDefinition
) {
1586 // This macro was defined on the command line, then #undef'd later.
1588 PP
.Diag(ImportLoc
, diag::warn_module_config_macro_undef
)
1589 << true << ConfigMacro
<< Mod
->getFullModuleName();
1590 auto LatestDef
= LatestLocalMD
->getDefinition();
1591 assert(LatestDef
.isUndefined() &&
1592 "predefined macro went away with no #undef?");
1593 PP
.Diag(LatestDef
.getUndefLocation(), diag::note_module_def_undef_here
)
1596 } else if (!CmdLineDefinition
) {
1597 // There was no definition for this macro in the predefines buffer,
1598 // but there was a local definition. Complain.
1599 PP
.Diag(ImportLoc
, diag::warn_module_config_macro_undef
)
1600 << false << ConfigMacro
<< Mod
->getFullModuleName();
1601 PP
.Diag(CurrentDefinition
->getDefinitionLoc(),
1602 diag::note_module_def_undef_here
)
1604 } else if (!CurrentDefinition
->isIdenticalTo(*CmdLineDefinition
, PP
,
1605 /*Syntactically=*/true)) {
1606 // The macro definitions differ.
1607 PP
.Diag(ImportLoc
, diag::warn_module_config_macro_undef
)
1608 << false << ConfigMacro
<< Mod
->getFullModuleName();
1609 PP
.Diag(CurrentDefinition
->getDefinitionLoc(),
1610 diag::note_module_def_undef_here
)
1615 static void checkConfigMacros(Preprocessor
&PP
, Module
*M
,
1616 SourceLocation ImportLoc
) {
1617 clang::Module
*TopModule
= M
->getTopLevelModule();
1618 for (const StringRef ConMacro
: TopModule
->ConfigMacros
) {
1619 checkConfigMacro(PP
, ConMacro
, M
, ImportLoc
);
1623 /// Write a new timestamp file with the given path.
1624 static void writeTimestampFile(StringRef TimestampFile
) {
1626 llvm::raw_fd_ostream
Out(TimestampFile
.str(), EC
, llvm::sys::fs::OF_None
);
1629 /// Prune the module cache of modules that haven't been accessed in
1631 static void pruneModuleCache(const HeaderSearchOptions
&HSOpts
) {
1632 llvm::sys::fs::file_status StatBuf
;
1633 llvm::SmallString
<128> TimestampFile
;
1634 TimestampFile
= HSOpts
.ModuleCachePath
;
1635 assert(!TimestampFile
.empty());
1636 llvm::sys::path::append(TimestampFile
, "modules.timestamp");
1638 // Try to stat() the timestamp file.
1639 if (std::error_code EC
= llvm::sys::fs::status(TimestampFile
, StatBuf
)) {
1640 // If the timestamp file wasn't there, create one now.
1641 if (EC
== std::errc::no_such_file_or_directory
) {
1642 writeTimestampFile(TimestampFile
);
1647 // Check whether the time stamp is older than our pruning interval.
1648 // If not, do nothing.
1649 time_t TimeStampModTime
=
1650 llvm::sys::toTimeT(StatBuf
.getLastModificationTime());
1651 time_t CurrentTime
= time(nullptr);
1652 if (CurrentTime
- TimeStampModTime
<= time_t(HSOpts
.ModuleCachePruneInterval
))
1655 // Write a new timestamp file so that nobody else attempts to prune.
1656 // There is a benign race condition here, if two Clang instances happen to
1657 // notice at the same time that the timestamp is out-of-date.
1658 writeTimestampFile(TimestampFile
);
1660 // Walk the entire module cache, looking for unused module files and module
1663 for (llvm::sys::fs::directory_iterator
Dir(HSOpts
.ModuleCachePath
, EC
),
1665 Dir
!= DirEnd
&& !EC
; Dir
.increment(EC
)) {
1666 // If we don't have a directory, there's nothing to look into.
1667 if (!llvm::sys::fs::is_directory(Dir
->path()))
1670 // Walk all of the files within this directory.
1671 for (llvm::sys::fs::directory_iterator
File(Dir
->path(), EC
), FileEnd
;
1672 File
!= FileEnd
&& !EC
; File
.increment(EC
)) {
1673 // We only care about module and global module index files.
1674 StringRef Extension
= llvm::sys::path::extension(File
->path());
1675 if (Extension
!= ".pcm" && Extension
!= ".timestamp" &&
1676 llvm::sys::path::filename(File
->path()) != "modules.idx")
1679 // Look at this file. If we can't stat it, there's nothing interesting
1681 if (llvm::sys::fs::status(File
->path(), StatBuf
))
1684 // If the file has been used recently enough, leave it there.
1685 time_t FileAccessTime
= llvm::sys::toTimeT(StatBuf
.getLastAccessedTime());
1686 if (CurrentTime
- FileAccessTime
<=
1687 time_t(HSOpts
.ModuleCachePruneAfter
)) {
1692 llvm::sys::fs::remove(File
->path());
1694 // Remove the timestamp file.
1695 std::string TimpestampFilename
= File
->path() + ".timestamp";
1696 llvm::sys::fs::remove(TimpestampFilename
);
1699 // If we removed all of the files in the directory, remove the directory
1701 if (llvm::sys::fs::directory_iterator(Dir
->path(), EC
) ==
1702 llvm::sys::fs::directory_iterator() && !EC
)
1703 llvm::sys::fs::remove(Dir
->path());
1707 void CompilerInstance::createASTReader() {
1711 if (!hasASTContext())
1714 // If we're implicitly building modules but not currently recursively
1715 // building a module, check whether we need to prune the module cache.
1716 if (getSourceManager().getModuleBuildStack().empty() &&
1717 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1718 getHeaderSearchOpts().ModuleCachePruneInterval
> 0 &&
1719 getHeaderSearchOpts().ModuleCachePruneAfter
> 0) {
1720 pruneModuleCache(getHeaderSearchOpts());
1723 HeaderSearchOptions
&HSOpts
= getHeaderSearchOpts();
1724 std::string Sysroot
= HSOpts
.Sysroot
;
1725 const PreprocessorOptions
&PPOpts
= getPreprocessorOpts();
1726 const FrontendOptions
&FEOpts
= getFrontendOpts();
1727 std::unique_ptr
<llvm::Timer
> ReadTimer
;
1729 if (FrontendTimerGroup
)
1730 ReadTimer
= std::make_unique
<llvm::Timer
>("reading_modules",
1732 *FrontendTimerGroup
);
1733 TheASTReader
= new ASTReader(
1734 getPreprocessor(), getModuleCache(), &getASTContext(),
1735 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions
,
1736 Sysroot
.empty() ? "" : Sysroot
.c_str(),
1737 PPOpts
.DisablePCHOrModuleValidation
,
1738 /*AllowASTWithCompilerErrors=*/FEOpts
.AllowPCMWithCompilerErrors
,
1739 /*AllowConfigurationMismatch=*/false, HSOpts
.ModulesValidateSystemHeaders
,
1740 HSOpts
.ValidateASTInputFilesContent
,
1741 getFrontendOpts().UseGlobalModuleIndex
, std::move(ReadTimer
));
1742 if (hasASTConsumer()) {
1743 TheASTReader
->setDeserializationListener(
1744 getASTConsumer().GetASTDeserializationListener());
1745 getASTContext().setASTMutationListener(
1746 getASTConsumer().GetASTMutationListener());
1748 getASTContext().setExternalSource(TheASTReader
);
1750 TheASTReader
->InitializeSema(getSema());
1751 if (hasASTConsumer())
1752 TheASTReader
->StartTranslationUnit(&getASTConsumer());
1754 for (auto &Listener
: DependencyCollectors
)
1755 Listener
->attachToASTReader(*TheASTReader
);
1758 bool CompilerInstance::loadModuleFile(
1759 StringRef FileName
, serialization::ModuleFile
*&LoadedModuleFile
) {
1761 if (FrontendTimerGroup
)
1762 Timer
.init("preloading." + FileName
.str(), "Preloading " + FileName
.str(),
1763 *FrontendTimerGroup
);
1764 llvm::TimeRegion
TimeLoading(FrontendTimerGroup
? &Timer
: nullptr);
1766 // If we don't already have an ASTReader, create one now.
1770 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1771 // ASTReader to diagnose it, since it can produce better errors that we can.
1772 bool ConfigMismatchIsRecoverable
=
1773 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch
,
1775 <= DiagnosticsEngine::Warning
;
1777 auto Listener
= std::make_unique
<ReadModuleNames
>(*PP
);
1778 auto &ListenerRef
= *Listener
;
1779 ASTReader::ListenerScope
ReadModuleNamesListener(*TheASTReader
,
1780 std::move(Listener
));
1782 // Try to load the module file.
1783 switch (TheASTReader
->ReadAST(
1784 FileName
, serialization::MK_ExplicitModule
, SourceLocation(),
1785 ConfigMismatchIsRecoverable
? ASTReader::ARR_ConfigurationMismatch
: 0,
1786 &LoadedModuleFile
)) {
1787 case ASTReader::Success
:
1788 // We successfully loaded the module file; remember the set of provided
1789 // modules so that we don't try to load implicit modules for them.
1790 ListenerRef
.registerAll();
1793 case ASTReader::ConfigurationMismatch
:
1794 // Ignore unusable module files.
1795 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch
)
1797 // All modules provided by any files we tried and failed to load are now
1798 // unavailable; includes of those modules should now be handled textually.
1799 ListenerRef
.markAllUnavailable();
1811 MS_PrebuiltModulePath
,
1812 MS_ModuleBuildPragma
1816 /// Select a source for loading the named module and compute the filename to
1818 static ModuleSource
selectModuleSource(
1819 Module
*M
, StringRef ModuleName
, std::string
&ModuleFilename
,
1820 const std::map
<std::string
, std::string
, std::less
<>> &BuiltModules
,
1822 assert(ModuleFilename
.empty() && "Already has a module source?");
1824 // Check to see if the module has been built as part of this compilation
1825 // via a module build pragma.
1826 auto BuiltModuleIt
= BuiltModules
.find(ModuleName
);
1827 if (BuiltModuleIt
!= BuiltModules
.end()) {
1828 ModuleFilename
= BuiltModuleIt
->second
;
1829 return MS_ModuleBuildPragma
;
1832 // Try to load the module from the prebuilt module path.
1833 const HeaderSearchOptions
&HSOpts
= HS
.getHeaderSearchOpts();
1834 if (!HSOpts
.PrebuiltModuleFiles
.empty() ||
1835 !HSOpts
.PrebuiltModulePaths
.empty()) {
1836 ModuleFilename
= HS
.getPrebuiltModuleFileName(ModuleName
);
1837 if (HSOpts
.EnablePrebuiltImplicitModules
&& ModuleFilename
.empty())
1838 ModuleFilename
= HS
.getPrebuiltImplicitModuleFileName(M
);
1839 if (!ModuleFilename
.empty())
1840 return MS_PrebuiltModulePath
;
1843 // Try to load the module from the module cache.
1845 ModuleFilename
= HS
.getCachedModuleFileName(M
);
1846 return MS_ModuleCache
;
1849 return MS_ModuleNotFound
;
1852 ModuleLoadResult
CompilerInstance::findOrCompileModuleAndReadAST(
1853 StringRef ModuleName
, SourceLocation ImportLoc
,
1854 SourceLocation ModuleNameLoc
, bool IsInclusionDirective
) {
1855 // Search for a module with the given name.
1856 HeaderSearch
&HS
= PP
->getHeaderSearchInfo();
1858 HS
.lookupModule(ModuleName
, ImportLoc
, true, !IsInclusionDirective
);
1860 // Check for any configuration macros that have changed. This is done
1861 // immediately before potentially building a module in case this module
1862 // depends on having one of its configuration macros defined to successfully
1863 // build. If this is not done the user will never see the warning.
1865 checkConfigMacros(getPreprocessor(), M
, ImportLoc
);
1867 // Select the source and filename for loading the named module.
1868 std::string ModuleFilename
;
1869 ModuleSource Source
=
1870 selectModuleSource(M
, ModuleName
, ModuleFilename
, BuiltModules
, HS
);
1871 if (Source
== MS_ModuleNotFound
) {
1872 // We can't find a module, error out here.
1873 getDiagnostics().Report(ModuleNameLoc
, diag::err_module_not_found
)
1874 << ModuleName
<< SourceRange(ImportLoc
, ModuleNameLoc
);
1877 if (ModuleFilename
.empty()) {
1878 if (M
&& M
->HasIncompatibleModuleFile
) {
1879 // We tried and failed to load a module file for this module. Fall
1880 // back to textual inclusion for its headers.
1881 return ModuleLoadResult::ConfigMismatch
;
1884 getDiagnostics().Report(ModuleNameLoc
, diag::err_module_build_disabled
)
1889 // Create an ASTReader on demand.
1890 if (!getASTReader())
1893 // Time how long it takes to load the module.
1895 if (FrontendTimerGroup
)
1896 Timer
.init("loading." + ModuleFilename
, "Loading " + ModuleFilename
,
1897 *FrontendTimerGroup
);
1898 llvm::TimeRegion
TimeLoading(FrontendTimerGroup
? &Timer
: nullptr);
1899 llvm::TimeTraceScope
TimeScope("Module Load", ModuleName
);
1901 // Try to load the module file. If we are not trying to load from the
1902 // module cache, we don't know how to rebuild modules.
1903 unsigned ARRFlags
= Source
== MS_ModuleCache
1904 ? ASTReader::ARR_OutOfDate
| ASTReader::ARR_Missing
|
1905 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1906 : Source
== MS_PrebuiltModulePath
1908 : ASTReader::ARR_ConfigurationMismatch
;
1909 switch (getASTReader()->ReadAST(ModuleFilename
,
1910 Source
== MS_PrebuiltModulePath
1911 ? serialization::MK_PrebuiltModule
1912 : Source
== MS_ModuleBuildPragma
1913 ? serialization::MK_ExplicitModule
1914 : serialization::MK_ImplicitModule
,
1915 ImportLoc
, ARRFlags
)) {
1916 case ASTReader::Success
: {
1919 assert(Source
!= MS_ModuleCache
&&
1920 "missing module, but file loaded from cache");
1922 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1923 // until the first call to ReadAST. Look it up now.
1924 M
= HS
.lookupModule(ModuleName
, ImportLoc
, true, !IsInclusionDirective
);
1926 // Check whether M refers to the file in the prebuilt module path.
1927 if (M
&& M
->getASTFile())
1928 if (auto ModuleFile
= FileMgr
->getOptionalFileRef(ModuleFilename
))
1929 if (*ModuleFile
== M
->getASTFile())
1932 getDiagnostics().Report(ModuleNameLoc
, diag::err_module_prebuilt
)
1934 return ModuleLoadResult();
1937 case ASTReader::OutOfDate
:
1938 case ASTReader::Missing
:
1939 // The most interesting case.
1942 case ASTReader::ConfigurationMismatch
:
1943 if (Source
== MS_PrebuiltModulePath
)
1944 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1945 // produce a warning here!
1946 getDiagnostics().Report(SourceLocation(),
1947 diag::warn_module_config_mismatch
)
1949 // Fall through to error out.
1951 case ASTReader::VersionMismatch
:
1952 case ASTReader::HadErrors
:
1953 ModuleLoader::HadFatalFailure
= true;
1954 // FIXME: The ASTReader will already have complained, but can we shoehorn
1955 // that diagnostic information into a more useful form?
1956 return ModuleLoadResult();
1958 case ASTReader::Failure
:
1959 ModuleLoader::HadFatalFailure
= true;
1960 return ModuleLoadResult();
1963 // ReadAST returned Missing or OutOfDate.
1964 if (Source
!= MS_ModuleCache
) {
1965 // We don't know the desired configuration for this module and don't
1966 // necessarily even have a module map. Since ReadAST already produces
1967 // diagnostics for these two cases, we simply error out here.
1968 return ModuleLoadResult();
1971 // The module file is missing or out-of-date. Build it.
1972 assert(M
&& "missing module, but trying to compile for cache");
1974 // Check whether there is a cycle in the module graph.
1975 ModuleBuildStack ModPath
= getSourceManager().getModuleBuildStack();
1976 ModuleBuildStack::iterator Pos
= ModPath
.begin(), PosEnd
= ModPath
.end();
1977 for (; Pos
!= PosEnd
; ++Pos
) {
1978 if (Pos
->first
== ModuleName
)
1982 if (Pos
!= PosEnd
) {
1983 SmallString
<256> CyclePath
;
1984 for (; Pos
!= PosEnd
; ++Pos
) {
1985 CyclePath
+= Pos
->first
;
1986 CyclePath
+= " -> ";
1988 CyclePath
+= ModuleName
;
1990 getDiagnostics().Report(ModuleNameLoc
, diag::err_module_cycle
)
1991 << ModuleName
<< CyclePath
;
1995 // Check whether we have already attempted to build this module (but failed).
1996 if (FailedModules
&& FailedModules
->hasAlreadyFailed(ModuleName
)) {
1997 getDiagnostics().Report(ModuleNameLoc
, diag::err_module_not_built
)
1998 << ModuleName
<< SourceRange(ImportLoc
, ModuleNameLoc
);
2002 // Try to compile and then read the AST.
2003 if (!compileModuleAndReadAST(*this, ImportLoc
, ModuleNameLoc
, M
,
2005 assert(getDiagnostics().hasErrorOccurred() &&
2006 "undiagnosed error in compileModuleAndReadAST");
2008 FailedModules
->addFailed(ModuleName
);
2012 // Okay, we've rebuilt and now loaded the module.
2017 CompilerInstance::loadModule(SourceLocation ImportLoc
,
2019 Module::NameVisibilityKind Visibility
,
2020 bool IsInclusionDirective
) {
2021 // Determine what file we're searching from.
2022 StringRef ModuleName
= Path
[0].first
->getName();
2023 SourceLocation ModuleNameLoc
= Path
[0].second
;
2025 // If we've already handled this import, just return the cached result.
2026 // This one-element cache is important to eliminate redundant diagnostics
2027 // when both the preprocessor and parser see the same import declaration.
2028 if (ImportLoc
.isValid() && LastModuleImportLoc
== ImportLoc
) {
2029 // Make the named module visible.
2030 if (LastModuleImportResult
&& ModuleName
!= getLangOpts().CurrentModule
)
2031 TheASTReader
->makeModuleVisible(LastModuleImportResult
, Visibility
,
2033 return LastModuleImportResult
;
2036 // If we don't already have information on this module, load the module now.
2037 Module
*Module
= nullptr;
2038 ModuleMap
&MM
= getPreprocessor().getHeaderSearchInfo().getModuleMap();
2039 if (auto MaybeModule
= MM
.getCachedModuleLoad(*Path
[0].first
)) {
2040 // Use the cached result, which may be nullptr.
2041 Module
= *MaybeModule
;
2042 // Config macros are already checked before building a module, but they need
2043 // to be checked at each import location in case any of the config macros
2044 // have a new value at the current `ImportLoc`.
2046 checkConfigMacros(getPreprocessor(), Module
, ImportLoc
);
2047 } else if (ModuleName
== getLangOpts().CurrentModule
) {
2048 // This is the module we're building.
2049 Module
= PP
->getHeaderSearchInfo().lookupModule(
2050 ModuleName
, ImportLoc
, /*AllowSearch*/ true,
2051 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective
);
2053 // Config macros do not need to be checked here for two reasons.
2054 // * This will always be textual inclusion, and thus the config macros
2055 // actually do impact the content of the header.
2056 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2057 // function as the `#include` or `#import` is textual.
2059 MM
.cacheModuleLoad(*Path
[0].first
, Module
);
2061 ModuleLoadResult Result
= findOrCompileModuleAndReadAST(
2062 ModuleName
, ImportLoc
, ModuleNameLoc
, IsInclusionDirective
);
2063 if (!Result
.isNormal())
2066 DisableGeneratingGlobalModuleIndex
= true;
2068 MM
.cacheModuleLoad(*Path
[0].first
, Module
);
2071 // If we never found the module, fail. Otherwise, verify the module and link
2074 return ModuleLoadResult();
2076 // Verify that the rest of the module path actually corresponds to
2078 bool MapPrivateSubModToTopLevel
= false;
2079 for (unsigned I
= 1, N
= Path
.size(); I
!= N
; ++I
) {
2080 StringRef Name
= Path
[I
].first
->getName();
2081 clang::Module
*Sub
= Module
->findSubmodule(Name
);
2083 // If the user is requesting Foo.Private and it doesn't exist, try to
2084 // match Foo_Private and emit a warning asking for the user to write
2085 // @import Foo_Private instead. FIXME: remove this when existing clients
2086 // migrate off of Foo.Private syntax.
2087 if (!Sub
&& Name
== "Private" && Module
== Module
->getTopLevelModule()) {
2088 SmallString
<128> PrivateModule(Module
->Name
);
2089 PrivateModule
.append("_Private");
2091 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> PrivPath
;
2092 auto &II
= PP
->getIdentifierTable().get(
2093 PrivateModule
, PP
->getIdentifierInfo(Module
->Name
)->getTokenID());
2094 PrivPath
.push_back(std::make_pair(&II
, Path
[0].second
));
2096 std::string FileName
;
2097 // If there is a modulemap module or prebuilt module, load it.
2098 if (PP
->getHeaderSearchInfo().lookupModule(PrivateModule
, ImportLoc
, true,
2099 !IsInclusionDirective
) ||
2100 selectModuleSource(nullptr, PrivateModule
, FileName
, BuiltModules
,
2101 PP
->getHeaderSearchInfo()) != MS_ModuleNotFound
)
2102 Sub
= loadModule(ImportLoc
, PrivPath
, Visibility
, IsInclusionDirective
);
2104 MapPrivateSubModToTopLevel
= true;
2105 PP
->markClangModuleAsAffecting(Module
);
2106 if (!getDiagnostics().isIgnored(
2107 diag::warn_no_priv_submodule_use_toplevel
, ImportLoc
)) {
2108 getDiagnostics().Report(Path
[I
].second
,
2109 diag::warn_no_priv_submodule_use_toplevel
)
2110 << Path
[I
].first
<< Module
->getFullModuleName() << PrivateModule
2111 << SourceRange(Path
[0].second
, Path
[I
].second
)
2112 << FixItHint::CreateReplacement(SourceRange(Path
[0].second
),
2114 getDiagnostics().Report(Sub
->DefinitionLoc
,
2115 diag::note_private_top_level_defined
);
2121 // Attempt to perform typo correction to find a module name that works.
2122 SmallVector
<StringRef
, 2> Best
;
2123 unsigned BestEditDistance
= (std::numeric_limits
<unsigned>::max
)();
2125 for (class Module
*SubModule
: Module
->submodules()) {
2127 Name
.edit_distance(SubModule
->Name
,
2128 /*AllowReplacements=*/true, BestEditDistance
);
2129 if (ED
<= BestEditDistance
) {
2130 if (ED
< BestEditDistance
) {
2132 BestEditDistance
= ED
;
2135 Best
.push_back(SubModule
->Name
);
2139 // If there was a clear winner, user it.
2140 if (Best
.size() == 1) {
2141 getDiagnostics().Report(Path
[I
].second
, diag::err_no_submodule_suggest
)
2142 << Path
[I
].first
<< Module
->getFullModuleName() << Best
[0]
2143 << SourceRange(Path
[0].second
, Path
[I
- 1].second
)
2144 << FixItHint::CreateReplacement(SourceRange(Path
[I
].second
),
2147 Sub
= Module
->findSubmodule(Best
[0]);
2152 // No submodule by this name. Complain, and don't look for further
2154 getDiagnostics().Report(Path
[I
].second
, diag::err_no_submodule
)
2155 << Path
[I
].first
<< Module
->getFullModuleName()
2156 << SourceRange(Path
[0].second
, Path
[I
- 1].second
);
2163 // Make the named module visible, if it's not already part of the module
2165 if (ModuleName
!= getLangOpts().CurrentModule
) {
2166 if (!Module
->IsFromModuleFile
&& !MapPrivateSubModToTopLevel
) {
2167 // We have an umbrella header or directory that doesn't actually include
2168 // all of the headers within the directory it covers. Complain about
2169 // this missing submodule and recover by forgetting that we ever saw
2171 // FIXME: Should we detect this at module load time? It seems fairly
2172 // expensive (and rare).
2173 getDiagnostics().Report(ImportLoc
, diag::warn_missing_submodule
)
2174 << Module
->getFullModuleName()
2175 << SourceRange(Path
.front().second
, Path
.back().second
);
2177 return ModuleLoadResult(Module
, ModuleLoadResult::MissingExpected
);
2180 // Check whether this module is available.
2181 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2182 *Module
, getDiagnostics())) {
2183 getDiagnostics().Report(ImportLoc
, diag::note_module_import_here
)
2184 << SourceRange(Path
.front().second
, Path
.back().second
);
2185 LastModuleImportLoc
= ImportLoc
;
2186 LastModuleImportResult
= ModuleLoadResult();
2187 return ModuleLoadResult();
2190 TheASTReader
->makeModuleVisible(Module
, Visibility
, ImportLoc
);
2193 // Resolve any remaining module using export_as for this one.
2195 .getHeaderSearchInfo()
2197 .resolveLinkAsDependencies(Module
->getTopLevelModule());
2199 LastModuleImportLoc
= ImportLoc
;
2200 LastModuleImportResult
= ModuleLoadResult(Module
);
2201 return LastModuleImportResult
;
2204 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc
,
2205 StringRef ModuleName
,
2207 // Avoid creating filenames with special characters.
2208 SmallString
<128> CleanModuleName(ModuleName
);
2209 for (auto &C
: CleanModuleName
)
2210 if (!isAlphanumeric(C
))
2213 // FIXME: Using a randomized filename here means that our intermediate .pcm
2214 // output is nondeterministic (as .pcm files refer to each other by name).
2215 // Can this affect the output in any way?
2216 SmallString
<128> ModuleFileName
;
2217 if (std::error_code EC
= llvm::sys::fs::createTemporaryFile(
2218 CleanModuleName
, "pcm", ModuleFileName
)) {
2219 getDiagnostics().Report(ImportLoc
, diag::err_fe_unable_to_open_output
)
2220 << ModuleFileName
<< EC
.message();
2223 std::string ModuleMapFileName
= (CleanModuleName
+ ".map").str();
2225 FrontendInputFile
Input(
2227 InputKind(getLanguageFromOptions(Invocation
->getLangOpts()),
2228 InputKind::ModuleMap
, /*Preprocessed*/true));
2230 std::string
NullTerminatedSource(Source
.str());
2232 auto PreBuildStep
= [&](CompilerInstance
&Other
) {
2233 // Create a virtual file containing our desired source.
2234 // FIXME: We shouldn't need to do this.
2235 FileEntryRef ModuleMapFile
= Other
.getFileManager().getVirtualFileRef(
2236 ModuleMapFileName
, NullTerminatedSource
.size(), 0);
2237 Other
.getSourceManager().overrideFileContents(
2238 ModuleMapFile
, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource
));
2240 Other
.BuiltModules
= std::move(BuiltModules
);
2241 Other
.DeleteBuiltModules
= false;
2244 auto PostBuildStep
= [this](CompilerInstance
&Other
) {
2245 BuiltModules
= std::move(Other
.BuiltModules
);
2248 // Build the module, inheriting any modules that we've built locally.
2249 if (compileModuleImpl(*this, ImportLoc
, ModuleName
, Input
, StringRef(),
2250 ModuleFileName
, PreBuildStep
, PostBuildStep
)) {
2251 BuiltModules
[std::string(ModuleName
)] = std::string(ModuleFileName
);
2252 llvm::sys::RemoveFileOnSignal(ModuleFileName
);
2256 void CompilerInstance::makeModuleVisible(Module
*Mod
,
2257 Module::NameVisibilityKind Visibility
,
2258 SourceLocation ImportLoc
) {
2264 TheASTReader
->makeModuleVisible(Mod
, Visibility
, ImportLoc
);
2267 GlobalModuleIndex
*CompilerInstance::loadGlobalModuleIndex(
2268 SourceLocation TriggerLoc
) {
2269 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2273 // Can't do anything if we don't have the module manager.
2276 // Get an existing global index. This loads it if not already
2278 TheASTReader
->loadGlobalIndex();
2279 GlobalModuleIndex
*GlobalIndex
= TheASTReader
->getGlobalIndex();
2280 // If the global index doesn't exist, create it.
2281 if (!GlobalIndex
&& shouldBuildGlobalModuleIndex() && hasFileManager() &&
2282 hasPreprocessor()) {
2283 llvm::sys::fs::create_directories(
2284 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2285 if (llvm::Error Err
= GlobalModuleIndex::writeIndex(
2286 getFileManager(), getPCHContainerReader(),
2287 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2288 // FIXME this drops the error on the floor. This code is only used for
2289 // typo correction and drops more than just this one source of errors
2290 // (such as the directory creation failure above). It should handle the
2292 consumeError(std::move(Err
));
2295 TheASTReader
->resetForReload();
2296 TheASTReader
->loadGlobalIndex();
2297 GlobalIndex
= TheASTReader
->getGlobalIndex();
2299 // For finding modules needing to be imported for fixit messages,
2300 // we need to make the global index cover all modules, so we do that here.
2301 if (!HaveFullGlobalModuleIndex
&& GlobalIndex
&& !buildingModule()) {
2302 ModuleMap
&MMap
= getPreprocessor().getHeaderSearchInfo().getModuleMap();
2303 bool RecreateIndex
= false;
2304 for (ModuleMap::module_iterator I
= MMap
.module_begin(),
2305 E
= MMap
.module_end(); I
!= E
; ++I
) {
2306 Module
*TheModule
= I
->second
;
2307 OptionalFileEntryRef Entry
= TheModule
->getASTFile();
2309 SmallVector
<std::pair
<IdentifierInfo
*, SourceLocation
>, 2> Path
;
2310 Path
.push_back(std::make_pair(
2311 getPreprocessor().getIdentifierInfo(TheModule
->Name
), TriggerLoc
));
2312 std::reverse(Path
.begin(), Path
.end());
2313 // Load a module as hidden. This also adds it to the global index.
2314 loadModule(TheModule
->DefinitionLoc
, Path
, Module::Hidden
, false);
2315 RecreateIndex
= true;
2318 if (RecreateIndex
) {
2319 if (llvm::Error Err
= GlobalModuleIndex::writeIndex(
2320 getFileManager(), getPCHContainerReader(),
2321 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2322 // FIXME As above, this drops the error on the floor.
2323 consumeError(std::move(Err
));
2326 TheASTReader
->resetForReload();
2327 TheASTReader
->loadGlobalIndex();
2328 GlobalIndex
= TheASTReader
->getGlobalIndex();
2330 HaveFullGlobalModuleIndex
= true;
2335 // Check global module index for missing imports.
2337 CompilerInstance::lookupMissingImports(StringRef Name
,
2338 SourceLocation TriggerLoc
) {
2339 // Look for the symbol in non-imported modules, but only if an error
2340 // actually occurred.
2341 if (!buildingModule()) {
2342 // Load global module index, or retrieve a previously loaded one.
2343 GlobalModuleIndex
*GlobalIndex
= loadGlobalModuleIndex(
2346 // Only if we have a global index.
2348 GlobalModuleIndex::HitSet FoundModules
;
2350 // Find the modules that reference the identifier.
2351 // Note that this only finds top-level modules.
2352 // We'll let diagnoseTypo find the actual declaration module.
2353 if (GlobalIndex
->lookupIdentifier(Name
, FoundModules
))
2360 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2362 void CompilerInstance::setExternalSemaSource(
2363 IntrusiveRefCntPtr
<ExternalSemaSource
> ESS
) {
2364 ExternalSemaSrc
= std::move(ESS
);