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/FileManager.h"
16 #include "clang/Basic/LangStandard.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/Stack.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/Version.h"
21 #include "clang/Config/config.h"
22 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
23 #include "clang/Frontend/FrontendAction.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Frontend/FrontendDiagnostic.h"
26 #include "clang/Frontend/LogDiagnosticPrinter.h"
27 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
28 #include "clang/Frontend/TextDiagnosticPrinter.h"
29 #include "clang/Frontend/Utils.h"
30 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Sema/CodeCompleteConsumer.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Serialization/ASTReader.h"
37 #include "clang/Serialization/GlobalModuleIndex.h"
38 #include "clang/Serialization/InMemoryModuleCache.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/BuryPointer.h"
41 #include "llvm/Support/CrashRecoveryContext.h"
42 #include "llvm/Support/Errc.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/LockFileManager.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Program.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/raw_ostream.h"
56 using namespace clang;
58 CompilerInstance::CompilerInstance(
59 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
60 InMemoryModuleCache *SharedModuleCache)
61 : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
62 Invocation(new CompilerInvocation()),
63 ModuleCache(SharedModuleCache ? SharedModuleCache
64 : new InMemoryModuleCache),
65 ThePCHContainerOperations(std::move(PCHContainerOps)) {}
67 CompilerInstance::~CompilerInstance() {
68 assert(OutputFiles.empty() && "Still output files in flight?");
71 void CompilerInstance::setInvocation(
72 std::shared_ptr<CompilerInvocation> Value) {
73 Invocation = std::move(Value);
76 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
77 return (BuildGlobalModuleIndex ||
78 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
79 getFrontendOpts().GenerateGlobalModuleIndex)) &&
83 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
87 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
88 OwnedVerboseOutputStream.release();
89 VerboseOutputStream = &Value;
92 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
93 OwnedVerboseOutputStream.swap(Value);
94 VerboseOutputStream = OwnedVerboseOutputStream.get();
97 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
98 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
100 void CompilerInstance::setFileManager(FileManager *Value) {
104 void CompilerInstance::setSourceManager(SourceManager *Value) {
108 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
109 PP = std::move(Value);
112 void CompilerInstance::setASTContext(ASTContext *Value) {
115 if (Context && Consumer)
116 getASTConsumer().Initialize(getASTContext());
119 void CompilerInstance::setSema(Sema *S) {
123 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
124 Consumer = std::move(Value);
126 if (Context && Consumer)
127 getASTConsumer().Initialize(getASTContext());
130 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
131 CompletionConsumer.reset(Value);
134 std::unique_ptr<Sema> CompilerInstance::takeSema() {
135 return std::move(TheSema);
138 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
139 return ModuleManager;
141 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
142 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
143 "Expected ASTReader to use the same PCM cache");
144 ModuleManager = std::move(Reader);
147 std::shared_ptr<ModuleDependencyCollector>
148 CompilerInstance::getModuleDepCollector() const {
149 return ModuleDepCollector;
152 void CompilerInstance::setModuleDepCollector(
153 std::shared_ptr<ModuleDependencyCollector> Collector) {
154 ModuleDepCollector = std::move(Collector);
157 static void collectHeaderMaps(const HeaderSearch &HS,
158 std::shared_ptr<ModuleDependencyCollector> MDC) {
159 SmallVector<std::string, 4> HeaderMapFileNames;
160 HS.getHeaderMapFileNames(HeaderMapFileNames);
161 for (auto &Name : HeaderMapFileNames)
165 static void collectIncludePCH(CompilerInstance &CI,
166 std::shared_ptr<ModuleDependencyCollector> MDC) {
167 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
168 if (PPOpts.ImplicitPCHInclude.empty())
171 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
172 FileManager &FileMgr = CI.getFileManager();
173 auto PCHDir = FileMgr.getDirectory(PCHInclude);
175 MDC->addFile(PCHInclude);
180 SmallString<128> DirNative;
181 llvm::sys::path::native((*PCHDir)->getName(), DirNative);
182 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
183 SimpleASTReaderListener Validator(CI.getPreprocessor());
184 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
185 Dir != DirEnd && !EC; Dir.increment(EC)) {
186 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
187 // used here since we're not interested in validating the PCH at this time,
188 // but only to check whether this is a file containing an AST.
189 if (!ASTReader::readASTFileControlBlock(
190 Dir->path(), FileMgr, CI.getPCHContainerReader(),
191 /*FindModuleFileExtensions=*/false, Validator,
192 /*ValidateDiagnosticOptions=*/false))
193 MDC->addFile(Dir->path());
197 static void collectVFSEntries(CompilerInstance &CI,
198 std::shared_ptr<ModuleDependencyCollector> MDC) {
199 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
202 // Collect all VFS found.
203 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
204 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
205 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
206 llvm::MemoryBuffer::getFile(VFSFile);
209 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
210 /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
213 for (auto &E : VFSEntries)
214 MDC->addFile(E.VPath, E.RPath);
218 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
219 const CodeGenOptions *CodeGenOpts,
220 DiagnosticsEngine &Diags) {
222 std::unique_ptr<raw_ostream> StreamOwner;
223 raw_ostream *OS = &llvm::errs();
224 if (DiagOpts->DiagnosticLogFile != "-") {
225 // Create the output stream.
226 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
227 DiagOpts->DiagnosticLogFile, EC,
228 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
230 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
231 << DiagOpts->DiagnosticLogFile << EC.message();
233 FileOS->SetUnbuffered();
235 StreamOwner = std::move(FileOS);
239 // Chain in the diagnostic client which will log the diagnostics.
240 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
241 std::move(StreamOwner));
243 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
244 if (Diags.ownsClient()) {
246 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
249 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
253 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
254 DiagnosticsEngine &Diags,
255 StringRef OutputFile) {
256 auto SerializedConsumer =
257 clang::serialized_diags::create(OutputFile, DiagOpts);
259 if (Diags.ownsClient()) {
260 Diags.setClient(new ChainedDiagnosticConsumer(
261 Diags.takeClient(), std::move(SerializedConsumer)));
263 Diags.setClient(new ChainedDiagnosticConsumer(
264 Diags.getClient(), std::move(SerializedConsumer)));
268 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
269 bool ShouldOwnClient) {
270 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
271 ShouldOwnClient, &getCodeGenOpts());
274 IntrusiveRefCntPtr<DiagnosticsEngine>
275 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
276 DiagnosticConsumer *Client,
277 bool ShouldOwnClient,
278 const CodeGenOptions *CodeGenOpts) {
279 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
280 IntrusiveRefCntPtr<DiagnosticsEngine>
281 Diags(new DiagnosticsEngine(DiagID, Opts));
283 // Create the diagnostic client for reporting errors or for
284 // implementing -verify.
286 Diags->setClient(Client, ShouldOwnClient);
288 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
290 // Chain in -verify checker, if requested.
291 if (Opts->VerifyDiagnostics)
292 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
294 // Chain in -diagnostic-log-file dumper, if requested.
295 if (!Opts->DiagnosticLogFile.empty())
296 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
298 if (!Opts->DiagnosticSerializationFile.empty())
299 SetupSerializedDiagnostics(Opts, *Diags,
300 Opts->DiagnosticSerializationFile);
302 // Configure our handling of diagnostics.
303 ProcessWarningOptions(*Diags, *Opts);
310 FileManager *CompilerInstance::createFileManager(
311 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
313 VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
314 : createVFSFromCompilerInvocation(getInvocation(),
316 assert(VFS && "FileManager has no VFS?");
317 FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
318 return FileMgr.get();
323 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
324 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
327 // Initialize the remapping of files to alternative contents, e.g.,
328 // those specified through other files.
329 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
330 SourceManager &SourceMgr,
331 FileManager &FileMgr,
332 const PreprocessorOptions &InitOpts) {
333 // Remap files in the source manager (with buffers).
334 for (const auto &RB : InitOpts.RemappedFileBuffers) {
335 // Create the file entry for the file that we're mapping from.
336 const FileEntry *FromFile =
337 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
339 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
340 if (!InitOpts.RetainRemappedFileBuffers)
345 // Override the contents of the "from" file with the contents of
347 SourceMgr.overrideFileContents(FromFile, RB.second,
348 InitOpts.RetainRemappedFileBuffers);
351 // Remap files in the source manager (with other files).
352 for (const auto &RF : InitOpts.RemappedFiles) {
353 // Find the file that we're mapping to.
354 auto ToFile = FileMgr.getFile(RF.second);
356 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
360 // Create the file entry for the file that we're mapping from.
361 const FileEntry *FromFile =
362 FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
364 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
368 // Override the contents of the "from" file with the contents of
370 SourceMgr.overrideFileContents(FromFile, *ToFile);
373 SourceMgr.setOverridenFilesKeepOriginalName(
374 InitOpts.RemappedFilesKeepOriginalName);
379 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
380 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
382 // The module manager holds a reference to the old preprocessor (if any).
383 ModuleManager.reset();
385 // Create the Preprocessor.
386 HeaderSearch *HeaderInfo =
387 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
388 getDiagnostics(), getLangOpts(), &getTarget());
389 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
390 getDiagnostics(), getLangOpts(),
391 getSourceManager(), *HeaderInfo, *this,
392 /*IdentifierInfoLookup=*/nullptr,
393 /*OwnsHeaderSearch=*/true, TUKind);
394 getTarget().adjust(getLangOpts());
395 PP->Initialize(getTarget(), getAuxTarget());
397 if (PPOpts.DetailedRecord)
398 PP->createPreprocessingRecord();
400 // Apply remappings to the source manager.
401 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
402 PP->getFileManager(), PPOpts);
404 // Predefine macros and configure the preprocessor.
405 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
408 // Initialize the header search object. In CUDA compilations, we use the aux
409 // triple (the host triple) to initialize our header search, since we need to
410 // find the host headers in order to compile the CUDA code.
411 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
412 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
413 PP->getAuxTargetInfo())
414 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
416 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
417 PP->getLangOpts(), *HeaderSearchTriple);
419 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
421 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
422 PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
424 // Handle generating dependencies, if requested.
425 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
426 if (!DepOpts.OutputFile.empty())
427 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
428 if (!DepOpts.DOTOutputFile.empty())
429 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
430 getHeaderSearchOpts().Sysroot);
432 // If we don't have a collector, but we are collecting module dependencies,
433 // then we're the top level compiler instance and need to create one.
434 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
435 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
436 DepOpts.ModuleDependencyOutputDir);
439 // If there is a module dep collector, register with other dep collectors
440 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
441 if (ModuleDepCollector) {
442 addDependencyCollector(ModuleDepCollector);
443 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
444 collectIncludePCH(*this, ModuleDepCollector);
445 collectVFSEntries(*this, ModuleDepCollector);
448 for (auto &Listener : DependencyCollectors)
449 Listener->attachToPreprocessor(*PP);
451 // Handle generating header include information, if requested.
452 if (DepOpts.ShowHeaderIncludes)
453 AttachHeaderIncludeGen(*PP, DepOpts);
454 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
455 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
456 if (OutputPath == "-")
458 AttachHeaderIncludeGen(*PP, DepOpts,
459 /*ShowAllHeaders=*/true, OutputPath,
460 /*ShowDepth=*/false);
463 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
464 AttachHeaderIncludeGen(*PP, DepOpts,
465 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
466 /*ShowDepth=*/true, /*MSStyle=*/true);
470 std::string CompilerInstance::getSpecificModuleCachePath() {
471 // Set up the module path, including the hash for the
472 // module-creation options.
473 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
474 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
475 llvm::sys::path::append(SpecificModuleCache,
476 getInvocation().getModuleHash());
477 return SpecificModuleCache.str();
482 void CompilerInstance::createASTContext() {
483 Preprocessor &PP = getPreprocessor();
484 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
485 PP.getIdentifierTable(), PP.getSelectorTable(),
486 PP.getBuiltinInfo());
487 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
488 setASTContext(Context);
493 void CompilerInstance::createPCHExternalASTSource(
494 StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
495 void *DeserializationListener, bool OwnDeserializationListener) {
496 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
497 ModuleManager = createPCHExternalASTSource(
498 Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
499 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
500 getASTContext(), getPCHContainerReader(),
501 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
502 DeserializationListener, OwnDeserializationListener, Preamble,
503 getFrontendOpts().UseGlobalModuleIndex);
506 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
507 StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
508 bool AllowPCHWithCompilerErrors, Preprocessor &PP,
509 InMemoryModuleCache &ModuleCache, ASTContext &Context,
510 const PCHContainerReader &PCHContainerRdr,
511 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
512 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
513 void *DeserializationListener, bool OwnDeserializationListener,
514 bool Preamble, bool UseGlobalModuleIndex) {
515 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
517 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
518 PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
519 Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
520 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
521 HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
522 UseGlobalModuleIndex));
524 // We need the external source to be set up before we read the AST, because
525 // eagerly-deserialized declarations may use it.
526 Context.setExternalSource(Reader.get());
528 Reader->setDeserializationListener(
529 static_cast<ASTDeserializationListener *>(DeserializationListener),
530 /*TakeOwnership=*/OwnDeserializationListener);
532 for (auto &Listener : DependencyCollectors)
533 Listener->attachToASTReader(*Reader);
535 switch (Reader->ReadAST(Path,
536 Preamble ? serialization::MK_Preamble
537 : serialization::MK_PCH,
539 ASTReader::ARR_None)) {
540 case ASTReader::Success:
541 // Set the predefines buffer as suggested by the PCH reader. Typically, the
542 // predefines buffer will be empty.
543 PP.setPredefines(Reader->getSuggestedPredefines());
546 case ASTReader::Failure:
547 // Unrecoverable failure: don't even try to process the input file.
550 case ASTReader::Missing:
551 case ASTReader::OutOfDate:
552 case ASTReader::VersionMismatch:
553 case ASTReader::ConfigurationMismatch:
554 case ASTReader::HadErrors:
555 // No suitable PCH file could be found. Return an error.
559 Context.setExternalSource(nullptr);
565 static bool EnableCodeCompletion(Preprocessor &PP,
569 // Tell the source manager to chop off the given file at a specific
571 auto Entry = PP.getFileManager().getFile(Filename);
573 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
578 // Truncate the named file at the given line/column.
579 PP.SetCodeCompletionPoint(*Entry, Line, Column);
583 void CompilerInstance::createCodeCompletionConsumer() {
584 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
585 if (!CompletionConsumer) {
586 setCodeCompletionConsumer(
587 createCodeCompletionConsumer(getPreprocessor(),
588 Loc.FileName, Loc.Line, Loc.Column,
589 getFrontendOpts().CodeCompleteOpts,
591 if (!CompletionConsumer)
593 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
594 Loc.Line, Loc.Column)) {
595 setCodeCompletionConsumer(nullptr);
600 void CompilerInstance::createFrontendTimer() {
601 FrontendTimerGroup.reset(
602 new llvm::TimerGroup("frontend", "Clang front-end time report"));
604 new llvm::Timer("frontend", "Clang front-end timer",
605 *FrontendTimerGroup));
608 CodeCompleteConsumer *
609 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
613 const CodeCompleteOptions &Opts,
615 if (EnableCodeCompletion(PP, Filename, Line, Column))
618 // Set up the creation routine for code-completion.
619 return new PrintingCodeCompleteConsumer(Opts, OS);
622 void CompilerInstance::createSema(TranslationUnitKind TUKind,
623 CodeCompleteConsumer *CompletionConsumer) {
624 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
625 TUKind, CompletionConsumer));
626 // Attach the external sema source if there is any.
627 if (ExternalSemaSrc) {
628 TheSema->addExternalSource(ExternalSemaSrc.get());
629 ExternalSemaSrc->InitializeSema(*TheSema);
635 void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
636 OutputFiles.push_back(std::move(OutFile));
639 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
640 for (OutputFile &OF : OutputFiles) {
641 if (!OF.TempFilename.empty()) {
643 llvm::sys::fs::remove(OF.TempFilename);
645 SmallString<128> NewOutFile(OF.Filename);
647 // If '-working-directory' was passed, the output filename should be
649 FileMgr->FixupRelativePath(NewOutFile);
650 if (std::error_code ec =
651 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
652 getDiagnostics().Report(diag::err_unable_to_rename_temp)
653 << OF.TempFilename << OF.Filename << ec.message();
655 llvm::sys::fs::remove(OF.TempFilename);
658 } else if (!OF.Filename.empty() && EraseFiles)
659 llvm::sys::fs::remove(OF.Filename);
662 if (DeleteBuiltModules) {
663 for (auto &Module : BuiltModules)
664 llvm::sys::fs::remove(Module.second);
665 BuiltModules.clear();
667 NonSeekStream.reset();
670 std::unique_ptr<raw_pwrite_stream>
671 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
672 StringRef Extension) {
673 return createOutputFile(getFrontendOpts().OutputFile, Binary,
674 /*RemoveFileOnSignal=*/true, InFile, Extension,
675 /*UseTemporary=*/true);
678 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
679 return std::make_unique<llvm::raw_null_ostream>();
682 std::unique_ptr<raw_pwrite_stream>
683 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
684 bool RemoveFileOnSignal, StringRef InFile,
685 StringRef Extension, bool UseTemporary,
686 bool CreateMissingDirectories) {
687 std::string OutputPathName, TempPathName;
689 std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
690 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
691 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
693 getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
698 // Add the output file -- but don't try to remove "-", since this means we are
701 OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
706 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
707 StringRef OutputPath, std::error_code &Error, bool Binary,
708 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
709 bool UseTemporary, bool CreateMissingDirectories,
710 std::string *ResultPathName, std::string *TempPathName) {
711 assert((!CreateMissingDirectories || UseTemporary) &&
712 "CreateMissingDirectories is only allowed when using temporary files");
714 std::string OutFile, TempFile;
715 if (!OutputPath.empty()) {
716 OutFile = OutputPath;
717 } else if (InFile == "-") {
719 } else if (!Extension.empty()) {
720 SmallString<128> Path(InFile);
721 llvm::sys::path::replace_extension(Path, Extension);
722 OutFile = Path.str();
727 std::unique_ptr<llvm::raw_fd_ostream> OS;
732 UseTemporary = false;
734 llvm::sys::fs::file_status Status;
735 llvm::sys::fs::status(OutputPath, Status);
736 if (llvm::sys::fs::exists(Status)) {
737 // Fail early if we can't write to the final destination.
738 if (!llvm::sys::fs::can_write(OutputPath)) {
739 Error = make_error_code(llvm::errc::operation_not_permitted);
743 // Don't use a temporary if the output is a special file. This handles
744 // things like '-o /dev/null'
745 if (!llvm::sys::fs::is_regular_file(Status))
746 UseTemporary = false;
752 // Create a temporary file.
753 // Insert -%%%%%%%% before the extension (if any), and because some tools
754 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
755 // artifacts, also append .tmp.
756 StringRef OutputExtension = llvm::sys::path::extension(OutFile);
757 SmallString<128> TempPath =
758 StringRef(OutFile).drop_back(OutputExtension.size());
759 TempPath += "-%%%%%%%%";
760 TempPath += OutputExtension;
764 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
766 if (CreateMissingDirectories &&
767 EC == llvm::errc::no_such_file_or_directory) {
768 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
769 EC = llvm::sys::fs::create_directories(Parent);
771 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
776 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
777 OSFile = TempFile = TempPath.str();
779 // If we failed to create the temporary, fallback to writing to the file
780 // directly. This handles the corner case where we cannot write to the
781 // directory, but can write to the file.
786 OS.reset(new llvm::raw_fd_ostream(
788 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text)));
793 // Make sure the out stream file gets removed if we crash.
794 if (RemoveFileOnSignal)
795 llvm::sys::RemoveFileOnSignal(OSFile);
798 *ResultPathName = OutFile;
800 *TempPathName = TempFile;
802 if (!Binary || OS->supportsSeeking())
803 return std::move(OS);
805 auto B = std::make_unique<llvm::buffer_ostream>(*OS);
806 assert(!NonSeekStream);
807 NonSeekStream = std::move(OS);
811 // Initialization Utilities
813 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
814 return InitializeSourceManager(
815 Input, getDiagnostics(), getFileManager(), getSourceManager(),
816 hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
817 getDependencyOutputOpts(), getFrontendOpts());
821 bool CompilerInstance::InitializeSourceManager(
822 const FrontendInputFile &Input, DiagnosticsEngine &Diags,
823 FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
824 DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
825 SrcMgr::CharacteristicKind Kind =
826 Input.getKind().getFormat() == InputKind::ModuleMap
827 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
828 : SrcMgr::C_User_ModuleMap
829 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
831 if (Input.isBuffer()) {
832 SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned,
833 Input.getBuffer(), Kind));
834 assert(SourceMgr.getMainFileID().isValid() &&
835 "Couldn't establish MainFileID!");
839 StringRef InputFile = Input.getFile();
841 // Figure out where to get and map in the main file.
842 if (InputFile != "-") {
843 auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
845 // FIXME: include the error in the diagnostic.
846 consumeError(FileOrErr.takeError());
847 Diags.Report(diag::err_fe_error_reading) << InputFile;
850 FileEntryRef File = *FileOrErr;
852 // The natural SourceManager infrastructure can't currently handle named
853 // pipes, but we would at least like to accept them for the main
854 // file. Detect them here, read them with the volatile flag so FileMgr will
855 // pick up the correct size, and simply override their contents as we do for
857 if (File.getFileEntry().isNamedPipe()) {
859 FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true);
861 // Create a new virtual file that will have the correct size.
862 const FileEntry *FE =
863 FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
864 SourceMgr.overrideFileContents(FE, std::move(*MB));
865 SourceMgr.setMainFileID(
866 SourceMgr.createFileID(FE, SourceLocation(), Kind));
868 Diags.Report(diag::err_cannot_open_file) << InputFile
869 << MB.getError().message();
873 SourceMgr.setMainFileID(
874 SourceMgr.createFileID(File, SourceLocation(), Kind));
877 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
878 llvm::MemoryBuffer::getSTDIN();
879 if (std::error_code EC = SBOrErr.getError()) {
880 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
883 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
885 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
886 SB->getBufferSize(), 0);
887 SourceMgr.setMainFileID(
888 SourceMgr.createFileID(File, SourceLocation(), Kind));
889 SourceMgr.overrideFileContents(File, std::move(SB));
892 assert(SourceMgr.getMainFileID().isValid() &&
893 "Couldn't establish MainFileID!");
897 // High-Level Operations
899 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
900 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
901 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
902 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
904 // Mark this point as the bottom of the stack if we don't have somewhere
905 // better. We generally expect frontend actions to be invoked with (nearly)
906 // DesiredStackSpace available.
909 raw_ostream &OS = getVerboseOutputStream();
911 if (!Act.PrepareToExecute(*this))
914 // Create the target instance.
915 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
916 getInvocation().TargetOpts));
920 // Create TargetInfo for the other side of CUDA and OpenMP compilation.
921 if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) &&
922 !getFrontendOpts().AuxTriple.empty()) {
923 auto TO = std::make_shared<TargetOptions>();
924 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
925 TO->HostTriple = getTarget().getTriple().str();
926 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
929 // Inform the target of the language options.
931 // FIXME: We shouldn't need to do this, the target should be immutable once
932 // created. This complexity should be lifted elsewhere.
933 getTarget().adjust(getLangOpts());
935 // Adjust target options based on codegen options.
936 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
938 if (auto *Aux = getAuxTarget())
939 getTarget().setAuxTarget(Aux);
941 // rewriter project will change target built-in bool type from its default.
942 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
943 getTarget().noSignedCharForObjCBool();
945 // Validate/process some options.
946 if (getHeaderSearchOpts().Verbose)
947 OS << "clang -cc1 version " CLANG_VERSION_STRING
948 << " based upon " << BACKEND_PACKAGE_STRING
949 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
951 if (getFrontendOpts().ShowTimers)
952 createFrontendTimer();
954 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
955 llvm::EnableStatistics(false);
957 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
958 // Reset the ID tables if we are reusing the SourceManager and parsing
960 if (hasSourceManager() && !Act.isModelParsingAction())
961 getSourceManager().clearIDTables();
963 if (Act.BeginSourceFile(*this, FIF)) {
964 if (llvm::Error Err = Act.Execute()) {
965 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
971 // Notify the diagnostic client that all files were processed.
972 getDiagnostics().getClient()->finish();
974 if (getDiagnosticOpts().ShowCarets) {
975 // We can have multiple diagnostics sharing one diagnostic client.
976 // Get the total number of warnings/errors from the client.
977 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
978 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
981 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
982 if (NumWarnings && NumErrors)
985 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
986 if (NumWarnings || NumErrors) {
988 if (getLangOpts().CUDA) {
989 if (!getLangOpts().CUDAIsDevice) {
990 OS << " when compiling for host";
992 OS << " when compiling for " << getTargetOpts().CPU;
999 if (getFrontendOpts().ShowStats) {
1000 if (hasFileManager()) {
1001 getFileManager().PrintStats();
1004 llvm::PrintStatistics(OS);
1006 StringRef StatsFile = getFrontendOpts().StatsFile;
1007 if (!StatsFile.empty()) {
1009 auto StatS = std::make_unique<llvm::raw_fd_ostream>(
1010 StatsFile, EC, llvm::sys::fs::OF_Text);
1012 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1013 << StatsFile << EC.message();
1015 llvm::PrintStatisticsJSON(*StatS);
1019 return !getDiagnostics().getClient()->getNumErrors();
1022 /// Determine the appropriate source input kind based on language
1024 static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1025 if (LangOpts.OpenCL)
1026 return Language::OpenCL;
1028 return Language::CUDA;
1030 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1031 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1034 /// Compile a module file for the given module, using the options
1035 /// provided by the importing compiler instance. Returns true if the module
1036 /// was built without errors.
1038 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1039 StringRef ModuleName, FrontendInputFile Input,
1040 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1041 llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
1042 [](CompilerInstance &) {},
1043 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1044 [](CompilerInstance &) {}) {
1045 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1047 // Construct a compiler invocation for creating this module.
1049 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
1051 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1053 // For any options that aren't intended to affect how a module is built,
1054 // reset them to their default values.
1055 Invocation->getLangOpts()->resetNonModularOptions();
1056 PPOpts.resetNonModularOptions();
1058 // Remove any macro definitions that are explicitly ignored by the module.
1059 // They aren't supposed to affect how the module is built anyway.
1060 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1061 PPOpts.Macros.erase(
1062 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1063 [&HSOpts](const std::pair<std::string, bool> &def) {
1064 StringRef MacroDef = def.first;
1065 return HSOpts.ModulesIgnoreMacros.count(
1066 llvm::CachedHashString(MacroDef.split('=').first)) > 0;
1068 PPOpts.Macros.end());
1070 // If the original compiler invocation had -fmodule-name, pass it through.
1071 Invocation->getLangOpts()->ModuleName =
1072 ImportingInstance.getInvocation().getLangOpts()->ModuleName;
1074 // Note the name of the module we're building.
1075 Invocation->getLangOpts()->CurrentModule = ModuleName;
1077 // Make sure that the failed-module structure has been allocated in
1078 // the importing instance, and propagate the pointer to the newly-created
1080 PreprocessorOptions &ImportingPPOpts
1081 = ImportingInstance.getInvocation().getPreprocessorOpts();
1082 if (!ImportingPPOpts.FailedModules)
1083 ImportingPPOpts.FailedModules =
1084 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1085 PPOpts.FailedModules = ImportingPPOpts.FailedModules;
1087 // If there is a module map file, build the module using the module map.
1088 // Set up the inputs/outputs so that we build the module from its umbrella
1090 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1091 FrontendOpts.OutputFile = ModuleFileName.str();
1092 FrontendOpts.DisableFree = false;
1093 FrontendOpts.GenerateGlobalModuleIndex = false;
1094 FrontendOpts.BuildingImplicitModule = true;
1095 FrontendOpts.OriginalModuleMap = OriginalModuleMapFile;
1096 // Force implicitly-built modules to hash the content of the module file.
1097 HSOpts.ModulesHashContent = true;
1098 FrontendOpts.Inputs = {Input};
1100 // Don't free the remapped file buffers; they are owned by our caller.
1101 PPOpts.RetainRemappedFileBuffers = true;
1103 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1104 assert(ImportingInstance.getInvocation().getModuleHash() ==
1105 Invocation->getModuleHash() && "Module hash mismatch!");
1107 // Construct a compiler instance that will be used to actually create the
1108 // module. Since we're sharing an in-memory module cache,
1109 // CompilerInstance::CompilerInstance is responsible for finalizing the
1110 // buffers to prevent use-after-frees.
1111 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
1112 &ImportingInstance.getModuleCache());
1113 auto &Inv = *Invocation;
1114 Instance.setInvocation(std::move(Invocation));
1116 Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
1117 ImportingInstance.getDiagnosticClient()),
1118 /*ShouldOwnClient=*/true);
1120 // Note that this module is part of the module build stack, so that we
1121 // can detect cycles in the module graph.
1122 Instance.setFileManager(&ImportingInstance.getFileManager());
1123 Instance.createSourceManager(Instance.getFileManager());
1124 SourceManager &SourceMgr = Instance.getSourceManager();
1125 SourceMgr.setModuleBuildStack(
1126 ImportingInstance.getSourceManager().getModuleBuildStack());
1127 SourceMgr.pushModuleBuildStack(ModuleName,
1128 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
1130 // If we're collecting module dependencies, we need to share a collector
1131 // between all of the module CompilerInstances. Other than that, we don't
1132 // want to produce any dependency output from the module build.
1133 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
1134 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1136 ImportingInstance.getDiagnostics().Report(ImportLoc,
1137 diag::remark_module_build)
1138 << ModuleName << ModuleFileName;
1140 PreBuildStep(Instance);
1142 // Execute the action to actually build the module in-place. Use a separate
1143 // thread so that we get a stack large enough.
1144 llvm::CrashRecoveryContext CRC;
1145 CRC.RunSafelyOnThread(
1147 GenerateModuleFromModuleMapAction Action;
1148 Instance.ExecuteAction(Action);
1152 PostBuildStep(Instance);
1154 ImportingInstance.getDiagnostics().Report(ImportLoc,
1155 diag::remark_module_build_done)
1158 // Delete the temporary module map file.
1159 // FIXME: Even though we're executing under crash protection, it would still
1160 // be nice to do this with RemoveFileOnSignal when we can. However, that
1161 // doesn't make sense for all clients, so clean this up manually.
1162 Instance.clearOutputFiles(/*EraseFiles=*/true);
1164 return !Instance.getDiagnostics().hasErrorOccurred();
1167 static const FileEntry *getPublicModuleMap(const FileEntry *File,
1168 FileManager &FileMgr) {
1169 StringRef Filename = llvm::sys::path::filename(File->getName());
1170 SmallString<128> PublicFilename(File->getDir()->getName());
1171 if (Filename == "module_private.map")
1172 llvm::sys::path::append(PublicFilename, "module.map");
1173 else if (Filename == "module.private.modulemap")
1174 llvm::sys::path::append(PublicFilename, "module.modulemap");
1177 if (auto FE = FileMgr.getFile(PublicFilename))
1182 /// Compile a module file for the given module, using the options
1183 /// provided by the importing compiler instance. Returns true if the module
1184 /// was built without errors.
1185 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1186 SourceLocation ImportLoc,
1188 StringRef ModuleFileName) {
1189 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
1190 InputKind::ModuleMap);
1192 // Get or create the module map that we'll use to build this module.
1194 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1196 if (const FileEntry *ModuleMapFile =
1197 ModMap.getContainingModuleMapFile(Module)) {
1198 // Canonicalize compilation to start with the public module map. This is
1199 // vital for submodules declarations in the private module maps to be
1200 // correctly parsed when depending on a top level module in the public one.
1201 if (const FileEntry *PublicMMFile = getPublicModuleMap(
1202 ModuleMapFile, ImportingInstance.getFileManager()))
1203 ModuleMapFile = PublicMMFile;
1205 // Use the module map where this module resides.
1206 Result = compileModuleImpl(
1207 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1208 FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
1209 ModMap.getModuleMapFileForUniquing(Module)->getName(),
1212 // FIXME: We only need to fake up an input file here as a way of
1213 // transporting the module's directory to the module map parser. We should
1214 // be able to do that more directly, and parse from a memory buffer without
1215 // inventing this file.
1216 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1217 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1219 std::string InferredModuleMapContent;
1220 llvm::raw_string_ostream OS(InferredModuleMapContent);
1224 Result = compileModuleImpl(
1225 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
1226 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1227 ModMap.getModuleMapFileForUniquing(Module)->getName(),
1229 [&](CompilerInstance &Instance) {
1230 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1231 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1232 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1233 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1234 Instance.getSourceManager().overrideFileContents(
1235 ModuleMapFile, std::move(ModuleMapBuffer));
1239 // We've rebuilt a module. If we're allowed to generate or update the global
1240 // module index, record that fact in the importing compiler instance.
1241 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1242 ImportingInstance.setBuildGlobalModuleIndex(true);
1248 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
1249 SourceLocation ImportLoc,
1250 SourceLocation ModuleNameLoc, Module *Module,
1251 StringRef ModuleFileName) {
1252 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1254 auto diagnoseBuildFailure = [&] {
1255 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1256 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1259 // FIXME: have LockFileManager return an error_code so that we can
1260 // avoid the mkdir when the directory already exists.
1261 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1262 llvm::sys::fs::create_directories(Dir);
1265 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1266 llvm::LockFileManager Locked(ModuleFileName);
1268 case llvm::LockFileManager::LFS_Error:
1269 // ModuleCache takes care of correctness and locks are only necessary for
1270 // performance. Fallback to building the module in case of any lock
1272 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1273 << Module->Name << Locked.getErrorMessage();
1274 // Clear out any potential leftover.
1275 Locked.unsafeRemoveLockFile();
1277 case llvm::LockFileManager::LFS_Owned:
1278 // We're responsible for building the module ourselves.
1279 if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1281 diagnoseBuildFailure();
1286 case llvm::LockFileManager::LFS_Shared:
1287 // Someone else is responsible for building the module. Wait for them to
1289 switch (Locked.waitForUnlock()) {
1290 case llvm::LockFileManager::Res_Success:
1291 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1293 case llvm::LockFileManager::Res_OwnerDied:
1294 continue; // try again to get the lock.
1295 case llvm::LockFileManager::Res_Timeout:
1296 // Since ModuleCache takes care of correctness, we try waiting for
1297 // another process to complete the build so clang does not do it done
1298 // twice. If case of timeout, build it ourselves.
1299 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1301 // Clear the lock file so that future invocations can make progress.
1302 Locked.unsafeRemoveLockFile();
1308 // Try to read the module file, now that we've compiled it.
1309 ASTReader::ASTReadResult ReadResult =
1310 ImportingInstance.getModuleManager()->ReadAST(
1311 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1312 ModuleLoadCapabilities);
1314 if (ReadResult == ASTReader::OutOfDate &&
1315 Locked == llvm::LockFileManager::LFS_Shared) {
1316 // The module may be out of date in the presence of file system races,
1317 // or if one of its imports depends on header search paths that are not
1318 // consistent with this ImportingInstance. Try again...
1320 } else if (ReadResult == ASTReader::Missing) {
1321 diagnoseBuildFailure();
1322 } else if (ReadResult != ASTReader::Success &&
1323 !Diags.hasErrorOccurred()) {
1324 // The ASTReader didn't diagnose the error, so conservatively report it.
1325 diagnoseBuildFailure();
1327 return ReadResult == ASTReader::Success;
1331 /// Diagnose differences between the current definition of the given
1332 /// configuration macro and the definition provided on the command line.
1333 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1334 Module *Mod, SourceLocation ImportLoc) {
1335 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1336 SourceManager &SourceMgr = PP.getSourceManager();
1338 // If this identifier has never had a macro definition, then it could
1339 // not have changed.
1340 if (!Id->hadMacroDefinition())
1342 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1344 // Find the macro definition from the command line.
1345 MacroInfo *CmdLineDefinition = nullptr;
1346 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1347 // We only care about the predefines buffer.
1348 FileID FID = SourceMgr.getFileID(MD->getLocation());
1349 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1351 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1352 CmdLineDefinition = DMD->getMacroInfo();
1356 auto *CurrentDefinition = PP.getMacroInfo(Id);
1357 if (CurrentDefinition == CmdLineDefinition) {
1358 // Macro matches. Nothing to do.
1359 } else if (!CurrentDefinition) {
1360 // This macro was defined on the command line, then #undef'd later.
1362 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1363 << true << ConfigMacro << Mod->getFullModuleName();
1364 auto LatestDef = LatestLocalMD->getDefinition();
1365 assert(LatestDef.isUndefined() &&
1366 "predefined macro went away with no #undef?");
1367 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1370 } else if (!CmdLineDefinition) {
1371 // There was no definition for this macro in the predefines buffer,
1372 // but there was a local definition. Complain.
1373 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1374 << false << ConfigMacro << Mod->getFullModuleName();
1375 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1376 diag::note_module_def_undef_here)
1378 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1379 /*Syntactically=*/true)) {
1380 // The macro definitions differ.
1381 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1382 << false << ConfigMacro << Mod->getFullModuleName();
1383 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1384 diag::note_module_def_undef_here)
1389 /// Write a new timestamp file with the given path.
1390 static void writeTimestampFile(StringRef TimestampFile) {
1392 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
1395 /// Prune the module cache of modules that haven't been accessed in
1397 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1398 llvm::sys::fs::file_status StatBuf;
1399 llvm::SmallString<128> TimestampFile;
1400 TimestampFile = HSOpts.ModuleCachePath;
1401 assert(!TimestampFile.empty());
1402 llvm::sys::path::append(TimestampFile, "modules.timestamp");
1404 // Try to stat() the timestamp file.
1405 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
1406 // If the timestamp file wasn't there, create one now.
1407 if (EC == std::errc::no_such_file_or_directory) {
1408 writeTimestampFile(TimestampFile);
1413 // Check whether the time stamp is older than our pruning interval.
1414 // If not, do nothing.
1415 time_t TimeStampModTime =
1416 llvm::sys::toTimeT(StatBuf.getLastModificationTime());
1417 time_t CurrentTime = time(nullptr);
1418 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1421 // Write a new timestamp file so that nobody else attempts to prune.
1422 // There is a benign race condition here, if two Clang instances happen to
1423 // notice at the same time that the timestamp is out-of-date.
1424 writeTimestampFile(TimestampFile);
1426 // Walk the entire module cache, looking for unused module files and module
1429 SmallString<128> ModuleCachePathNative;
1430 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1431 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1432 Dir != DirEnd && !EC; Dir.increment(EC)) {
1433 // If we don't have a directory, there's nothing to look into.
1434 if (!llvm::sys::fs::is_directory(Dir->path()))
1437 // Walk all of the files within this directory.
1438 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1439 File != FileEnd && !EC; File.increment(EC)) {
1440 // We only care about module and global module index files.
1441 StringRef Extension = llvm::sys::path::extension(File->path());
1442 if (Extension != ".pcm" && Extension != ".timestamp" &&
1443 llvm::sys::path::filename(File->path()) != "modules.idx")
1446 // Look at this file. If we can't stat it, there's nothing interesting
1448 if (llvm::sys::fs::status(File->path(), StatBuf))
1451 // If the file has been used recently enough, leave it there.
1452 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
1453 if (CurrentTime - FileAccessTime <=
1454 time_t(HSOpts.ModuleCachePruneAfter)) {
1459 llvm::sys::fs::remove(File->path());
1461 // Remove the timestamp file.
1462 std::string TimpestampFilename = File->path() + ".timestamp";
1463 llvm::sys::fs::remove(TimpestampFilename);
1466 // If we removed all of the files in the directory, remove the directory
1468 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1469 llvm::sys::fs::directory_iterator() && !EC)
1470 llvm::sys::fs::remove(Dir->path());
1474 void CompilerInstance::createModuleManager() {
1475 if (!ModuleManager) {
1476 if (!hasASTContext())
1479 // If we're implicitly building modules but not currently recursively
1480 // building a module, check whether we need to prune the module cache.
1481 if (getSourceManager().getModuleBuildStack().empty() &&
1482 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1483 getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1484 getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1485 pruneModuleCache(getHeaderSearchOpts());
1488 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1489 std::string Sysroot = HSOpts.Sysroot;
1490 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1491 std::unique_ptr<llvm::Timer> ReadTimer;
1492 if (FrontendTimerGroup)
1493 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1495 *FrontendTimerGroup);
1496 ModuleManager = new ASTReader(
1497 getPreprocessor(), getModuleCache(), &getASTContext(),
1498 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1499 Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
1500 /*AllowASTWithCompilerErrors=*/false,
1501 /*AllowConfigurationMismatch=*/false,
1502 HSOpts.ModulesValidateSystemHeaders,
1503 HSOpts.ValidateASTInputFilesContent,
1504 getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1505 if (hasASTConsumer()) {
1506 ModuleManager->setDeserializationListener(
1507 getASTConsumer().GetASTDeserializationListener());
1508 getASTContext().setASTMutationListener(
1509 getASTConsumer().GetASTMutationListener());
1511 getASTContext().setExternalSource(ModuleManager);
1513 ModuleManager->InitializeSema(getSema());
1514 if (hasASTConsumer())
1515 ModuleManager->StartTranslationUnit(&getASTConsumer());
1517 for (auto &Listener : DependencyCollectors)
1518 Listener->attachToASTReader(*ModuleManager);
1522 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1524 if (FrontendTimerGroup)
1525 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1526 *FrontendTimerGroup);
1527 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1529 // Helper to recursively read the module names for all modules we're adding.
1530 // We mark these as known and redirect any attempt to load that module to
1531 // the files we were handed.
1532 struct ReadModuleNames : ASTReaderListener {
1533 CompilerInstance &CI;
1534 llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1536 ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1538 void ReadModuleName(StringRef ModuleName) override {
1539 LoadedModules.push_back(
1540 CI.getPreprocessor().getIdentifierInfo(ModuleName));
1543 void registerAll() {
1544 for (auto *II : LoadedModules) {
1545 CI.KnownModules[II] = CI.getPreprocessor()
1546 .getHeaderSearchInfo()
1548 .findModule(II->getName());
1550 LoadedModules.clear();
1553 void markAllUnavailable() {
1554 for (auto *II : LoadedModules) {
1555 if (Module *M = CI.getPreprocessor()
1556 .getHeaderSearchInfo()
1558 .findModule(II->getName())) {
1559 M->HasIncompatibleModuleFile = true;
1561 // Mark module as available if the only reason it was unavailable
1562 // was missing headers.
1563 SmallVector<Module *, 2> Stack;
1565 while (!Stack.empty()) {
1566 Module *Current = Stack.pop_back_val();
1567 if (Current->IsMissingRequirement) continue;
1568 Current->IsAvailable = true;
1569 Stack.insert(Stack.end(),
1570 Current->submodule_begin(), Current->submodule_end());
1574 LoadedModules.clear();
1578 // If we don't already have an ASTReader, create one now.
1580 createModuleManager();
1582 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1583 // ASTReader to diagnose it, since it can produce better errors that we can.
1584 bool ConfigMismatchIsRecoverable =
1585 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
1587 <= DiagnosticsEngine::Warning;
1589 auto Listener = std::make_unique<ReadModuleNames>(*this);
1590 auto &ListenerRef = *Listener;
1591 ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
1592 std::move(Listener));
1594 // Try to load the module file.
1595 switch (ModuleManager->ReadAST(
1596 FileName, serialization::MK_ExplicitModule, SourceLocation(),
1597 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
1598 case ASTReader::Success:
1599 // We successfully loaded the module file; remember the set of provided
1600 // modules so that we don't try to load implicit modules for them.
1601 ListenerRef.registerAll();
1604 case ASTReader::ConfigurationMismatch:
1605 // Ignore unusable module files.
1606 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1608 // All modules provided by any files we tried and failed to load are now
1609 // unavailable; includes of those modules should now be handled textually.
1610 ListenerRef.markAllUnavailable();
1619 CompilerInstance::loadModule(SourceLocation ImportLoc,
1621 Module::NameVisibilityKind Visibility,
1622 bool IsInclusionDirective) {
1623 // Determine what file we're searching from.
1624 StringRef ModuleName = Path[0].first->getName();
1625 SourceLocation ModuleNameLoc = Path[0].second;
1627 // If we've already handled this import, just return the cached result.
1628 // This one-element cache is important to eliminate redundant diagnostics
1629 // when both the preprocessor and parser see the same import declaration.
1630 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1631 // Make the named module visible.
1632 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1633 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1635 return LastModuleImportResult;
1638 clang::Module *Module = nullptr;
1640 // If we don't already have information on this module, load the module now.
1641 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1642 = KnownModules.find(Path[0].first);
1643 if (Known != KnownModules.end()) {
1644 // Retrieve the cached top-level module.
1645 Module = Known->second;
1646 } else if (ModuleName == getLangOpts().CurrentModule) {
1647 // This is the module we're building.
1648 Module = PP->getHeaderSearchInfo().lookupModule(
1649 ModuleName, /*AllowSearch*/ true,
1650 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1651 /// FIXME: perhaps we should (a) look for a module using the module name
1652 // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
1653 //if (Module == nullptr) {
1654 // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1656 // ModuleBuildFailed = true;
1657 // return ModuleLoadResult();
1659 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1661 // Search for a module with the given name.
1662 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
1663 !IsInclusionDirective);
1664 HeaderSearchOptions &HSOpts =
1665 PP->getHeaderSearchInfo().getHeaderSearchOpts();
1667 std::string ModuleFileName;
1669 ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
1670 } Source = ModuleNotFound;
1672 // Check to see if the module has been built as part of this compilation
1673 // via a module build pragma.
1674 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1675 if (BuiltModuleIt != BuiltModules.end()) {
1676 ModuleFileName = BuiltModuleIt->second;
1677 Source = ModuleBuildPragma;
1680 // Try to load the module from the prebuilt module path.
1681 if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() ||
1682 !HSOpts.PrebuiltModulePaths.empty())) {
1684 PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
1685 if (!ModuleFileName.empty())
1686 Source = PrebuiltModulePath;
1689 // Try to load the module from the module cache.
1690 if (Source == ModuleNotFound && Module) {
1691 ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
1692 Source = ModuleCache;
1695 if (Source == ModuleNotFound) {
1696 // We can't find a module, error out here.
1697 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1698 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1699 ModuleBuildFailed = true;
1700 return ModuleLoadResult();
1703 if (ModuleFileName.empty()) {
1704 if (Module && Module->HasIncompatibleModuleFile) {
1705 // We tried and failed to load a module file for this module. Fall
1706 // back to textual inclusion for its headers.
1707 return ModuleLoadResult::ConfigMismatch;
1710 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1712 ModuleBuildFailed = true;
1713 return ModuleLoadResult();
1716 // If we don't already have an ASTReader, create one now.
1718 createModuleManager();
1721 if (FrontendTimerGroup)
1722 Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
1723 *FrontendTimerGroup);
1724 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1725 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1727 // Try to load the module file. If we are not trying to load from the
1728 // module cache, we don't know how to rebuild modules.
1729 unsigned ARRFlags = Source == ModuleCache ?
1730 ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing :
1731 Source == PrebuiltModulePath ?
1733 ASTReader::ARR_ConfigurationMismatch;
1734 switch (ModuleManager->ReadAST(ModuleFileName,
1735 Source == PrebuiltModulePath
1736 ? serialization::MK_PrebuiltModule
1737 : Source == ModuleBuildPragma
1738 ? serialization::MK_ExplicitModule
1739 : serialization::MK_ImplicitModule,
1740 ImportLoc, ARRFlags)) {
1741 case ASTReader::Success: {
1742 if (Source != ModuleCache && !Module) {
1743 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
1744 !IsInclusionDirective);
1745 auto ModuleFile = FileMgr->getFile(ModuleFileName);
1746 if (!Module || !Module->getASTFile() ||
1747 !ModuleFile || (*ModuleFile != Module->getASTFile())) {
1748 // Error out if Module does not refer to the file in the prebuilt
1750 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1752 ModuleBuildFailed = true;
1753 KnownModules[Path[0].first] = nullptr;
1754 return ModuleLoadResult();
1760 case ASTReader::OutOfDate:
1761 case ASTReader::Missing: {
1762 if (Source != ModuleCache) {
1763 // We don't know the desired configuration for this module and don't
1764 // necessarily even have a module map. Since ReadAST already produces
1765 // diagnostics for these two cases, we simply error out here.
1766 ModuleBuildFailed = true;
1767 KnownModules[Path[0].first] = nullptr;
1768 return ModuleLoadResult();
1771 // The module file is missing or out-of-date. Build it.
1772 assert(Module && "missing module file");
1773 // Check whether there is a cycle in the module graph.
1774 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1775 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1776 for (; Pos != PosEnd; ++Pos) {
1777 if (Pos->first == ModuleName)
1781 if (Pos != PosEnd) {
1782 SmallString<256> CyclePath;
1783 for (; Pos != PosEnd; ++Pos) {
1784 CyclePath += Pos->first;
1785 CyclePath += " -> ";
1787 CyclePath += ModuleName;
1789 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1790 << ModuleName << CyclePath;
1791 return ModuleLoadResult();
1794 // Check whether we have already attempted to build this module (but
1796 if (getPreprocessorOpts().FailedModules &&
1797 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1798 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1800 << SourceRange(ImportLoc, ModuleNameLoc);
1801 ModuleBuildFailed = true;
1802 return ModuleLoadResult();
1805 // Try to compile and then load the module.
1806 if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1808 assert(getDiagnostics().hasErrorOccurred() &&
1809 "undiagnosed error in compileAndLoadModule");
1810 if (getPreprocessorOpts().FailedModules)
1811 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1812 KnownModules[Path[0].first] = nullptr;
1813 ModuleBuildFailed = true;
1814 return ModuleLoadResult();
1817 // Okay, we've rebuilt and now loaded the module.
1821 case ASTReader::ConfigurationMismatch:
1822 if (Source == PrebuiltModulePath)
1823 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1824 // produce a warning here!
1825 getDiagnostics().Report(SourceLocation(),
1826 diag::warn_module_config_mismatch)
1828 // Fall through to error out.
1830 case ASTReader::VersionMismatch:
1831 case ASTReader::HadErrors:
1832 ModuleLoader::HadFatalFailure = true;
1833 // FIXME: The ASTReader will already have complained, but can we shoehorn
1834 // that diagnostic information into a more useful form?
1835 KnownModules[Path[0].first] = nullptr;
1836 return ModuleLoadResult();
1838 case ASTReader::Failure:
1839 ModuleLoader::HadFatalFailure = true;
1840 // Already complained, but note now that we failed.
1841 KnownModules[Path[0].first] = nullptr;
1842 ModuleBuildFailed = true;
1843 return ModuleLoadResult();
1846 // Cache the result of this top-level module lookup for later.
1847 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1850 // If we never found the module, fail.
1852 return ModuleLoadResult();
1854 // Verify that the rest of the module path actually corresponds to
1856 bool MapPrivateSubModToTopLevel = false;
1857 if (Path.size() > 1) {
1858 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1859 StringRef Name = Path[I].first->getName();
1860 clang::Module *Sub = Module->findSubmodule(Name);
1862 // If the user is requesting Foo.Private and it doesn't exist, try to
1863 // match Foo_Private and emit a warning asking for the user to write
1864 // @import Foo_Private instead. FIXME: remove this when existing clients
1865 // migrate off of Foo.Private syntax.
1866 if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
1867 Module == Module->getTopLevelModule()) {
1868 SmallString<128> PrivateModule(Module->Name);
1869 PrivateModule.append("_Private");
1871 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
1872 auto &II = PP->getIdentifierTable().get(
1873 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
1874 PrivPath.push_back(std::make_pair(&II, Path[0].second));
1876 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
1877 !IsInclusionDirective))
1879 loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1881 MapPrivateSubModToTopLevel = true;
1882 if (!getDiagnostics().isIgnored(
1883 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1884 getDiagnostics().Report(Path[I].second,
1885 diag::warn_no_priv_submodule_use_toplevel)
1886 << Path[I].first << Module->getFullModuleName() << PrivateModule
1887 << SourceRange(Path[0].second, Path[I].second)
1888 << FixItHint::CreateReplacement(SourceRange(Path[0].second),
1890 getDiagnostics().Report(Sub->DefinitionLoc,
1891 diag::note_private_top_level_defined);
1897 // Attempt to perform typo correction to find a module name that works.
1898 SmallVector<StringRef, 2> Best;
1899 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1901 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1902 JEnd = Module->submodule_end();
1904 unsigned ED = Name.edit_distance((*J)->Name,
1905 /*AllowReplacements=*/true,
1907 if (ED <= BestEditDistance) {
1908 if (ED < BestEditDistance) {
1910 BestEditDistance = ED;
1913 Best.push_back((*J)->Name);
1917 // If there was a clear winner, user it.
1918 if (Best.size() == 1) {
1919 getDiagnostics().Report(Path[I].second,
1920 diag::err_no_submodule_suggest)
1921 << Path[I].first << Module->getFullModuleName() << Best[0]
1922 << SourceRange(Path[0].second, Path[I-1].second)
1923 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1926 Sub = Module->findSubmodule(Best[0]);
1931 // No submodule by this name. Complain, and don't look for further
1933 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1934 << Path[I].first << Module->getFullModuleName()
1935 << SourceRange(Path[0].second, Path[I-1].second);
1943 // Make the named module visible, if it's not already part of the module
1945 if (ModuleName != getLangOpts().CurrentModule) {
1946 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
1947 // We have an umbrella header or directory that doesn't actually include
1948 // all of the headers within the directory it covers. Complain about
1949 // this missing submodule and recover by forgetting that we ever saw
1951 // FIXME: Should we detect this at module load time? It seems fairly
1952 // expensive (and rare).
1953 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1954 << Module->getFullModuleName()
1955 << SourceRange(Path.front().second, Path.back().second);
1957 return ModuleLoadResult::MissingExpected;
1960 // Check whether this module is available.
1961 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
1962 getDiagnostics(), Module)) {
1963 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
1964 << SourceRange(Path.front().second, Path.back().second);
1965 LastModuleImportLoc = ImportLoc;
1966 LastModuleImportResult = ModuleLoadResult();
1967 return ModuleLoadResult();
1970 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1973 // Check for any configuration macros that have changed.
1974 clang::Module *TopModule = Module->getTopLevelModule();
1975 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1976 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1980 // Resolve any remaining module using export_as for this one.
1982 .getHeaderSearchInfo()
1984 .resolveLinkAsDependencies(TopModule);
1986 LastModuleImportLoc = ImportLoc;
1987 LastModuleImportResult = ModuleLoadResult(Module);
1988 return LastModuleImportResult;
1991 void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc,
1992 StringRef ModuleName,
1994 // Avoid creating filenames with special characters.
1995 SmallString<128> CleanModuleName(ModuleName);
1996 for (auto &C : CleanModuleName)
1997 if (!isAlphanumeric(C))
2000 // FIXME: Using a randomized filename here means that our intermediate .pcm
2001 // output is nondeterministic (as .pcm files refer to each other by name).
2002 // Can this affect the output in any way?
2003 SmallString<128> ModuleFileName;
2004 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2005 CleanModuleName, "pcm", ModuleFileName)) {
2006 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2007 << ModuleFileName << EC.message();
2010 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2012 FrontendInputFile Input(
2014 InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
2015 InputKind::ModuleMap, /*Preprocessed*/true));
2017 std::string NullTerminatedSource(Source.str());
2019 auto PreBuildStep = [&](CompilerInstance &Other) {
2020 // Create a virtual file containing our desired source.
2021 // FIXME: We shouldn't need to do this.
2022 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
2023 ModuleMapFileName, NullTerminatedSource.size(), 0);
2024 Other.getSourceManager().overrideFileContents(
2026 llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2028 Other.BuiltModules = std::move(BuiltModules);
2029 Other.DeleteBuiltModules = false;
2032 auto PostBuildStep = [this](CompilerInstance &Other) {
2033 BuiltModules = std::move(Other.BuiltModules);
2036 // Build the module, inheriting any modules that we've built locally.
2037 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
2038 ModuleFileName, PreBuildStep, PostBuildStep)) {
2039 BuiltModules[ModuleName] = ModuleFileName.str();
2040 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2044 void CompilerInstance::makeModuleVisible(Module *Mod,
2045 Module::NameVisibilityKind Visibility,
2046 SourceLocation ImportLoc) {
2048 createModuleManager();
2052 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
2055 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2056 SourceLocation TriggerLoc) {
2057 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2060 createModuleManager();
2061 // Can't do anything if we don't have the module manager.
2064 // Get an existing global index. This loads it if not already
2066 ModuleManager->loadGlobalIndex();
2067 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
2068 // If the global index doesn't exist, create it.
2069 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2070 hasPreprocessor()) {
2071 llvm::sys::fs::create_directories(
2072 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
2073 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2074 getFileManager(), getPCHContainerReader(),
2075 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2076 // FIXME this drops the error on the floor. This code is only used for
2077 // typo correction and drops more than just this one source of errors
2078 // (such as the directory creation failure above). It should handle the
2080 consumeError(std::move(Err));
2083 ModuleManager->resetForReload();
2084 ModuleManager->loadGlobalIndex();
2085 GlobalIndex = ModuleManager->getGlobalIndex();
2087 // For finding modules needing to be imported for fixit messages,
2088 // we need to make the global index cover all modules, so we do that here.
2089 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2090 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2091 bool RecreateIndex = false;
2092 for (ModuleMap::module_iterator I = MMap.module_begin(),
2093 E = MMap.module_end(); I != E; ++I) {
2094 Module *TheModule = I->second;
2095 const FileEntry *Entry = TheModule->getASTFile();
2097 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2098 Path.push_back(std::make_pair(
2099 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
2100 std::reverse(Path.begin(), Path.end());
2101 // Load a module as hidden. This also adds it to the global index.
2102 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2103 RecreateIndex = true;
2106 if (RecreateIndex) {
2107 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2108 getFileManager(), getPCHContainerReader(),
2109 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
2110 // FIXME As above, this drops the error on the floor.
2111 consumeError(std::move(Err));
2114 ModuleManager->resetForReload();
2115 ModuleManager->loadGlobalIndex();
2116 GlobalIndex = ModuleManager->getGlobalIndex();
2118 HaveFullGlobalModuleIndex = true;
2123 // Check global module index for missing imports.
2125 CompilerInstance::lookupMissingImports(StringRef Name,
2126 SourceLocation TriggerLoc) {
2127 // Look for the symbol in non-imported modules, but only if an error
2128 // actually occurred.
2129 if (!buildingModule()) {
2130 // Load global module index, or retrieve a previously loaded one.
2131 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2134 // Only if we have a global index.
2136 GlobalModuleIndex::HitSet FoundModules;
2138 // Find the modules that reference the identifier.
2139 // Note that this only finds top-level modules.
2140 // We'll let diagnoseTypo find the actual declaration module.
2141 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2148 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2150 void CompilerInstance::setExternalSemaSource(
2151 IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2152 ExternalSemaSrc = std::move(ESS);