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