Debian Codegraph @

clang/lib/Frontend/CompilerInstance.cpp

raw
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 //===----------------------------------------------------------------------===//
8
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/DiagnosticFrontend.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/LangStandard.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/Stack.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Config/config.h"
24 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
25 #include "clang/Frontend/FrontendAction.h"
26 #include "clang/Frontend/FrontendActions.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/ParsedAttr.h"
39 #include "clang/Sema/Sema.h"
40 #include "clang/Serialization/ASTReader.h"
41 #include "clang/Serialization/GlobalModuleIndex.h"
42 #include "clang/Serialization/InMemoryModuleCache.h"
43 #include "clang/Serialization/ModuleCache.h"
44 #include "clang/Serialization/SerializationDiagnostic.h"
45 #include "llvm/ADT/IntrusiveRefCntPtr.h"
46 #include "llvm/ADT/STLExtras.h"
47 #include "llvm/ADT/ScopeExit.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Config/llvm-config.h"
50 #include "llvm/Plugins/PassPlugin.h"
51 #include "llvm/Support/AdvisoryLock.h"
52 #include "llvm/Support/BuryPointer.h"
53 #include "llvm/Support/CrashRecoveryContext.h"
54 #include "llvm/Support/Errc.h"
55 #include "llvm/Support/FileSystem.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 #include "llvm/Support/Path.h"
58 #include "llvm/Support/Signals.h"
59 #include "llvm/Support/TimeProfiler.h"
60 #include "llvm/Support/Timer.h"
61 #include "llvm/Support/VirtualFileSystem.h"
62 #include "llvm/Support/VirtualOutputBackends.h"
63 #include "llvm/Support/VirtualOutputError.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/TargetParser/Host.h"
66 #include <optional>
67 #include <time.h>
68 #include <utility>
69
70 using namespace clang;
71
72 CompilerInstance::CompilerInstance(
73 std::shared_ptr<CompilerInvocation> Invocation,
74 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
75 std::shared_ptr<ModuleCache> ModCache)
76 : ModuleLoader(/*BuildingModule=*/ModCache != nullptr),
77 Invocation(std::move(Invocation)),
78 ModCache(ModCache ? std::move(ModCache)
79 : createCrossProcessModuleCache()),
80 ThePCHContainerOperations(std::move(PCHContainerOps)) {
81 assert(this->Invocation && "Invocation must not be null");
82 }
83
84 CompilerInstance::~CompilerInstance() {
85 assert(OutputFiles.empty() && "Still output files in flight?");
86 }
87
88 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
89 return (BuildGlobalModuleIndex ||
90 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
91 getFrontendOpts().GenerateGlobalModuleIndex)) &&
92 !DisableGeneratingGlobalModuleIndex;
93 }
94
95 void CompilerInstance::setDiagnostics(
96 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Value) {
97 Diagnostics = std::move(Value);
98 }
99
100 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
101 OwnedVerboseOutputStream.reset();
102 VerboseOutputStream = &Value;
103 }
104
105 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
106 OwnedVerboseOutputStream.swap(Value);
107 VerboseOutputStream = OwnedVerboseOutputStream.get();
108 }
109
110 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
111 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
112
113 bool CompilerInstance::createTarget() {
114 // Create the target instance.
115 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
116 getInvocation().getTargetOpts()));
117 if (!hasTarget())
118 return false;
119
120 // Check whether AuxTarget exists, if not, then create TargetInfo for the
121 // other side of CUDA/OpenMP/SYCL compilation.
122 if (!getAuxTarget() &&
123 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
124 !getFrontendOpts().AuxTriple.empty()) {
125 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
126 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
127 if (getFrontendOpts().AuxTargetCPU)
128 TO->CPU = *getFrontendOpts().AuxTargetCPU;
129 if (getFrontendOpts().AuxTargetFeatures)
130 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
131 TO->HostTriple = getTarget().getTriple().str();
132 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), *TO));
133 }
134
135 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
136 if (getLangOpts().RoundingMath) {
137 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
138 getLangOpts().RoundingMath = false;
139 }
140 auto FPExc = getLangOpts().getFPExceptionMode();
141 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
142 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
143 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
144 }
145 // FIXME: can we disable FEnvAccess?
146 }
147
148 // We should do it here because target knows nothing about
149 // language options when it's being created.
150 if (getLangOpts().OpenCL &&
151 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
152 return false;
153
154 // Inform the target of the language options.
155 // FIXME: We shouldn't need to do this, the target should be immutable once
156 // created. This complexity should be lifted elsewhere.
157 getTarget().adjust(getDiagnostics(), getLangOpts(), getAuxTarget());
158
159 if (auto *Aux = getAuxTarget())
160 getTarget().setAuxTarget(Aux);
161
162 return true;
163 }
164
165 void CompilerInstance::setFileManager(IntrusiveRefCntPtr<FileManager> Value) {
166 assert(Value == nullptr ||
167 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
168 FileMgr = std::move(Value);
169 }
170
171 void CompilerInstance::setSourceManager(
172 llvm::IntrusiveRefCntPtr<SourceManager> Value) {
173 SourceMgr = std::move(Value);
174 }
175
176 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
177 PP = std::move(Value);
178 }
179
180 void CompilerInstance::setASTContext(
181 llvm::IntrusiveRefCntPtr<ASTContext> Value) {
182 Context = std::move(Value);
183
184 if (Context && Consumer)
185 getASTConsumer().Initialize(getASTContext());
186 }
187
188 void CompilerInstance::setSema(Sema *S) {
189 TheSema.reset(S);
190 }
191
192 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
193 Consumer = std::move(Value);
194
195 if (Context && Consumer)
196 getASTConsumer().Initialize(getASTContext());
197 }
198
199 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
200 CompletionConsumer.reset(Value);
201 }
202
203 std::unique_ptr<Sema> CompilerInstance::takeSema() {
204 return std::move(TheSema);
205 }
206
207 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
208 return TheASTReader;
209 }
210 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
211 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
212 "Expected ASTReader to use the same PCM cache");
213 TheASTReader = std::move(Reader);
214 }
215
216 std::shared_ptr<ModuleDependencyCollector>
217 CompilerInstance::getModuleDepCollector() const {
218 return ModuleDepCollector;
219 }
220
221 void CompilerInstance::setModuleDepCollector(
222 std::shared_ptr<ModuleDependencyCollector> Collector) {
223 ModuleDepCollector = std::move(Collector);
224 }
225
226 static void collectHeaderMaps(const HeaderSearch &HS,
227 std::shared_ptr<ModuleDependencyCollector> MDC) {
228 SmallVector<std::string, 4> HeaderMapFileNames;
229 HS.getHeaderMapFileNames(HeaderMapFileNames);
230 for (auto &Name : HeaderMapFileNames)
231 MDC->addFile(Name);
232 }
233
234 static void collectIncludePCH(CompilerInstance &CI,
235 std::shared_ptr<ModuleDependencyCollector> MDC) {
236 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
237 if (PPOpts.ImplicitPCHInclude.empty())
238 return;
239
240 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
241 FileManager &FileMgr = CI.getFileManager();
242 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
243 if (!PCHDir) {
244 MDC->addFile(PCHInclude);
245 return;
246 }
247
248 std::error_code EC;
249 SmallString<128> DirNative;
250 llvm::sys::path::native(PCHDir->getName(), DirNative);
251 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
252 SimpleASTReaderListener Validator(CI.getPreprocessor());
253 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
254 Dir != DirEnd && !EC; Dir.increment(EC)) {
255 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
256 // used here since we're not interested in validating the PCH at this time,
257 // but only to check whether this is a file containing an AST.
258 if (!ASTReader::readASTFileControlBlock(
259 Dir->path(), FileMgr, CI.getModuleCache(),
260 CI.getPCHContainerReader(),
261 /*FindModuleFileExtensions=*/false, Validator,
262 /*ValidateDiagnosticOptions=*/false))
263 MDC->addFile(Dir->path());
264 }
265 }
266
267 static void collectVFSEntries(CompilerInstance &CI,
268 std::shared_ptr<ModuleDependencyCollector> MDC) {
269 // Collect all VFS found.
270 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
271 CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) {
272 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
273 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
274 });
275
276 for (auto &E : VFSEntries)
277 MDC->addFile(E.VPath, E.RPath);
278 }
279
280 void CompilerInstance::createVirtualFileSystem(
281 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS, DiagnosticConsumer *DC) {
282 DiagnosticOptions DiagOpts;
283 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
284 /*ShouldOwnClient=*/false);
285
286 VFS = createVFSFromCompilerInvocation(getInvocation(), Diags,
287 std::move(BaseFS));
288 // FIXME: Should this go into createVFSFromCompilerInvocation?
289 if (getFrontendOpts().ShowStats)
290 VFS =
291 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
292 }
293
294 // Diagnostics
295 static void SetUpDiagnosticLog(DiagnosticOptions &DiagOpts,
296 const CodeGenOptions *CodeGenOpts,
297 DiagnosticsEngine &Diags) {
298 std::error_code EC;
299 std::unique_ptr<raw_ostream> StreamOwner;
300 raw_ostream *OS = &llvm::errs();
301 if (DiagOpts.DiagnosticLogFile != "-") {
302 // Create the output stream.
303 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
304 DiagOpts.DiagnosticLogFile, EC,
305 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
306 if (EC) {
307 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
308 << DiagOpts.DiagnosticLogFile << EC.message();
309 } else {
310 FileOS->SetUnbuffered();
311 OS = FileOS.get();
312 StreamOwner = std::move(FileOS);
313 }
314 }
315
316 // Chain in the diagnostic client which will log the diagnostics.
317 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
318 std::move(StreamOwner));
319 if (CodeGenOpts)
320 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
321 if (Diags.ownsClient()) {
322 Diags.setClient(
323 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
324 } else {
325 Diags.setClient(
326 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
327 }
328 }
329
330 static void SetupSerializedDiagnostics(DiagnosticOptions &DiagOpts,
331 DiagnosticsEngine &Diags,
332 StringRef OutputFile) {
333 auto SerializedConsumer =
334 clang::serialized_diags::create(OutputFile, DiagOpts);
335
336 if (Diags.ownsClient()) {
337 Diags.setClient(new ChainedDiagnosticConsumer(
338 Diags.takeClient(), std::move(SerializedConsumer)));
339 } else {
340 Diags.setClient(new ChainedDiagnosticConsumer(
341 Diags.getClient(), std::move(SerializedConsumer)));
342 }
343 }
344
345 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
346 bool ShouldOwnClient) {
347 Diagnostics = createDiagnostics(getVirtualFileSystem(), getDiagnosticOpts(),
348 Client, ShouldOwnClient, &getCodeGenOpts());
349 }
350
351 IntrusiveRefCntPtr<DiagnosticsEngine> CompilerInstance::createDiagnostics(
352 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
353 DiagnosticConsumer *Client, bool ShouldOwnClient,
354 const CodeGenOptions *CodeGenOpts) {
355 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
356 DiagnosticIDs::create(), Opts);
357
358 // Create the diagnostic client for reporting errors or for
359 // implementing -verify.
360 if (Client) {
361 Diags->setClient(Client, ShouldOwnClient);
362 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
363 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
364 } else
365 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
366
367 // Chain in -verify checker, if requested.
368 if (Opts.VerifyDiagnostics)
369 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
370
371 // Chain in -diagnostic-log-file dumper, if requested.
372 if (!Opts.DiagnosticLogFile.empty())
373 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
374
375 if (!Opts.DiagnosticSerializationFile.empty())
376 SetupSerializedDiagnostics(Opts, *Diags, Opts.DiagnosticSerializationFile);
377
378 // Configure our handling of diagnostics.
379 ProcessWarningOptions(*Diags, Opts, VFS);
380
381 return Diags;
382 }
383
384 // File Manager
385
386 void CompilerInstance::createFileManager() {
387 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
388 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), VFS);
389 }
390
391 // Source Manager
392
393 void CompilerInstance::createSourceManager() {
394 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
395 assert(FileMgr && "FileManager needed for creating SourceManager");
396 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(),
397 getFileManager());
398 }
399
400 // Initialize the remapping of files to alternative contents, e.g.,
401 // those specified through other files.
402 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
403 SourceManager &SourceMgr,
404 FileManager &FileMgr,
405 const PreprocessorOptions &InitOpts) {
406 // Remap files in the source manager (with buffers).
407 for (const auto &RB : InitOpts.RemappedFileBuffers) {
408 // Create the file entry for the file that we're mapping from.
409 FileEntryRef FromFile =
410 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
411
412 // Override the contents of the "from" file with the contents of the
413 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
414 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
415 // to the SourceManager.
416 if (InitOpts.RetainRemappedFileBuffers)
417 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
418 else
419 SourceMgr.overrideFileContents(
420 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
421 }
422
423 // Remap files in the source manager (with other files).
424 for (const auto &RF : InitOpts.RemappedFiles) {
425 // Find the file that we're mapping to.
426 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
427 if (!ToFile) {
428 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
429 continue;
430 }
431
432 // Create the file entry for the file that we're mapping from.
433 FileEntryRef FromFile =
434 FileMgr.getVirtualFileRef(RF.first, ToFile->getSize(), 0);
435
436 // Override the contents of the "from" file with the contents of
437 // the "to" file.
438 SourceMgr.overrideFileContents(FromFile, *ToFile);
439 }
440
441 SourceMgr.setOverridenFilesKeepOriginalName(
442 InitOpts.RemappedFilesKeepOriginalName);
443 }
444
445 // Preprocessor
446
447 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
448 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
449
450 // The AST reader holds a reference to the old preprocessor (if any).
451 TheASTReader.reset();
452
453 // Create the Preprocessor.
454 HeaderSearch *HeaderInfo =
455 new HeaderSearch(getHeaderSearchOpts(), getSourceManager(),
456 getDiagnostics(), getLangOpts(), &getTarget());
457 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
458 getDiagnostics(), getLangOpts(),
459 getSourceManager(), *HeaderInfo, *this,
460 /*IdentifierInfoLookup=*/nullptr,
461 /*OwnsHeaderSearch=*/true, TUKind);
462 getTarget().adjust(getDiagnostics(), getLangOpts(), getAuxTarget());
463 PP->Initialize(getTarget(), getAuxTarget());
464
465 if (PPOpts.DetailedRecord)
466 PP->createPreprocessingRecord();
467
468 // Apply remappings to the source manager.
469 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
470 PP->getFileManager(), PPOpts);
471
472 // Predefine macros and configure the preprocessor.
473 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
474 getFrontendOpts(), getCodeGenOpts());
475
476 // Initialize the header search object. In CUDA compilations, we use the aux
477 // triple (the host triple) to initialize our header search, since we need to
478 // find the host headers in order to compile the CUDA code.
479 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
480 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
481 PP->getAuxTargetInfo())
482 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
483
484 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
485 PP->getLangOpts(), *HeaderSearchTriple);
486
487 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
488
489 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
490 std::string ModuleHash = getInvocation().getModuleHash();
491 PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
492 PP->getHeaderSearchInfo().setModuleCachePath(
493 getSpecificModuleCachePath(ModuleHash));
494 }
495
496 // Handle generating dependencies, if requested.
497 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
498 if (!DepOpts.OutputFile.empty())
499 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
500 if (!DepOpts.DOTOutputFile.empty())
501 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
502 getHeaderSearchOpts().Sysroot);
503
504 // If we don't have a collector, but we are collecting module dependencies,
505 // then we're the top level compiler instance and need to create one.
506 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
507 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
508 DepOpts.ModuleDependencyOutputDir, getVirtualFileSystemPtr());
509 }
510
511 // If there is a module dep collector, register with other dep collectors
512 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
513 if (ModuleDepCollector) {
514 addDependencyCollector(ModuleDepCollector);
515 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
516 collectIncludePCH(*this, ModuleDepCollector);
517 collectVFSEntries(*this, ModuleDepCollector);
518 }
519
520 // Modules need an output manager.
521 if (!hasOutputManager())
522 createOutputManager();
523
524 for (auto &Listener : DependencyCollectors)
525 Listener->attachToPreprocessor(*PP);
526
527 // Handle generating header include information, if requested.
528 if (DepOpts.ShowHeaderIncludes)
529 AttachHeaderIncludeGen(*PP, DepOpts);
530 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
531 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
532 if (OutputPath == "-")
533 OutputPath = "";
534 AttachHeaderIncludeGen(*PP, DepOpts,
535 /*ShowAllHeaders=*/true, OutputPath,
536 /*ShowDepth=*/false);
537 }
538
539 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
540 AttachHeaderIncludeGen(*PP, DepOpts,
541 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
542 /*ShowDepth=*/true, /*MSStyle=*/true);
543 }
544
545 if (GetDependencyDirectives)
546 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
547 }
548
549 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
550 assert(FileMgr && "Specific module cache path requires a FileManager");
551
552 // Set up the module path, including the hash for the module-creation options.
553 SmallString<256> SpecificModuleCache;
554 normalizeModuleCachePath(*FileMgr, getHeaderSearchOpts().ModuleCachePath,
555 SpecificModuleCache);
556 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
557 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
558 return std::string(SpecificModuleCache);
559 }
560
561 // ASTContext
562
563 void CompilerInstance::createASTContext() {
564 Preprocessor &PP = getPreprocessor();
565 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
566 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
567 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
568 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
569 setASTContext(std::move(Context));
570 }
571
572 // ExternalASTSource
573
574 namespace {
575 // Helper to recursively read the module names for all modules we're adding.
576 // We mark these as known and redirect any attempt to load that module to
577 // the files we were handed.
578 struct ReadModuleNames : ASTReaderListener {
579 Preprocessor &PP;
580 llvm::SmallVector<std::string, 8> LoadedModules;
581
582 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
583
584 void ReadModuleName(StringRef ModuleName) override {
585 // Keep the module name as a string for now. It's not safe to create a new
586 // IdentifierInfo from an ASTReader callback.
587 LoadedModules.push_back(ModuleName.str());
588 }
589
590 void registerAll() {
591 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
592 for (const std::string &LoadedModule : LoadedModules)
593 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
594 MM.findOrLoadModule(LoadedModule));
595 LoadedModules.clear();
596 }
597
598 void markAllUnavailable() {
599 for (const std::string &LoadedModule : LoadedModules) {
600 if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findOrLoadModule(
601 LoadedModule)) {
602 M->HasIncompatibleModuleFile = true;
603
604 // Mark module as available if the only reason it was unavailable
605 // was missing headers.
606 SmallVector<Module *, 2> Stack;
607 Stack.push_back(M);
608 while (!Stack.empty()) {
609 Module *Current = Stack.pop_back_val();
610 if (Current->IsUnimportable) continue;
611 Current->IsAvailable = true;
612 auto SubmodulesRange = Current->submodules();
613 llvm::append_range(Stack, SubmodulesRange);
614 }
615 }
616 }
617 LoadedModules.clear();
618 }
619 };
620 } // namespace
621
622 void CompilerInstance::createPCHExternalASTSource(
623 StringRef Path, DisableValidationForModuleKind DisableValidation,
624 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
625 bool OwnDeserializationListener) {
626 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
627 TheASTReader = createPCHExternalASTSource(
628 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
629 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
630 getASTContext(), getPCHContainerReader(), getCodeGenOpts(),
631 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
632 DeserializationListener, OwnDeserializationListener, Preamble,
633 getFrontendOpts().UseGlobalModuleIndex);
634 }
635
636 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
637 StringRef Path, StringRef Sysroot,
638 DisableValidationForModuleKind DisableValidation,
639 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
640 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
641 const CodeGenOptions &CodeGenOpts,
642 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
643 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
644 void *DeserializationListener, bool OwnDeserializationListener,
645 bool Preamble, bool UseGlobalModuleIndex) {
646 const HeaderSearchOptions &HSOpts =
647 PP.getHeaderSearchInfo().getHeaderSearchOpts();
648
649 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
650 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
651 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
652 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
653 HSOpts.ModulesValidateSystemHeaders,
654 HSOpts.ModulesForceValidateUserHeaders,
655 HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
656
657 // We need the external source to be set up before we read the AST, because
658 // eagerly-deserialized declarations may use it.
659 Context.setExternalSource(Reader);
660
661 Reader->setDeserializationListener(
662 static_cast<ASTDeserializationListener *>(DeserializationListener),
663 /*TakeOwnership=*/OwnDeserializationListener);
664
665 for (auto &Listener : DependencyCollectors)
666 Listener->attachToASTReader(*Reader);
667
668 auto Listener = std::make_unique<ReadModuleNames>(PP);
669 auto &ListenerRef = *Listener;
670 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
671 std::move(Listener));
672
673 switch (Reader->ReadAST(Path,
674 Preamble ? serialization::MK_Preamble
675 : serialization::MK_PCH,
676 SourceLocation(),
677 ASTReader::ARR_None)) {
678 case ASTReader::Success:
679 // Set the predefines buffer as suggested by the PCH reader. Typically, the
680 // predefines buffer will be empty.
681 PP.setPredefines(Reader->getSuggestedPredefines());
682 ListenerRef.registerAll();
683 return Reader;
684
685 case ASTReader::Failure:
686 // Unrecoverable failure: don't even try to process the input file.
687 break;
688
689 case ASTReader::Missing:
690 case ASTReader::OutOfDate:
691 case ASTReader::VersionMismatch:
692 case ASTReader::ConfigurationMismatch:
693 case ASTReader::HadErrors:
694 // No suitable PCH file could be found. Return an error.
695 break;
696 }
697
698 ListenerRef.markAllUnavailable();
699 Context.setExternalSource(nullptr);
700 return nullptr;
701 }
702
703 // Code Completion
704
705 static bool EnableCodeCompletion(Preprocessor &PP,
706 StringRef Filename,
707 unsigned Line,
708 unsigned Column) {
709 // Tell the source manager to chop off the given file at a specific
710 // line and column.
711 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
712 if (!Entry) {
713 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
714 << Filename;
715 return true;
716 }
717
718 // Truncate the named file at the given line/column.
719 PP.SetCodeCompletionPoint(*Entry, Line, Column);
720 return false;
721 }
722
723 void CompilerInstance::createCodeCompletionConsumer() {
724 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
725 if (!CompletionConsumer) {
726 setCodeCompletionConsumer(createCodeCompletionConsumer(
727 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
728 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
729 return;
730 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
731 Loc.Line, Loc.Column)) {
732 setCodeCompletionConsumer(nullptr);
733 return;
734 }
735 }
736
737 void CompilerInstance::createFrontendTimer() {
738 timerGroup.reset(new llvm::TimerGroup("clang", "Clang time report"));
739 FrontendTimer.reset(new llvm::Timer("frontend", "Front end", *timerGroup));
740 }
741
742 CodeCompleteConsumer *
743 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
744 StringRef Filename,
745 unsigned Line,
746 unsigned Column,
747 const CodeCompleteOptions &Opts,
748 raw_ostream &OS) {
749 if (EnableCodeCompletion(PP, Filename, Line, Column))
750 return nullptr;
751
752 // Set up the creation routine for code-completion.
753 return new PrintingCodeCompleteConsumer(Opts, OS);
754 }
755
756 void CompilerInstance::createSema(TranslationUnitKind TUKind,
757 CodeCompleteConsumer *CompletionConsumer) {
758 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
759 TUKind, CompletionConsumer));
760
761 // Set up API notes.
762 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
763
764 // Attach the external sema source if there is any.
765 if (ExternalSemaSrc) {
766 TheSema->addExternalSource(ExternalSemaSrc);
767 ExternalSemaSrc->InitializeSema(*TheSema);
768 }
769
770 // If we're building a module and are supposed to load API notes,
771 // notify the API notes manager.
772 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
773 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
774 currentModule, getLangOpts().APINotesModules,
775 getAPINotesOpts().ModuleSearchPaths);
776 }
777 }
778
779 // Output Files
780
781 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
782 // The ASTConsumer can own streams that write to the output files.
783 assert(!hasASTConsumer() && "ASTConsumer should be reset");
784 if (!EraseFiles) {
785 for (auto &O : OutputFiles)
786 llvm::handleAllErrors(
787 O.keep(),
788 [&](const llvm::vfs::TempFileOutputError &E) {
789 getDiagnostics().Report(diag::err_unable_to_rename_temp)
790 << E.getTempPath() << E.getOutputPath()
791 << E.convertToErrorCode().message();
792 },
793 [&](const llvm::vfs::OutputError &E) {
794 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
795 << E.getOutputPath() << E.convertToErrorCode().message();
796 },
797 [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
798 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
799 << O.getPath() << EIB.message();
800 });
801 }
802 OutputFiles.clear();
803 if (DeleteBuiltModules) {
804 for (auto &Module : BuiltModules)
805 llvm::sys::fs::remove(Module.second);
806 BuiltModules.clear();
807 }
808 }
809
810 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
811 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
812 bool CreateMissingDirectories, bool ForceUseTemporary) {
813 StringRef OutputPath = getFrontendOpts().OutputFile;
814 std::optional<SmallString<128>> PathStorage;
815 if (OutputPath.empty()) {
816 if (InFile == "-" || Extension.empty()) {
817 OutputPath = "-";
818 } else {
819 PathStorage.emplace(InFile);
820 llvm::sys::path::replace_extension(*PathStorage, Extension);
821 OutputPath = *PathStorage;
822 }
823 }
824
825 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
826 getFrontendOpts().UseTemporary || ForceUseTemporary,
827 CreateMissingDirectories);
828 }
829
830 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
831 return std::make_unique<llvm::raw_null_ostream>();
832 }
833
834 // Output Manager
835
836 void CompilerInstance::setOutputManager(
837 IntrusiveRefCntPtr<llvm::vfs::OutputBackend> NewOutputs) {
838 assert(!OutputMgr && "Already has an output manager");
839 OutputMgr = std::move(NewOutputs);
840 }
841
842 void CompilerInstance::createOutputManager() {
843 assert(!OutputMgr && "Already has an output manager");
844 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
845 }
846
847 llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
848 assert(OutputMgr);
849 return *OutputMgr;
850 }
851
852 llvm::vfs::OutputBackend &CompilerInstance::getOrCreateOutputManager() {
853 if (!hasOutputManager())
854 createOutputManager();
855 return getOutputManager();
856 }
857
858 std::unique_ptr<raw_pwrite_stream>
859 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
860 bool RemoveFileOnSignal, bool UseTemporary,
861 bool CreateMissingDirectories) {
862 Expected<std::unique_ptr<raw_pwrite_stream>> OS =
863 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
864 CreateMissingDirectories);
865 if (OS)
866 return std::move(*OS);
867 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
868 << OutputPath << errorToErrorCode(OS.takeError()).message();
869 return nullptr;
870 }
871
872 Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
873 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
874 bool RemoveFileOnSignal,
875 bool UseTemporary,
876 bool CreateMissingDirectories) {
877 assert((!CreateMissingDirectories || UseTemporary) &&
878 "CreateMissingDirectories is only allowed when using temporary files");
879
880 // If '-working-directory' was passed, the output filename should be
881 // relative to that.
882 std::optional<SmallString<128>> AbsPath;
883 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
884 assert(hasFileManager() &&
885 "File Manager is required to fix up relative path.\n");
886
887 AbsPath.emplace(OutputPath);
888 FileManager::fixupRelativePath(getFileSystemOpts(), *AbsPath);
889 OutputPath = *AbsPath;
890 }
891
892 using namespace llvm::vfs;
893 Expected<OutputFile> O = getOrCreateOutputManager().createFile(
894 OutputPath,
895 OutputConfig()
896 .setTextWithCRLF(!Binary)
897 .setDiscardOnSignal(RemoveFileOnSignal)
898 .setAtomicWrite(UseTemporary)
899 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
900 if (!O)
901 return O.takeError();
902
903 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
904 OutputFiles.push_back(std::move(*O));
905 return OutputFiles.back().createProxy();
906 }
907
908 // Initialization Utilities
909
910 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
911 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
912 getSourceManager());
913 }
914
915 // static
916 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
917 DiagnosticsEngine &Diags,
918 FileManager &FileMgr,
919 SourceManager &SourceMgr) {
920 SrcMgr::CharacteristicKind Kind =
921 Input.getKind().getFormat() == InputKind::ModuleMap
922 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
923 : SrcMgr::C_User_ModuleMap
924 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
925
926 if (Input.isBuffer()) {
927 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
928 assert(SourceMgr.getMainFileID().isValid() &&
929 "Couldn't establish MainFileID!");
930 return true;
931 }
932
933 StringRef InputFile = Input.getFile();
934
935 // Figure out where to get and map in the main file.
936 auto FileOrErr = InputFile == "-"
937 ? FileMgr.getSTDIN()
938 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
939 if (!FileOrErr) {
940 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
941 if (InputFile != "-")
942 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
943 else
944 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
945 return false;
946 }
947
948 SourceMgr.setMainFileID(
949 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
950
951 assert(SourceMgr.getMainFileID().isValid() &&
952 "Couldn't establish MainFileID!");
953 return true;
954 }
955
956 // High-Level Operations
957
958 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
959 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
960 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
961 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
962
963 // Mark this point as the bottom of the stack if we don't have somewhere
964 // better. We generally expect frontend actions to be invoked with (nearly)
965 // DesiredStackSpace available.
966 noteBottomOfStack();
967
968 llvm::scope_exit FinishDiagnosticClient([&]() {
969 // Notify the diagnostic client that all files were processed.
970 getDiagnosticClient().finish();
971 });
972
973 raw_ostream &OS = getVerboseOutputStream();
974
975 if (!Act.PrepareToExecute(*this))
976 return false;
977
978 if (!createTarget())
979 return false;
980
981 // rewriter project will change target built-in bool type from its default.
982 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
983 getTarget().noSignedCharForObjCBool();
984
985 // Validate/process some options.
986 if (getHeaderSearchOpts().Verbose)
987 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
988 << LLVM_VERSION_STRING << " default target "
989 << llvm::sys::getDefaultTargetTriple() << "\n";
990
991 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
992 llvm::EnableStatistics(false);
993
994 // Sort vectors containing toc data and no toc data variables to facilitate
995 // binary search later.
996 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
997 llvm::sort(getCodeGenOpts().NoTocDataVars);
998
999 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1000 // Reset the ID tables if we are reusing the SourceManager and parsing
1001 // regular files.
1002 if (hasSourceManager() && !Act.isModelParsingAction())
1003 getSourceManager().clearIDTables();
1004
1005 if (Act.BeginSourceFile(*this, FIF)) {
1006 if (llvm::Error Err = Act.Execute()) {
1007 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1008 }
1009 Act.EndSourceFile();
1010 }
1011 }
1012
1013 printDiagnosticStats();
1014
1015 if (getFrontendOpts().ShowStats) {
1016 if (hasFileManager()) {
1017 getFileManager().PrintStats();
1018 OS << '\n';
1019 }
1020 llvm::PrintStatistics(OS);
1021 }
1022 StringRef StatsFile = getFrontendOpts().StatsFile;
1023 if (!StatsFile.empty()) {
1024 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1025 if (getFrontendOpts().AppendStats)
1026 FileFlags |= llvm::sys::fs::OF_Append;
1027 std::error_code EC;
1028 auto StatS =
1029 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1030 if (EC) {
1031 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1032 << StatsFile << EC.message();
1033 } else {
1034 llvm::PrintStatisticsJSON(*StatS);
1035 }
1036 }
1037
1038 return !getDiagnostics().getClient()->getNumErrors();
1039 }
1040
1041 void CompilerInstance::printDiagnosticStats() {
1042 if (!getDiagnosticOpts().ShowCarets)
1043 return;
1044
1045 raw_ostream &OS = getVerboseOutputStream();
1046
1047 // We can have multiple diagnostics sharing one diagnostic client.
1048 // Get the total number of warnings/errors from the client.
1049 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1050 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1051
1052 if (NumWarnings)
1053 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1054 if (NumWarnings && NumErrors)
1055 OS << " and ";
1056 if (NumErrors)
1057 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1058 if (NumWarnings || NumErrors) {
1059 OS << " generated";
1060 if (getLangOpts().CUDA) {
1061 if (!getLangOpts().CUDAIsDevice) {
1062 OS << " when compiling for host";
1063 } else {
1064 OS << " when compiling for "
1065 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1066 : getTarget().getTriple().str());
1067 }
1068 }
1069 OS << ".\n";
1070 }
1071 }
1072
1073 void CompilerInstance::LoadRequestedPlugins() {
1074 // Load any requested plugins.
1075 for (const std::string &Path : getFrontendOpts().Plugins) {
1076 std::string Error;
1077 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1078 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1079 << Path << Error;
1080 }
1081
1082 // Load and store pass plugins for the back-end.
1083 for (const std::string &Path : getCodeGenOpts().PassPlugins) {
1084 if (auto PassPlugin = llvm::PassPlugin::Load(Path)) {
1085 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1086 } else {
1087 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1088 << Path << toString(PassPlugin.takeError());
1089 }
1090 }
1091
1092 // Check if any of the loaded plugins replaces the main AST action
1093 for (const FrontendPluginRegistry::entry &Plugin :
1094 FrontendPluginRegistry::entries()) {
1095 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1096 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1097 getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
1098 getFrontendOpts().ActionName = Plugin.getName().str();
1099 break;
1100 }
1101 }
1102 }
1103
1104 /// Determine the appropriate source input kind based on language
1105 /// options.
1106 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1107 if (LangOpts.OpenCL)
1108 return Language::OpenCL;
1109 if (LangOpts.CUDA)
1110 return Language::CUDA;
1111 if (LangOpts.ObjC)
1112 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1113 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1114 }
1115
1116 std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1117 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1118 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1119 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1120 // Construct a compiler invocation for creating this module.
1121 auto Invocation = std::make_shared<CompilerInvocation>(getInvocation());
1122
1123 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1124
1125 // For any options that aren't intended to affect how a module is built,
1126 // reset them to their default values.
1127 Invocation->resetNonModularOptions();
1128
1129 // Remove any macro definitions that are explicitly ignored by the module.
1130 // They aren't supposed to affect how the module is built anyway.
1131 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1132 llvm::erase_if(PPOpts.Macros,
1133 [&HSOpts](const std::pair<std::string, bool> &def) {
1134 StringRef MacroDef = def.first;
1135 return HSOpts.ModulesIgnoreMacros.contains(
1136 llvm::CachedHashString(MacroDef.split('=').first));
1137 });
1138
1139 // If the original compiler invocation had -fmodule-name, pass it through.
1140 Invocation->getLangOpts().ModuleName =
1141 getInvocation().getLangOpts().ModuleName;
1142
1143 // Note the name of the module we're building.
1144 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1145
1146 // If there is a module map file, build the module using the module map.
1147 // Set up the inputs/outputs so that we build the module from its umbrella
1148 // header.
1149 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1150 FrontendOpts.OutputFile = ModuleFileName.str();
1151 FrontendOpts.DisableFree = false;
1152 FrontendOpts.GenerateGlobalModuleIndex = false;
1153 FrontendOpts.BuildingImplicitModule = true;
1154 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1155 // Force implicitly-built modules to hash the content of the module file.
1156 HSOpts.ModulesHashContent = true;
1157 FrontendOpts.Inputs = {std::move(Input)};
1158
1159 // Don't free the remapped file buffers; they are owned by our caller.
1160 PPOpts.RetainRemappedFileBuffers = true;
1161
1162 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1163
1164 DiagOpts.VerifyDiagnostics = 0;
1165 assert(getInvocation().getModuleHash() == Invocation->getModuleHash() &&
1166 "Module hash mismatch!");
1167
1168 // Construct a compiler instance that will be used to actually create the
1169 // module. Since we're sharing an in-memory module cache,
1170 // CompilerInstance::CompilerInstance is responsible for finalizing the
1171 // buffers to prevent use-after-frees.
1172 auto InstancePtr = std::make_unique<CompilerInstance>(
1173 std::move(Invocation), getPCHContainerOperations(), ModCache);
1174 auto &Instance = *InstancePtr;
1175
1176 auto &Inv = Instance.getInvocation();
1177
1178 if (ThreadSafeConfig) {
1179 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1180 Instance.createFileManager();
1181 } else if (FrontendOpts.ModulesShareFileManager) {
1182 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1183 Instance.setFileManager(getFileManagerPtr());
1184 } else {
1185 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1186 Instance.createFileManager();
1187 }
1188
1189 if (ThreadSafeConfig) {
1190 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1191 /*ShouldOwnClient=*/false);
1192 } else {
1193 Instance.createDiagnostics(
1194 new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1195 /*ShouldOwnClient=*/true);
1196 }
1197 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1198 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1199
1200 Instance.createSourceManager();
1201 SourceManager &SourceMgr = Instance.getSourceManager();
1202
1203 if (ThreadSafeConfig) {
1204 // Detecting cycles in the module graph is responsibility of the client.
1205 } else {
1206 // Note that this module is part of the module build stack, so that we
1207 // can detect cycles in the module graph.
1208 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1209 SourceMgr.pushModuleBuildStack(
1210 ModuleName, FullSourceLoc(ImportLoc, getSourceManager()));
1211 }
1212
1213 // Make a copy for the new instance.
1214 Instance.FailedModules = FailedModules;
1215
1216 if (GetDependencyDirectives)
1217 Instance.GetDependencyDirectives =
1218 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1219
1220 if (ThreadSafeConfig) {
1221 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1222 } else {
1223 // If we're collecting module dependencies, we need to share a collector
1224 // between all of the module CompilerInstances. Other than that, we don't
1225 // want to produce any dependency output from the module build.
1226 Instance.setModuleDepCollector(getModuleDepCollector());
1227 }
1228 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1229
1230 return InstancePtr;
1231 }
1232
1233 bool CompilerInstance::compileModule(SourceLocation ImportLoc,
1234 StringRef ModuleName,
1235 StringRef ModuleFileName,
1236 CompilerInstance &Instance) {
1237 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1238
1239 // Never compile a module that's already finalized - this would cause the
1240 // existing module to be freed, causing crashes if it is later referenced
1241 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1242 getDiagnostics().Report(ImportLoc, diag::err_module_rebuild_finalized)
1243 << ModuleName;
1244 return false;
1245 }
1246
1247 getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1248 << ModuleName << ModuleFileName;
1249
1250 // Execute the action to actually build the module in-place. Use a separate
1251 // thread so that we get a stack large enough.
1252 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1253 [&]() {
1254 GenerateModuleFromModuleMapAction Action;
1255 Instance.ExecuteAction(Action);
1256 },
1257 DesiredStackSize);
1258
1259 getDiagnostics().Report(ImportLoc, diag::remark_module_build_done)
1260 << ModuleName;
1261
1262 // Propagate the statistics to the parent FileManager.
1263 if (!getFrontendOpts().ModulesShareFileManager)
1264 getFileManager().AddStats(Instance.getFileManager());
1265
1266 // Propagate the failed modules to the parent instance.
1267 FailedModules = std::move(Instance.FailedModules);
1268
1269 if (Crashed) {
1270 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1271 // that must be closed before clearing output files.
1272 Instance.setSema(nullptr);
1273 Instance.setASTConsumer(nullptr);
1274
1275 // Delete any remaining temporary files related to Instance.
1276 Instance.clearOutputFiles(/*EraseFiles=*/true);
1277 }
1278
1279 // We've rebuilt a module. If we're allowed to generate or update the global
1280 // module index, record that fact in the importing compiler instance.
1281 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1282 setBuildGlobalModuleIndex(true);
1283 }
1284
1285 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1286 // occurred.
1287 return !Instance.getDiagnostics().hasErrorOccurred() ||
1288 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1289 }
1290
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);
1302 }
1303
1304 std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1305 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
1306 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1307 StringRef ModuleName = Module->getTopLevelModuleName();
1308
1309 InputKind IK(getLanguageFromOptions(getLangOpts()), InputKind::ModuleMap);
1310
1311 // Get or create the module map that we'll use to build this module.
1312 ModuleMap &ModMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1313 SourceManager &SourceMgr = getSourceManager();
1314
1315 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1316 ModuleMapFID.isValid()) {
1317 // We want to use the top-level module map. If we don't, the compiling
1318 // instance may think the containing module map is a top-level one, while
1319 // the importing instance knows it's included from a parent module map via
1320 // the extern directive. This mismatch could bite us later.
1321 SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1322 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1323 ModuleMapFID = SourceMgr.getFileID(Loc);
1324 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1325 }
1326
1327 OptionalFileEntryRef ModuleMapFile =
1328 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1329 assert(ModuleMapFile && "Top-level module map with no FileID");
1330
1331 // Canonicalize compilation to start with the public module map. This is
1332 // vital for submodules declarations in the private module maps to be
1333 // correctly parsed when depending on a top level module in the public one.
1334 if (OptionalFileEntryRef PublicMMFile =
1335 getPublicModuleMap(*ModuleMapFile, getFileManager()))
1336 ModuleMapFile = PublicMMFile;
1337
1338 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1339
1340 // Use the systemness of the module map as parsed instead of using the
1341 // IsSystem attribute of the module. If the module has [system] but the
1342 // module map is not in a system path, then this would incorrectly parse
1343 // any other modules in that module map as system too.
1344 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(ModuleMapFID);
1345 bool IsSystem = isSystem(SLoc.getFile().getFileCharacteristic());
1346
1347 // Use the module map where this module resides.
1348 return cloneForModuleCompileImpl(
1349 ImportLoc, ModuleName,
1350 FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1351 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1352 std::move(ThreadSafeConfig));
1353 }
1354
1355 // FIXME: We only need to fake up an input file here as a way of
1356 // transporting the module's directory to the module map parser. We should
1357 // be able to do that more directly, and parse from a memory buffer without
1358 // inventing this file.
1359 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1360 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1361
1362 std::string InferredModuleMapContent;
1363 llvm::raw_string_ostream OS(InferredModuleMapContent);
1364 Module->print(OS);
1365
1366 auto Instance = cloneForModuleCompileImpl(
1367 ImportLoc, ModuleName,
1368 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1369 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1370 std::move(ThreadSafeConfig));
1371
1372 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1373 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1374 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1375 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1376 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1377 std::move(ModuleMapBuffer));
1378
1379 return Instance;
1380 }
1381
1382 /// Read the AST right after compiling the module.
1383 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1384 SourceLocation ImportLoc,
1385 SourceLocation ModuleNameLoc,
1386 Module *Module, StringRef ModuleFileName,
1387 bool *OutOfDate, bool *Missing) {
1388 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1389
1390 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1391 if (OutOfDate)
1392 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1393
1394 // Try to read the module file, now that we've compiled it.
1395 ASTReader::ASTReadResult ReadResult =
1396 ImportingInstance.getASTReader()->ReadAST(
1397 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1398 ModuleLoadCapabilities);
1399 if (ReadResult == ASTReader::Success)
1400 return true;
1401
1402 // The caller wants to handle out-of-date failures.
1403 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1404 *OutOfDate = true;
1405 return false;
1406 }
1407
1408 // The caller wants to handle missing module files.
1409 if (Missing && ReadResult == ASTReader::Missing) {
1410 *Missing = true;
1411 return false;
1412 }
1413
1414 // The ASTReader didn't diagnose the error, so conservatively report it.
1415 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1416 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1417 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1418
1419 return false;
1420 }
1421
1422 /// Compile a module in a separate compiler instance and read the AST,
1423 /// returning true if the module compiles without errors.
1424 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1425 SourceLocation ImportLoc,
1426 SourceLocation ModuleNameLoc,
1427 Module *Module,
1428 StringRef ModuleFileName) {
1429 {
1430 auto Instance = ImportingInstance.cloneForModuleCompile(
1431 ModuleNameLoc, Module, ModuleFileName);
1432
1433 if (!ImportingInstance.compileModule(ModuleNameLoc,
1434 Module->getTopLevelModuleName(),
1435 ModuleFileName, *Instance)) {
1436 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1437 diag::err_module_not_built)
1438 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1439 return false;
1440 }
1441 }
1442
1443 // The module is built successfully, we can update its timestamp now.
1444 if (ImportingInstance.getPreprocessor()
1445 .getHeaderSearchInfo()
1446 .getHeaderSearchOpts()
1447 .ModulesValidateOncePerBuildSession) {
1448 ImportingInstance.getModuleCache().updateModuleTimestamp(ModuleFileName);
1449 }
1450
1451 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1452 Module, ModuleFileName,
1453 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1454 }
1455
1456 /// Compile a module in a separate compiler instance and read the AST,
1457 /// returning true if the module compiles without errors, using a lock manager
1458 /// to avoid building the same module in multiple compiler instances.
1459 ///
1460 /// Uses a lock file manager and exponential backoff to reduce the chances that
1461 /// multiple instances will compete to create the same module. On timeout,
1462 /// deletes the lock file in order to avoid deadlock from crashing processes or
1463 /// bugs in the lock file manager.
1464 static bool compileModuleAndReadASTBehindLock(
1465 CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1466 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1467 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1468
1469 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1470 << ModuleFileName << Module->Name;
1471
1472 auto &ModuleCache = ImportingInstance.getModuleCache();
1473 ModuleCache.prepareForGetLock(ModuleFileName);
1474
1475 while (true) {
1476 auto Lock = ModuleCache.getLock(ModuleFileName);
1477 bool Owned;
1478 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1479 // ModuleCache takes care of correctness and locks are only necessary for
1480 // performance. Fallback to building the module in case of any lock
1481 // related errors.
1482 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1483 << Module->Name << toString(std::move(Err));
1484 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1485 ModuleNameLoc, Module, ModuleFileName);
1486 }
1487 if (Owned) {
1488 // We're responsible for building the module ourselves.
1489 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1490 ModuleNameLoc, Module, ModuleFileName);
1491 }
1492
1493 // Someone else is responsible for building the module. Wait for them to
1494 // finish.
1495 switch (Lock->waitForUnlockFor(std::chrono::seconds(90))) {
1496 case llvm::WaitForUnlockResult::Success:
1497 break; // The interesting case.
1498 case llvm::WaitForUnlockResult::OwnerDied:
1499 continue; // try again to get the lock.
1500 case llvm::WaitForUnlockResult::Timeout:
1501 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1502 // for someone else to complete the build so that it does not happen
1503 // twice. In case of timeout, build it ourselves.
1504 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1505 << Module->Name;
1506 // Clear the lock file so that future invocations can make progress.
1507 Lock->unsafeMaybeUnlock();
1508 continue;
1509 }
1510
1511 // Read the module that was just written by someone else.
1512 bool OutOfDate = false;
1513 bool Missing = false;
1514 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1515 Module, ModuleFileName, &OutOfDate, &Missing))
1516 return true;
1517 if (!OutOfDate && !Missing)
1518 return false;
1519
1520 // The module may be missing or out of date in the presence of file system
1521 // races. It may also be out of date if one of its imports depends on header
1522 // search paths that are not consistent with this ImportingInstance.
1523 // Try again...
1524 }
1525 }
1526
1527 /// Compile a module in a separate compiler instance and read the AST,
1528 /// returning true if the module compiles without errors, potentially using a
1529 /// lock manager to avoid building the same module in multiple compiler
1530 /// instances.
1531 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1532 SourceLocation ImportLoc,
1533 SourceLocation ModuleNameLoc,
1534 Module *Module, StringRef ModuleFileName) {
1535 return ImportingInstance.getInvocation()
1536 .getFrontendOpts()
1537 .BuildingImplicitModuleUsesLock
1538 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1539 ModuleNameLoc, Module,
1540 ModuleFileName)
1541 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1542 ModuleNameLoc, Module,
1543 ModuleFileName);
1544 }
1545
1546 /// Diagnose differences between the current definition of the given
1547 /// configuration macro and the definition provided on the command line.
1548 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1549 Module *Mod, SourceLocation ImportLoc) {
1550 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1551 SourceManager &SourceMgr = PP.getSourceManager();
1552
1553 // If this identifier has never had a macro definition, then it could
1554 // not have changed.
1555 if (!Id->hadMacroDefinition())
1556 return;
1557 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1558
1559 // Find the macro definition from the command line.
1560 MacroInfo *CmdLineDefinition = nullptr;
1561 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1562 // We only care about the predefines buffer.
1563 FileID FID = SourceMgr.getFileID(MD->getLocation());
1564 if (FID.isInvalid())
1565 continue;
1566 if (FID != PP.getPredefinesFileID() && FID != PP.getPCHPredefinesFileID())
1567 continue;
1568 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1569 CmdLineDefinition = DMD->getMacroInfo();
1570 break;
1571 }
1572
1573 auto *CurrentDefinition = PP.getMacroInfo(Id);
1574 if (CurrentDefinition == CmdLineDefinition) {
1575 // Macro matches. Nothing to do.
1576 } else if (!CurrentDefinition) {
1577 // This macro was defined on the command line, then #undef'd later.
1578 // Complain.
1579 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1580 << true << ConfigMacro << Mod->getFullModuleName();
1581 auto LatestDef = LatestLocalMD->getDefinition();
1582 assert(LatestDef.isUndefined() &&
1583 "predefined macro went away with no #undef?");
1584 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1585 << true;
1586 return;
1587 } else if (!CmdLineDefinition) {
1588 // There was no definition for this macro in the predefines buffer,
1589 // but there was a local definition. Complain.
1590 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1591 << false << ConfigMacro << Mod->getFullModuleName();
1592 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1593 diag::note_module_def_undef_here)
1594 << false;
1595 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1596 /*Syntactically=*/true)) {
1597 // The macro definitions differ.
1598 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1599 << false << ConfigMacro << Mod->getFullModuleName();
1600 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1601 diag::note_module_def_undef_here)
1602 << false;
1603 }
1604 }
1605
1606 static void checkConfigMacros(Preprocessor &PP, Module *M,
1607 SourceLocation ImportLoc) {
1608 clang::Module *TopModule = M->getTopLevelModule();
1609 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1610 checkConfigMacro(PP, ConMacro, M, ImportLoc);
1611 }
1612 }
1613
1614 void CompilerInstance::createASTReader() {
1615 if (TheASTReader)
1616 return;
1617
1618 if (!hasASTContext())
1619 createASTContext();
1620
1621 // If we're implicitly building modules but not currently recursively
1622 // building a module, check whether we need to prune the module cache.
1623 if (getSourceManager().getModuleBuildStack().empty() &&
1624 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1625 ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath,
1626 getHeaderSearchOpts().ModuleCachePruneInterval,
1627 getHeaderSearchOpts().ModuleCachePruneAfter);
1628
1629 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1630 std::string Sysroot = HSOpts.Sysroot;
1631 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1632 const FrontendOptions &FEOpts = getFrontendOpts();
1633 std::unique_ptr<llvm::Timer> ReadTimer;
1634
1635 if (timerGroup)
1636 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1637 "Reading modules", *timerGroup);
1638 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1639 getPreprocessor(), getModuleCache(), &getASTContext(),
1640 getPCHContainerReader(), getCodeGenOpts(),
1641 getFrontendOpts().ModuleFileExtensions,
1642 Sysroot.empty() ? "" : Sysroot.c_str(),
1643 PPOpts.DisablePCHOrModuleValidation,
1644 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1645 /*AllowConfigurationMismatch=*/false,
1646 +HSOpts.ModulesValidateSystemHeaders,
1647 +HSOpts.ModulesForceValidateUserHeaders,
1648 +HSOpts.ValidateASTInputFilesContent,
1649 +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1650 if (hasASTConsumer()) {
1651 TheASTReader->setDeserializationListener(
1652 getASTConsumer().GetASTDeserializationListener());
1653 getASTContext().setASTMutationListener(
1654 getASTConsumer().GetASTMutationListener());
1655 }
1656 getASTContext().setExternalSource(TheASTReader);
1657 if (hasSema())
1658 TheASTReader->InitializeSema(getSema());
1659 if (hasASTConsumer())
1660 TheASTReader->StartTranslationUnit(&getASTConsumer());
1661
1662 for (auto &Listener : DependencyCollectors)
1663 Listener->attachToASTReader(*TheASTReader);
1664 }
1665
1666 bool CompilerInstance::loadModuleFile(
1667 StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1668 llvm::Timer Timer;
1669 if (timerGroup)
1670 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1671 *timerGroup);
1672 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1673
1674 // If we don't already have an ASTReader, create one now.
1675 if (!TheASTReader)
1676 createASTReader();
1677
1678 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1679 // ASTReader to diagnose it, since it can produce better errors that we can.
1680 bool ConfigMismatchIsRecoverable =
1681 getDiagnostics().getDiagnosticLevel(diag::warn_ast_file_config_mismatch,
1682 SourceLocation()) <=
1683 DiagnosticsEngine::Warning;
1684
1685 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1686 auto &ListenerRef = *Listener;
1687 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1688 std::move(Listener));
1689
1690 // Try to load the module file.
1691 switch (TheASTReader->ReadAST(
1692 FileName, serialization::MK_ExplicitModule, SourceLocation(),
1693 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1694 &LoadedModuleFile)) {
1695 case ASTReader::Success:
1696 // We successfully loaded the module file; remember the set of provided
1697 // modules so that we don't try to load implicit modules for them.
1698 ListenerRef.registerAll();
1699 return true;
1700
1701 case ASTReader::ConfigurationMismatch:
1702 // Ignore unusable module files.
1703 getDiagnostics().Report(SourceLocation(),
1704 diag::warn_ast_file_config_mismatch)
1705 << FileName;
1706 // All modules provided by any files we tried and failed to load are now
1707 // unavailable; includes of those modules should now be handled textually.
1708 ListenerRef.markAllUnavailable();
1709 return true;
1710
1711 default:
1712 return false;
1713 }
1714 }
1715
1716 namespace {
1717 enum ModuleSource {
1718 MS_ModuleNotFound,
1719 MS_ModuleCache,
1720 MS_PrebuiltModulePath,
1721 MS_ModuleBuildPragma
1722 };
1723 } // end namespace
1724
1725 /// Select a source for loading the named module and compute the filename to
1726 /// load it from.
1727 static ModuleSource selectModuleSource(
1728 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1729 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1730 HeaderSearch &HS) {
1731 assert(ModuleFilename.empty() && "Already has a module source?");
1732
1733 // Check to see if the module has been built as part of this compilation
1734 // via a module build pragma.
1735 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1736 if (BuiltModuleIt != BuiltModules.end()) {
1737 ModuleFilename = BuiltModuleIt->second;
1738 return MS_ModuleBuildPragma;
1739 }
1740
1741 // Try to load the module from the prebuilt module path.
1742 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1743 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1744 !HSOpts.PrebuiltModulePaths.empty()) {
1745 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1746 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1747 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1748 if (!ModuleFilename.empty())
1749 return MS_PrebuiltModulePath;
1750 }
1751
1752 // Try to load the module from the module cache.
1753 if (M) {
1754 ModuleFilename = HS.getCachedModuleFileName(M);
1755 return MS_ModuleCache;
1756 }
1757
1758 return MS_ModuleNotFound;
1759 }
1760
1761 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1762 StringRef ModuleName, SourceLocation ImportLoc,
1763 SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1764 // Search for a module with the given name.
1765 HeaderSearch &HS = PP->getHeaderSearchInfo();
1766 Module *M =
1767 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1768
1769 // Check for any configuration macros that have changed. This is done
1770 // immediately before potentially building a module in case this module
1771 // depends on having one of its configuration macros defined to successfully
1772 // build. If this is not done the user will never see the warning.
1773 if (M)
1774 checkConfigMacros(getPreprocessor(), M, ImportLoc);
1775
1776 // Select the source and filename for loading the named module.
1777 std::string ModuleFilename;
1778 ModuleSource Source =
1779 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1780 if (Source == MS_ModuleNotFound) {
1781 // We can't find a module, error out here.
1782 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1783 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1784 return nullptr;
1785 }
1786 if (ModuleFilename.empty()) {
1787 if (M && M->HasIncompatibleModuleFile) {
1788 // We tried and failed to load a module file for this module. Fall
1789 // back to textual inclusion for its headers.
1790 return ModuleLoadResult::ConfigMismatch;
1791 }
1792
1793 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1794 << ModuleName;
1795 return nullptr;
1796 }
1797
1798 // Create an ASTReader on demand.
1799 if (!getASTReader())
1800 createASTReader();
1801
1802 // Time how long it takes to load the module.
1803 llvm::Timer Timer;
1804 if (timerGroup)
1805 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1806 *timerGroup);
1807 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1808 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1809
1810 // Try to load the module file. If we are not trying to load from the
1811 // module cache, we don't know how to rebuild modules.
1812 unsigned ARRFlags = Source == MS_ModuleCache
1813 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1814 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1815 : Source == MS_PrebuiltModulePath
1816 ? 0
1817 : ASTReader::ARR_ConfigurationMismatch;
1818 switch (getASTReader()->ReadAST(ModuleFilename,
1819 Source == MS_PrebuiltModulePath
1820 ? serialization::MK_PrebuiltModule
1821 : Source == MS_ModuleBuildPragma
1822 ? serialization::MK_ExplicitModule
1823 : serialization::MK_ImplicitModule,
1824 ImportLoc, ARRFlags)) {
1825 case ASTReader::Success: {
1826 if (M)
1827 return M;
1828 assert(Source != MS_ModuleCache &&
1829 "missing module, but file loaded from cache");
1830
1831 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1832 // until the first call to ReadAST. Look it up now.
1833 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1834
1835 // Check whether M refers to the file in the prebuilt module path.
1836 if (M && M->getASTFile())
1837 if (auto ModuleFile = FileMgr->getOptionalFileRef(ModuleFilename))
1838 if (*ModuleFile == M->getASTFile())
1839 return M;
1840
1841 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1842 << ModuleName;
1843 return ModuleLoadResult();
1844 }
1845
1846 case ASTReader::OutOfDate:
1847 case ASTReader::Missing:
1848 // The most interesting case.
1849 break;
1850
1851 case ASTReader::ConfigurationMismatch:
1852 if (Source == MS_PrebuiltModulePath)
1853 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1854 // produce a warning here!
1855 getDiagnostics().Report(SourceLocation(),
1856 diag::warn_ast_file_config_mismatch)
1857 << ModuleFilename;
1858 // Fall through to error out.
1859 [[fallthrough]];
1860 case ASTReader::VersionMismatch:
1861 case ASTReader::HadErrors:
1862 ModuleLoader::HadFatalFailure = true;
1863 // FIXME: The ASTReader will already have complained, but can we shoehorn
1864 // that diagnostic information into a more useful form?
1865 return ModuleLoadResult();
1866
1867 case ASTReader::Failure:
1868 ModuleLoader::HadFatalFailure = true;
1869 return ModuleLoadResult();
1870 }
1871
1872 // ReadAST returned Missing or OutOfDate.
1873 if (Source != MS_ModuleCache) {
1874 // We don't know the desired configuration for this module and don't
1875 // necessarily even have a module map. Since ReadAST already produces
1876 // diagnostics for these two cases, we simply error out here.
1877 return ModuleLoadResult();
1878 }
1879
1880 // The module file is missing or out-of-date. Build it.
1881 assert(M && "missing module, but trying to compile for cache");
1882
1883 // Check whether there is a cycle in the module graph.
1884 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1885 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1886 for (; Pos != PosEnd; ++Pos) {
1887 if (Pos->first == ModuleName)
1888 break;
1889 }
1890
1891 if (Pos != PosEnd) {
1892 SmallString<256> CyclePath;
1893 for (; Pos != PosEnd; ++Pos) {
1894 CyclePath += Pos->first;
1895 CyclePath += " -> ";
1896 }
1897 CyclePath += ModuleName;
1898
1899 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1900 << ModuleName << CyclePath;
1901 return nullptr;
1902 }
1903
1904 // Check whether we have already attempted to build this module (but failed).
1905 if (FailedModules.contains(ModuleName)) {
1906 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1907 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1908 return nullptr;
1909 }
1910
1911 // Try to compile and then read the AST.
1912 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1913 ModuleFilename)) {
1914 assert(getDiagnostics().hasErrorOccurred() &&
1915 "undiagnosed error in compileModuleAndReadAST");
1916 FailedModules.insert(ModuleName);
1917 return nullptr;
1918 }
1919
1920 // Okay, we've rebuilt and now loaded the module.
1921 return M;
1922 }
1923
1924 ModuleLoadResult
1925 CompilerInstance::loadModule(SourceLocation ImportLoc,
1926 ModuleIdPath Path,
1927 Module::NameVisibilityKind Visibility,
1928 bool IsInclusionDirective) {
1929 // Determine what file we're searching from.
1930 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
1931 SourceLocation ModuleNameLoc = Path[0].getLoc();
1932
1933 // If we've already handled this import, just return the cached result.
1934 // This one-element cache is important to eliminate redundant diagnostics
1935 // when both the preprocessor and parser see the same import declaration.
1936 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1937 // Make the named module visible.
1938 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1939 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1940 ImportLoc);
1941 return LastModuleImportResult;
1942 }
1943
1944 // If we don't already have information on this module, load the module now.
1945 Module *Module = nullptr;
1946 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1947 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].getIdentifierInfo())) {
1948 // Use the cached result, which may be nullptr.
1949 Module = *MaybeModule;
1950 // Config macros are already checked before building a module, but they need
1951 // to be checked at each import location in case any of the config macros
1952 // have a new value at the current `ImportLoc`.
1953 if (Module)
1954 checkConfigMacros(getPreprocessor(), Module, ImportLoc);
1955 } else if (ModuleName == getLangOpts().CurrentModule) {
1956 // This is the module we're building.
1957 Module = PP->getHeaderSearchInfo().lookupModule(
1958 ModuleName, ImportLoc, /*AllowSearch*/ true,
1959 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1960
1961 // Config macros do not need to be checked here for two reasons.
1962 // * This will always be textual inclusion, and thus the config macros
1963 // actually do impact the content of the header.
1964 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
1965 // function as the `#include` or `#import` is textual.
1966
1967 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
1968 } else {
1969 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1970 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1971 if (!Result.isNormal())
1972 return Result;
1973 if (!Result)
1974 DisableGeneratingGlobalModuleIndex = true;
1975 Module = Result;
1976 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
1977 }
1978
1979 // If we never found the module, fail. Otherwise, verify the module and link
1980 // it up.
1981 if (!Module)
1982 return ModuleLoadResult();
1983
1984 // Verify that the rest of the module path actually corresponds to
1985 // a submodule.
1986 bool MapPrivateSubModToTopLevel = false;
1987 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1988 StringRef Name = Path[I].getIdentifierInfo()->getName();
1989 clang::Module *Sub = Module->findSubmodule(Name);
1990
1991 // If the user is requesting Foo.Private and it doesn't exist, try to
1992 // match Foo_Private and emit a warning asking for the user to write
1993 // @import Foo_Private instead. FIXME: remove this when existing clients
1994 // migrate off of Foo.Private syntax.
1995 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
1996 SmallString<128> PrivateModule(Module->Name);
1997 PrivateModule.append("_Private");
1998
1999 SmallVector<IdentifierLoc, 2> PrivPath;
2000 auto &II = PP->getIdentifierTable().get(
2001 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2002 PrivPath.emplace_back(Path[0].getLoc(), &II);
2003
2004 std::string FileName;
2005 // If there is a modulemap module or prebuilt module, load it.
2006 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2007 !IsInclusionDirective) ||
2008 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2009 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2010 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2011 if (Sub) {
2012 MapPrivateSubModToTopLevel = true;
2013 PP->markClangModuleAsAffecting(Module);
2014 if (!getDiagnostics().isIgnored(
2015 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2016 getDiagnostics().Report(Path[I].getLoc(),
2017 diag::warn_no_priv_submodule_use_toplevel)
2018 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2019 << PrivateModule
2020 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2021 << FixItHint::CreateReplacement(SourceRange(Path[0].getLoc()),
2022 PrivateModule);
2023 getDiagnostics().Report(Sub->DefinitionLoc,
2024 diag::note_private_top_level_defined);
2025 }
2026 }
2027 }
2028
2029 if (!Sub) {
2030 // Attempt to perform typo correction to find a module name that works.
2031 SmallVector<StringRef, 2> Best;
2032 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2033
2034 for (class Module *SubModule : Module->submodules()) {
2035 unsigned ED =
2036 Name.edit_distance(SubModule->Name,
2037 /*AllowReplacements=*/true, BestEditDistance);
2038 if (ED <= BestEditDistance) {
2039 if (ED < BestEditDistance) {
2040 Best.clear();
2041 BestEditDistance = ED;
2042 }
2043
2044 Best.push_back(SubModule->Name);
2045 }
2046 }
2047
2048 // If there was a clear winner, user it.
2049 if (Best.size() == 1) {
2050 getDiagnostics().Report(Path[I].getLoc(),
2051 diag::err_no_submodule_suggest)
2052 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2053 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2054 << FixItHint::CreateReplacement(SourceRange(Path[I].getLoc()),
2055 Best[0]);
2056
2057 Sub = Module->findSubmodule(Best[0]);
2058 }
2059 }
2060
2061 if (!Sub) {
2062 // No submodule by this name. Complain, and don't look for further
2063 // submodules.
2064 getDiagnostics().Report(Path[I].getLoc(), diag::err_no_submodule)
2065 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2066 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2067 break;
2068 }
2069
2070 Module = Sub;
2071 }
2072
2073 // Make the named module visible, if it's not already part of the module
2074 // we are parsing.
2075 if (ModuleName != getLangOpts().CurrentModule) {
2076 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2077 // We have an umbrella header or directory that doesn't actually include
2078 // all of the headers within the directory it covers. Complain about
2079 // this missing submodule and recover by forgetting that we ever saw
2080 // this submodule.
2081 // FIXME: Should we detect this at module load time? It seems fairly
2082 // expensive (and rare).
2083 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2084 << Module->getFullModuleName()
2085 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2086
2087 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
2088 }
2089
2090 // Check whether this module is available.
2091 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
2092 *Module, getDiagnostics())) {
2093 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2094 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2095 LastModuleImportLoc = ImportLoc;
2096 LastModuleImportResult = ModuleLoadResult();
2097 return ModuleLoadResult();
2098 }
2099
2100 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2101 }
2102
2103 // Resolve any remaining module using export_as for this one.
2104 getPreprocessor()
2105 .getHeaderSearchInfo()
2106 .getModuleMap()
2107 .resolveLinkAsDependencies(Module->getTopLevelModule());
2108
2109 LastModuleImportLoc = ImportLoc;
2110 LastModuleImportResult = ModuleLoadResult(Module);
2111 return LastModuleImportResult;
2112 }
2113
2114 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2115 StringRef ModuleName,
2116 StringRef Source) {
2117 // Avoid creating filenames with special characters.
2118 SmallString<128> CleanModuleName(ModuleName);
2119 for (auto &C : CleanModuleName)
2120 if (!isAlphanumeric(C))
2121 C = '_';
2122
2123 // FIXME: Using a randomized filename here means that our intermediate .pcm
2124 // output is nondeterministic (as .pcm files refer to each other by name).
2125 // Can this affect the output in any way?
2126 SmallString<128> ModuleFileName;
2127 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2128 CleanModuleName, "pcm", ModuleFileName)) {
2129 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2130 << ModuleFileName << EC.message();
2131 return;
2132 }
2133 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2134
2135 FrontendInputFile Input(
2136 ModuleMapFileName,
2137 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2138 InputKind::ModuleMap, /*Preprocessed*/true));
2139
2140 std::string NullTerminatedSource(Source.str());
2141
2142 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2143 StringRef(), ModuleFileName);
2144
2145 // Create a virtual file containing our desired source.
2146 // FIXME: We shouldn't need to do this.
2147 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2148 ModuleMapFileName, NullTerminatedSource.size(), 0);
2149 Other->getSourceManager().overrideFileContents(
2150 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2151
2152 Other->BuiltModules = std::move(BuiltModules);
2153 Other->DeleteBuiltModules = false;
2154
2155 // Build the module, inheriting any modules that we've built locally.
2156 bool Success = compileModule(ImportLoc, ModuleName, ModuleFileName, *Other);
2157
2158 BuiltModules = std::move(Other->BuiltModules);
2159
2160 if (Success) {
2161 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2162 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2163 }
2164 }
2165
2166 void CompilerInstance::makeModuleVisible(Module *Mod,
2167 Module::NameVisibilityKind Visibility,
2168 SourceLocation ImportLoc) {
2169 if (!TheASTReader)
2170 createASTReader();
2171 if (!TheASTReader)
2172 return;
2173
2174 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2175 }
2176
2177 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2178 SourceLocation TriggerLoc) {
2179 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2180 return nullptr;
2181 if (!TheASTReader)
2182 createASTReader();
2183 // Can't do anything if we don't have the module manager.
2184 if (!TheASTReader)
2185 return nullptr;
2186 // Get an existing global index. This loads it if not already
2187 // loaded.
2188 TheASTReader->loadGlobalIndex();
2189 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2190 // If the global index doesn't exist, create it.
2191 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2192 hasPreprocessor()) {
2193 llvm::sys::fs::create_directories(
2194 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2195 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2196 getFileManager(), getPCHContainerReader(),
2197 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2198 // FIXME this drops the error on the floor. This code is only used for
2199 // typo correction and drops more than just this one source of errors
2200 // (such as the directory creation failure above). It should handle the
2201 // error.
2202 consumeError(std::move(Err));
2203 return nullptr;
2204 }
2205 TheASTReader->resetForReload();
2206 TheASTReader->loadGlobalIndex();
2207 GlobalIndex = TheASTReader->getGlobalIndex();
2208 }
2209 // For finding modules needing to be imported for fixit messages,
2210 // we need to make the global index cover all modules, so we do that here.
2211 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2212 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2213 bool RecreateIndex = false;
2214 for (ModuleMap::module_iterator I = MMap.module_begin(),
2215 E = MMap.module_end(); I != E; ++I) {
2216 Module *TheModule = I->second;
2217 OptionalFileEntryRef Entry = TheModule->getASTFile();
2218 if (!Entry) {
2219 SmallVector<IdentifierLoc, 2> Path;
2220 Path.emplace_back(TriggerLoc,
2221 getPreprocessor().getIdentifierInfo(TheModule->Name));
2222 std::reverse(Path.begin(), Path.end());
2223 // Load a module as hidden. This also adds it to the global index.
2224 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2225 RecreateIndex = true;
2226 }
2227 }
2228 if (RecreateIndex) {
2229 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2230 getFileManager(), getPCHContainerReader(),
2231 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2232 // FIXME As above, this drops the error on the floor.
2233 consumeError(std::move(Err));
2234 return nullptr;
2235 }
2236 TheASTReader->resetForReload();
2237 TheASTReader->loadGlobalIndex();
2238 GlobalIndex = TheASTReader->getGlobalIndex();
2239 }
2240 HaveFullGlobalModuleIndex = true;
2241 }
2242 return GlobalIndex;
2243 }
2244
2245 // Check global module index for missing imports.
2246 bool
2247 CompilerInstance::lookupMissingImports(StringRef Name,
2248 SourceLocation TriggerLoc) {
2249 // Look for the symbol in non-imported modules, but only if an error
2250 // actually occurred.
2251 if (!buildingModule()) {
2252 // Load global module index, or retrieve a previously loaded one.
2253 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2254 TriggerLoc);
2255
2256 // Only if we have a global index.
2257 if (GlobalIndex) {
2258 GlobalModuleIndex::HitSet FoundModules;
2259
2260 // Find the modules that reference the identifier.
2261 // Note that this only finds top-level modules.
2262 // We'll let diagnoseTypo find the actual declaration module.
2263 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2264 return true;
2265 }
2266 }
2267
2268 return false;
2269 }
2270 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2271
2272 void CompilerInstance::setExternalSemaSource(
2273 IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2274 ExternalSemaSrc = std::move(ESS);
2275 }