xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Frontend/CompilerInstance.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CompilerInstance.cpp ---------------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "clang/Frontend/CompilerInstance.h"
107330f729Sjoerg #include "clang/AST/ASTConsumer.h"
117330f729Sjoerg #include "clang/AST/ASTContext.h"
127330f729Sjoerg #include "clang/AST/Decl.h"
137330f729Sjoerg #include "clang/Basic/CharInfo.h"
147330f729Sjoerg #include "clang/Basic/Diagnostic.h"
157330f729Sjoerg #include "clang/Basic/FileManager.h"
167330f729Sjoerg #include "clang/Basic/LangStandard.h"
177330f729Sjoerg #include "clang/Basic/SourceManager.h"
187330f729Sjoerg #include "clang/Basic/Stack.h"
197330f729Sjoerg #include "clang/Basic/TargetInfo.h"
207330f729Sjoerg #include "clang/Basic/Version.h"
217330f729Sjoerg #include "clang/Config/config.h"
227330f729Sjoerg #include "clang/Frontend/ChainedDiagnosticConsumer.h"
237330f729Sjoerg #include "clang/Frontend/FrontendAction.h"
247330f729Sjoerg #include "clang/Frontend/FrontendActions.h"
257330f729Sjoerg #include "clang/Frontend/FrontendDiagnostic.h"
267330f729Sjoerg #include "clang/Frontend/LogDiagnosticPrinter.h"
277330f729Sjoerg #include "clang/Frontend/SerializedDiagnosticPrinter.h"
287330f729Sjoerg #include "clang/Frontend/TextDiagnosticPrinter.h"
297330f729Sjoerg #include "clang/Frontend/Utils.h"
307330f729Sjoerg #include "clang/Frontend/VerifyDiagnosticConsumer.h"
317330f729Sjoerg #include "clang/Lex/HeaderSearch.h"
327330f729Sjoerg #include "clang/Lex/Preprocessor.h"
337330f729Sjoerg #include "clang/Lex/PreprocessorOptions.h"
347330f729Sjoerg #include "clang/Sema/CodeCompleteConsumer.h"
357330f729Sjoerg #include "clang/Sema/Sema.h"
367330f729Sjoerg #include "clang/Serialization/ASTReader.h"
377330f729Sjoerg #include "clang/Serialization/GlobalModuleIndex.h"
387330f729Sjoerg #include "clang/Serialization/InMemoryModuleCache.h"
397330f729Sjoerg #include "llvm/ADT/Statistic.h"
407330f729Sjoerg #include "llvm/Support/BuryPointer.h"
417330f729Sjoerg #include "llvm/Support/CrashRecoveryContext.h"
427330f729Sjoerg #include "llvm/Support/Errc.h"
437330f729Sjoerg #include "llvm/Support/FileSystem.h"
447330f729Sjoerg #include "llvm/Support/Host.h"
457330f729Sjoerg #include "llvm/Support/LockFileManager.h"
467330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
477330f729Sjoerg #include "llvm/Support/Path.h"
487330f729Sjoerg #include "llvm/Support/Program.h"
497330f729Sjoerg #include "llvm/Support/Signals.h"
507330f729Sjoerg #include "llvm/Support/TimeProfiler.h"
517330f729Sjoerg #include "llvm/Support/Timer.h"
527330f729Sjoerg #include "llvm/Support/raw_ostream.h"
537330f729Sjoerg #include <time.h>
547330f729Sjoerg #include <utility>
557330f729Sjoerg 
567330f729Sjoerg using namespace clang;
577330f729Sjoerg 
CompilerInstance(std::shared_ptr<PCHContainerOperations> PCHContainerOps,InMemoryModuleCache * SharedModuleCache)587330f729Sjoerg CompilerInstance::CompilerInstance(
597330f729Sjoerg     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
607330f729Sjoerg     InMemoryModuleCache *SharedModuleCache)
617330f729Sjoerg     : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
627330f729Sjoerg       Invocation(new CompilerInvocation()),
637330f729Sjoerg       ModuleCache(SharedModuleCache ? SharedModuleCache
647330f729Sjoerg                                     : new InMemoryModuleCache),
657330f729Sjoerg       ThePCHContainerOperations(std::move(PCHContainerOps)) {}
667330f729Sjoerg 
~CompilerInstance()677330f729Sjoerg CompilerInstance::~CompilerInstance() {
687330f729Sjoerg   assert(OutputFiles.empty() && "Still output files in flight?");
697330f729Sjoerg }
707330f729Sjoerg 
setInvocation(std::shared_ptr<CompilerInvocation> Value)717330f729Sjoerg void CompilerInstance::setInvocation(
727330f729Sjoerg     std::shared_ptr<CompilerInvocation> Value) {
737330f729Sjoerg   Invocation = std::move(Value);
747330f729Sjoerg }
757330f729Sjoerg 
shouldBuildGlobalModuleIndex() const767330f729Sjoerg bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
777330f729Sjoerg   return (BuildGlobalModuleIndex ||
78*e038c9c4Sjoerg           (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
797330f729Sjoerg            getFrontendOpts().GenerateGlobalModuleIndex)) &&
80*e038c9c4Sjoerg          !DisableGeneratingGlobalModuleIndex;
817330f729Sjoerg }
827330f729Sjoerg 
setDiagnostics(DiagnosticsEngine * Value)837330f729Sjoerg void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
847330f729Sjoerg   Diagnostics = Value;
857330f729Sjoerg }
867330f729Sjoerg 
setVerboseOutputStream(raw_ostream & Value)877330f729Sjoerg void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
88*e038c9c4Sjoerg   OwnedVerboseOutputStream.reset();
897330f729Sjoerg   VerboseOutputStream = &Value;
907330f729Sjoerg }
917330f729Sjoerg 
setVerboseOutputStream(std::unique_ptr<raw_ostream> Value)927330f729Sjoerg void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
937330f729Sjoerg   OwnedVerboseOutputStream.swap(Value);
947330f729Sjoerg   VerboseOutputStream = OwnedVerboseOutputStream.get();
957330f729Sjoerg }
967330f729Sjoerg 
setTarget(TargetInfo * Value)977330f729Sjoerg void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
setAuxTarget(TargetInfo * Value)987330f729Sjoerg void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
997330f729Sjoerg 
createTarget()100*e038c9c4Sjoerg bool CompilerInstance::createTarget() {
101*e038c9c4Sjoerg   // Create the target instance.
102*e038c9c4Sjoerg   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
103*e038c9c4Sjoerg                                          getInvocation().TargetOpts));
104*e038c9c4Sjoerg   if (!hasTarget())
105*e038c9c4Sjoerg     return false;
106*e038c9c4Sjoerg 
107*e038c9c4Sjoerg   // Check whether AuxTarget exists, if not, then create TargetInfo for the
108*e038c9c4Sjoerg   // other side of CUDA/OpenMP/SYCL compilation.
109*e038c9c4Sjoerg   if (!getAuxTarget() &&
110*e038c9c4Sjoerg       (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
111*e038c9c4Sjoerg        getLangOpts().SYCLIsDevice) &&
112*e038c9c4Sjoerg       !getFrontendOpts().AuxTriple.empty()) {
113*e038c9c4Sjoerg     auto TO = std::make_shared<TargetOptions>();
114*e038c9c4Sjoerg     TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
115*e038c9c4Sjoerg     if (getFrontendOpts().AuxTargetCPU)
116*e038c9c4Sjoerg       TO->CPU = getFrontendOpts().AuxTargetCPU.getValue();
117*e038c9c4Sjoerg     if (getFrontendOpts().AuxTargetFeatures)
118*e038c9c4Sjoerg       TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue();
119*e038c9c4Sjoerg     TO->HostTriple = getTarget().getTriple().str();
120*e038c9c4Sjoerg     setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
121*e038c9c4Sjoerg   }
122*e038c9c4Sjoerg 
123*e038c9c4Sjoerg   if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
124*e038c9c4Sjoerg     if (getLangOpts().getFPRoundingMode() !=
125*e038c9c4Sjoerg         llvm::RoundingMode::NearestTiesToEven) {
126*e038c9c4Sjoerg       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
127*e038c9c4Sjoerg       getLangOpts().setFPRoundingMode(llvm::RoundingMode::NearestTiesToEven);
128*e038c9c4Sjoerg     }
129*e038c9c4Sjoerg     if (getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore) {
130*e038c9c4Sjoerg       getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
131*e038c9c4Sjoerg       getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
132*e038c9c4Sjoerg     }
133*e038c9c4Sjoerg     // FIXME: can we disable FEnvAccess?
134*e038c9c4Sjoerg   }
135*e038c9c4Sjoerg 
136*e038c9c4Sjoerg   // We should do it here because target knows nothing about
137*e038c9c4Sjoerg   // language options when it's being created.
138*e038c9c4Sjoerg   if (getLangOpts().OpenCL &&
139*e038c9c4Sjoerg       !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
140*e038c9c4Sjoerg     return false;
141*e038c9c4Sjoerg 
142*e038c9c4Sjoerg   // Inform the target of the language options.
143*e038c9c4Sjoerg   // FIXME: We shouldn't need to do this, the target should be immutable once
144*e038c9c4Sjoerg   // created. This complexity should be lifted elsewhere.
145*e038c9c4Sjoerg   getTarget().adjust(getLangOpts());
146*e038c9c4Sjoerg 
147*e038c9c4Sjoerg   // Adjust target options based on codegen options.
148*e038c9c4Sjoerg   getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
149*e038c9c4Sjoerg 
150*e038c9c4Sjoerg   if (auto *Aux = getAuxTarget())
151*e038c9c4Sjoerg     getTarget().setAuxTarget(Aux);
152*e038c9c4Sjoerg 
153*e038c9c4Sjoerg   return true;
154*e038c9c4Sjoerg }
155*e038c9c4Sjoerg 
getVirtualFileSystem() const156*e038c9c4Sjoerg llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
157*e038c9c4Sjoerg   return getFileManager().getVirtualFileSystem();
158*e038c9c4Sjoerg }
159*e038c9c4Sjoerg 
setFileManager(FileManager * Value)1607330f729Sjoerg void CompilerInstance::setFileManager(FileManager *Value) {
1617330f729Sjoerg   FileMgr = Value;
1627330f729Sjoerg }
1637330f729Sjoerg 
setSourceManager(SourceManager * Value)1647330f729Sjoerg void CompilerInstance::setSourceManager(SourceManager *Value) {
1657330f729Sjoerg   SourceMgr = Value;
1667330f729Sjoerg }
1677330f729Sjoerg 
setPreprocessor(std::shared_ptr<Preprocessor> Value)1687330f729Sjoerg void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
1697330f729Sjoerg   PP = std::move(Value);
1707330f729Sjoerg }
1717330f729Sjoerg 
setASTContext(ASTContext * Value)1727330f729Sjoerg void CompilerInstance::setASTContext(ASTContext *Value) {
1737330f729Sjoerg   Context = Value;
1747330f729Sjoerg 
1757330f729Sjoerg   if (Context && Consumer)
1767330f729Sjoerg     getASTConsumer().Initialize(getASTContext());
1777330f729Sjoerg }
1787330f729Sjoerg 
setSema(Sema * S)1797330f729Sjoerg void CompilerInstance::setSema(Sema *S) {
1807330f729Sjoerg   TheSema.reset(S);
1817330f729Sjoerg }
1827330f729Sjoerg 
setASTConsumer(std::unique_ptr<ASTConsumer> Value)1837330f729Sjoerg void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
1847330f729Sjoerg   Consumer = std::move(Value);
1857330f729Sjoerg 
1867330f729Sjoerg   if (Context && Consumer)
1877330f729Sjoerg     getASTConsumer().Initialize(getASTContext());
1887330f729Sjoerg }
1897330f729Sjoerg 
setCodeCompletionConsumer(CodeCompleteConsumer * Value)1907330f729Sjoerg void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
1917330f729Sjoerg   CompletionConsumer.reset(Value);
1927330f729Sjoerg }
1937330f729Sjoerg 
takeSema()1947330f729Sjoerg std::unique_ptr<Sema> CompilerInstance::takeSema() {
1957330f729Sjoerg   return std::move(TheSema);
1967330f729Sjoerg }
1977330f729Sjoerg 
getASTReader() const198*e038c9c4Sjoerg IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
199*e038c9c4Sjoerg   return TheASTReader;
2007330f729Sjoerg }
setASTReader(IntrusiveRefCntPtr<ASTReader> Reader)201*e038c9c4Sjoerg void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
2027330f729Sjoerg   assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
2037330f729Sjoerg          "Expected ASTReader to use the same PCM cache");
204*e038c9c4Sjoerg   TheASTReader = std::move(Reader);
2057330f729Sjoerg }
2067330f729Sjoerg 
2077330f729Sjoerg std::shared_ptr<ModuleDependencyCollector>
getModuleDepCollector() const2087330f729Sjoerg CompilerInstance::getModuleDepCollector() const {
2097330f729Sjoerg   return ModuleDepCollector;
2107330f729Sjoerg }
2117330f729Sjoerg 
setModuleDepCollector(std::shared_ptr<ModuleDependencyCollector> Collector)2127330f729Sjoerg void CompilerInstance::setModuleDepCollector(
2137330f729Sjoerg     std::shared_ptr<ModuleDependencyCollector> Collector) {
2147330f729Sjoerg   ModuleDepCollector = std::move(Collector);
2157330f729Sjoerg }
2167330f729Sjoerg 
collectHeaderMaps(const HeaderSearch & HS,std::shared_ptr<ModuleDependencyCollector> MDC)2177330f729Sjoerg static void collectHeaderMaps(const HeaderSearch &HS,
2187330f729Sjoerg                               std::shared_ptr<ModuleDependencyCollector> MDC) {
2197330f729Sjoerg   SmallVector<std::string, 4> HeaderMapFileNames;
2207330f729Sjoerg   HS.getHeaderMapFileNames(HeaderMapFileNames);
2217330f729Sjoerg   for (auto &Name : HeaderMapFileNames)
2227330f729Sjoerg     MDC->addFile(Name);
2237330f729Sjoerg }
2247330f729Sjoerg 
collectIncludePCH(CompilerInstance & CI,std::shared_ptr<ModuleDependencyCollector> MDC)2257330f729Sjoerg static void collectIncludePCH(CompilerInstance &CI,
2267330f729Sjoerg                               std::shared_ptr<ModuleDependencyCollector> MDC) {
2277330f729Sjoerg   const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
2287330f729Sjoerg   if (PPOpts.ImplicitPCHInclude.empty())
2297330f729Sjoerg     return;
2307330f729Sjoerg 
2317330f729Sjoerg   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
2327330f729Sjoerg   FileManager &FileMgr = CI.getFileManager();
2337330f729Sjoerg   auto PCHDir = FileMgr.getDirectory(PCHInclude);
2347330f729Sjoerg   if (!PCHDir) {
2357330f729Sjoerg     MDC->addFile(PCHInclude);
2367330f729Sjoerg     return;
2377330f729Sjoerg   }
2387330f729Sjoerg 
2397330f729Sjoerg   std::error_code EC;
2407330f729Sjoerg   SmallString<128> DirNative;
2417330f729Sjoerg   llvm::sys::path::native((*PCHDir)->getName(), DirNative);
2427330f729Sjoerg   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
2437330f729Sjoerg   SimpleASTReaderListener Validator(CI.getPreprocessor());
2447330f729Sjoerg   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
2457330f729Sjoerg        Dir != DirEnd && !EC; Dir.increment(EC)) {
2467330f729Sjoerg     // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
2477330f729Sjoerg     // used here since we're not interested in validating the PCH at this time,
2487330f729Sjoerg     // but only to check whether this is a file containing an AST.
2497330f729Sjoerg     if (!ASTReader::readASTFileControlBlock(
2507330f729Sjoerg             Dir->path(), FileMgr, CI.getPCHContainerReader(),
2517330f729Sjoerg             /*FindModuleFileExtensions=*/false, Validator,
2527330f729Sjoerg             /*ValidateDiagnosticOptions=*/false))
2537330f729Sjoerg       MDC->addFile(Dir->path());
2547330f729Sjoerg   }
2557330f729Sjoerg }
2567330f729Sjoerg 
collectVFSEntries(CompilerInstance & CI,std::shared_ptr<ModuleDependencyCollector> MDC)2577330f729Sjoerg static void collectVFSEntries(CompilerInstance &CI,
2587330f729Sjoerg                               std::shared_ptr<ModuleDependencyCollector> MDC) {
2597330f729Sjoerg   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
2607330f729Sjoerg     return;
2617330f729Sjoerg 
2627330f729Sjoerg   // Collect all VFS found.
2637330f729Sjoerg   SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
2647330f729Sjoerg   for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
2657330f729Sjoerg     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
2667330f729Sjoerg         llvm::MemoryBuffer::getFile(VFSFile);
2677330f729Sjoerg     if (!Buffer)
2687330f729Sjoerg       return;
2697330f729Sjoerg     llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
2707330f729Sjoerg                                   /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
2717330f729Sjoerg   }
2727330f729Sjoerg 
2737330f729Sjoerg   for (auto &E : VFSEntries)
2747330f729Sjoerg     MDC->addFile(E.VPath, E.RPath);
2757330f729Sjoerg }
2767330f729Sjoerg 
2777330f729Sjoerg // Diagnostics
SetUpDiagnosticLog(DiagnosticOptions * DiagOpts,const CodeGenOptions * CodeGenOpts,DiagnosticsEngine & Diags)2787330f729Sjoerg static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
2797330f729Sjoerg                                const CodeGenOptions *CodeGenOpts,
2807330f729Sjoerg                                DiagnosticsEngine &Diags) {
2817330f729Sjoerg   std::error_code EC;
2827330f729Sjoerg   std::unique_ptr<raw_ostream> StreamOwner;
2837330f729Sjoerg   raw_ostream *OS = &llvm::errs();
2847330f729Sjoerg   if (DiagOpts->DiagnosticLogFile != "-") {
2857330f729Sjoerg     // Create the output stream.
2867330f729Sjoerg     auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
2877330f729Sjoerg         DiagOpts->DiagnosticLogFile, EC,
288*e038c9c4Sjoerg         llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
2897330f729Sjoerg     if (EC) {
2907330f729Sjoerg       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
2917330f729Sjoerg           << DiagOpts->DiagnosticLogFile << EC.message();
2927330f729Sjoerg     } else {
2937330f729Sjoerg       FileOS->SetUnbuffered();
2947330f729Sjoerg       OS = FileOS.get();
2957330f729Sjoerg       StreamOwner = std::move(FileOS);
2967330f729Sjoerg     }
2977330f729Sjoerg   }
2987330f729Sjoerg 
2997330f729Sjoerg   // Chain in the diagnostic client which will log the diagnostics.
3007330f729Sjoerg   auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
3017330f729Sjoerg                                                         std::move(StreamOwner));
3027330f729Sjoerg   if (CodeGenOpts)
3037330f729Sjoerg     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
3047330f729Sjoerg   if (Diags.ownsClient()) {
3057330f729Sjoerg     Diags.setClient(
3067330f729Sjoerg         new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
3077330f729Sjoerg   } else {
3087330f729Sjoerg     Diags.setClient(
3097330f729Sjoerg         new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
3107330f729Sjoerg   }
3117330f729Sjoerg }
3127330f729Sjoerg 
SetupSerializedDiagnostics(DiagnosticOptions * DiagOpts,DiagnosticsEngine & Diags,StringRef OutputFile)3137330f729Sjoerg static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
3147330f729Sjoerg                                        DiagnosticsEngine &Diags,
3157330f729Sjoerg                                        StringRef OutputFile) {
3167330f729Sjoerg   auto SerializedConsumer =
3177330f729Sjoerg       clang::serialized_diags::create(OutputFile, DiagOpts);
3187330f729Sjoerg 
3197330f729Sjoerg   if (Diags.ownsClient()) {
3207330f729Sjoerg     Diags.setClient(new ChainedDiagnosticConsumer(
3217330f729Sjoerg         Diags.takeClient(), std::move(SerializedConsumer)));
3227330f729Sjoerg   } else {
3237330f729Sjoerg     Diags.setClient(new ChainedDiagnosticConsumer(
3247330f729Sjoerg         Diags.getClient(), std::move(SerializedConsumer)));
3257330f729Sjoerg   }
3267330f729Sjoerg }
3277330f729Sjoerg 
createDiagnostics(DiagnosticConsumer * Client,bool ShouldOwnClient)3287330f729Sjoerg void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
3297330f729Sjoerg                                          bool ShouldOwnClient) {
3307330f729Sjoerg   Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
3317330f729Sjoerg                                   ShouldOwnClient, &getCodeGenOpts());
3327330f729Sjoerg }
3337330f729Sjoerg 
3347330f729Sjoerg IntrusiveRefCntPtr<DiagnosticsEngine>
createDiagnostics(DiagnosticOptions * Opts,DiagnosticConsumer * Client,bool ShouldOwnClient,const CodeGenOptions * CodeGenOpts)3357330f729Sjoerg CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
3367330f729Sjoerg                                     DiagnosticConsumer *Client,
3377330f729Sjoerg                                     bool ShouldOwnClient,
3387330f729Sjoerg                                     const CodeGenOptions *CodeGenOpts) {
3397330f729Sjoerg   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
3407330f729Sjoerg   IntrusiveRefCntPtr<DiagnosticsEngine>
3417330f729Sjoerg       Diags(new DiagnosticsEngine(DiagID, Opts));
3427330f729Sjoerg 
3437330f729Sjoerg   // Create the diagnostic client for reporting errors or for
3447330f729Sjoerg   // implementing -verify.
3457330f729Sjoerg   if (Client) {
3467330f729Sjoerg     Diags->setClient(Client, ShouldOwnClient);
3477330f729Sjoerg   } else
3487330f729Sjoerg     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
3497330f729Sjoerg 
3507330f729Sjoerg   // Chain in -verify checker, if requested.
3517330f729Sjoerg   if (Opts->VerifyDiagnostics)
3527330f729Sjoerg     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
3537330f729Sjoerg 
3547330f729Sjoerg   // Chain in -diagnostic-log-file dumper, if requested.
3557330f729Sjoerg   if (!Opts->DiagnosticLogFile.empty())
3567330f729Sjoerg     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
3577330f729Sjoerg 
3587330f729Sjoerg   if (!Opts->DiagnosticSerializationFile.empty())
3597330f729Sjoerg     SetupSerializedDiagnostics(Opts, *Diags,
3607330f729Sjoerg                                Opts->DiagnosticSerializationFile);
3617330f729Sjoerg 
3627330f729Sjoerg   // Configure our handling of diagnostics.
3637330f729Sjoerg   ProcessWarningOptions(*Diags, *Opts);
3647330f729Sjoerg 
3657330f729Sjoerg   return Diags;
3667330f729Sjoerg }
3677330f729Sjoerg 
3687330f729Sjoerg // File Manager
3697330f729Sjoerg 
createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)3707330f729Sjoerg FileManager *CompilerInstance::createFileManager(
3717330f729Sjoerg     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
3727330f729Sjoerg   if (!VFS)
3737330f729Sjoerg     VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
3747330f729Sjoerg                   : createVFSFromCompilerInvocation(getInvocation(),
3757330f729Sjoerg                                                     getDiagnostics());
3767330f729Sjoerg   assert(VFS && "FileManager has no VFS?");
3777330f729Sjoerg   FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
3787330f729Sjoerg   return FileMgr.get();
3797330f729Sjoerg }
3807330f729Sjoerg 
3817330f729Sjoerg // Source Manager
3827330f729Sjoerg 
createSourceManager(FileManager & FileMgr)3837330f729Sjoerg void CompilerInstance::createSourceManager(FileManager &FileMgr) {
3847330f729Sjoerg   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
3857330f729Sjoerg }
3867330f729Sjoerg 
3877330f729Sjoerg // Initialize the remapping of files to alternative contents, e.g.,
3887330f729Sjoerg // those specified through other files.
InitializeFileRemapping(DiagnosticsEngine & Diags,SourceManager & SourceMgr,FileManager & FileMgr,const PreprocessorOptions & InitOpts)3897330f729Sjoerg static void InitializeFileRemapping(DiagnosticsEngine &Diags,
3907330f729Sjoerg                                     SourceManager &SourceMgr,
3917330f729Sjoerg                                     FileManager &FileMgr,
3927330f729Sjoerg                                     const PreprocessorOptions &InitOpts) {
3937330f729Sjoerg   // Remap files in the source manager (with buffers).
3947330f729Sjoerg   for (const auto &RB : InitOpts.RemappedFileBuffers) {
3957330f729Sjoerg     // Create the file entry for the file that we're mapping from.
3967330f729Sjoerg     const FileEntry *FromFile =
3977330f729Sjoerg         FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
3987330f729Sjoerg     if (!FromFile) {
3997330f729Sjoerg       Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
4007330f729Sjoerg       if (!InitOpts.RetainRemappedFileBuffers)
4017330f729Sjoerg         delete RB.second;
4027330f729Sjoerg       continue;
4037330f729Sjoerg     }
4047330f729Sjoerg 
405*e038c9c4Sjoerg     // Override the contents of the "from" file with the contents of the
406*e038c9c4Sjoerg     // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
407*e038c9c4Sjoerg     // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
408*e038c9c4Sjoerg     // to the SourceManager.
409*e038c9c4Sjoerg     if (InitOpts.RetainRemappedFileBuffers)
410*e038c9c4Sjoerg       SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
411*e038c9c4Sjoerg     else
412*e038c9c4Sjoerg       SourceMgr.overrideFileContents(
413*e038c9c4Sjoerg           FromFile, std::unique_ptr<llvm::MemoryBuffer>(
414*e038c9c4Sjoerg                         const_cast<llvm::MemoryBuffer *>(RB.second)));
4157330f729Sjoerg   }
4167330f729Sjoerg 
4177330f729Sjoerg   // Remap files in the source manager (with other files).
4187330f729Sjoerg   for (const auto &RF : InitOpts.RemappedFiles) {
4197330f729Sjoerg     // Find the file that we're mapping to.
4207330f729Sjoerg     auto ToFile = FileMgr.getFile(RF.second);
4217330f729Sjoerg     if (!ToFile) {
4227330f729Sjoerg       Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
4237330f729Sjoerg       continue;
4247330f729Sjoerg     }
4257330f729Sjoerg 
4267330f729Sjoerg     // Create the file entry for the file that we're mapping from.
4277330f729Sjoerg     const FileEntry *FromFile =
4287330f729Sjoerg         FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0);
4297330f729Sjoerg     if (!FromFile) {
4307330f729Sjoerg       Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
4317330f729Sjoerg       continue;
4327330f729Sjoerg     }
4337330f729Sjoerg 
4347330f729Sjoerg     // Override the contents of the "from" file with the contents of
4357330f729Sjoerg     // the "to" file.
4367330f729Sjoerg     SourceMgr.overrideFileContents(FromFile, *ToFile);
4377330f729Sjoerg   }
4387330f729Sjoerg 
4397330f729Sjoerg   SourceMgr.setOverridenFilesKeepOriginalName(
4407330f729Sjoerg       InitOpts.RemappedFilesKeepOriginalName);
4417330f729Sjoerg }
4427330f729Sjoerg 
4437330f729Sjoerg // Preprocessor
4447330f729Sjoerg 
createPreprocessor(TranslationUnitKind TUKind)4457330f729Sjoerg void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
4467330f729Sjoerg   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
4477330f729Sjoerg 
448*e038c9c4Sjoerg   // The AST reader holds a reference to the old preprocessor (if any).
449*e038c9c4Sjoerg   TheASTReader.reset();
4507330f729Sjoerg 
4517330f729Sjoerg   // Create the Preprocessor.
4527330f729Sjoerg   HeaderSearch *HeaderInfo =
4537330f729Sjoerg       new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
4547330f729Sjoerg                        getDiagnostics(), getLangOpts(), &getTarget());
4557330f729Sjoerg   PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
4567330f729Sjoerg                                       getDiagnostics(), getLangOpts(),
4577330f729Sjoerg                                       getSourceManager(), *HeaderInfo, *this,
4587330f729Sjoerg                                       /*IdentifierInfoLookup=*/nullptr,
4597330f729Sjoerg                                       /*OwnsHeaderSearch=*/true, TUKind);
4607330f729Sjoerg   getTarget().adjust(getLangOpts());
4617330f729Sjoerg   PP->Initialize(getTarget(), getAuxTarget());
4627330f729Sjoerg 
4637330f729Sjoerg   if (PPOpts.DetailedRecord)
4647330f729Sjoerg     PP->createPreprocessingRecord();
4657330f729Sjoerg 
4667330f729Sjoerg   // Apply remappings to the source manager.
4677330f729Sjoerg   InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
4687330f729Sjoerg                           PP->getFileManager(), PPOpts);
4697330f729Sjoerg 
4707330f729Sjoerg   // Predefine macros and configure the preprocessor.
4717330f729Sjoerg   InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
4727330f729Sjoerg                          getFrontendOpts());
4737330f729Sjoerg 
4747330f729Sjoerg   // Initialize the header search object.  In CUDA compilations, we use the aux
4757330f729Sjoerg   // triple (the host triple) to initialize our header search, since we need to
4767330f729Sjoerg   // find the host headers in order to compile the CUDA code.
4777330f729Sjoerg   const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
4787330f729Sjoerg   if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
4797330f729Sjoerg       PP->getAuxTargetInfo())
4807330f729Sjoerg     HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
4817330f729Sjoerg 
4827330f729Sjoerg   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
4837330f729Sjoerg                            PP->getLangOpts(), *HeaderSearchTriple);
4847330f729Sjoerg 
4857330f729Sjoerg   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
4867330f729Sjoerg 
487*e038c9c4Sjoerg   if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
488*e038c9c4Sjoerg     std::string ModuleHash = getInvocation().getModuleHash();
489*e038c9c4Sjoerg     PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
490*e038c9c4Sjoerg     PP->getHeaderSearchInfo().setModuleCachePath(
491*e038c9c4Sjoerg         getSpecificModuleCachePath(ModuleHash));
492*e038c9c4Sjoerg   }
4937330f729Sjoerg 
4947330f729Sjoerg   // Handle generating dependencies, if requested.
4957330f729Sjoerg   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
4967330f729Sjoerg   if (!DepOpts.OutputFile.empty())
4977330f729Sjoerg     addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
4987330f729Sjoerg   if (!DepOpts.DOTOutputFile.empty())
4997330f729Sjoerg     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
5007330f729Sjoerg                              getHeaderSearchOpts().Sysroot);
5017330f729Sjoerg 
5027330f729Sjoerg   // If we don't have a collector, but we are collecting module dependencies,
5037330f729Sjoerg   // then we're the top level compiler instance and need to create one.
5047330f729Sjoerg   if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
5057330f729Sjoerg     ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
5067330f729Sjoerg         DepOpts.ModuleDependencyOutputDir);
5077330f729Sjoerg   }
5087330f729Sjoerg 
5097330f729Sjoerg   // If there is a module dep collector, register with other dep collectors
5107330f729Sjoerg   // and also (a) collect header maps and (b) TODO: input vfs overlay files.
5117330f729Sjoerg   if (ModuleDepCollector) {
5127330f729Sjoerg     addDependencyCollector(ModuleDepCollector);
5137330f729Sjoerg     collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
5147330f729Sjoerg     collectIncludePCH(*this, ModuleDepCollector);
5157330f729Sjoerg     collectVFSEntries(*this, ModuleDepCollector);
5167330f729Sjoerg   }
5177330f729Sjoerg 
5187330f729Sjoerg   for (auto &Listener : DependencyCollectors)
5197330f729Sjoerg     Listener->attachToPreprocessor(*PP);
5207330f729Sjoerg 
5217330f729Sjoerg   // Handle generating header include information, if requested.
5227330f729Sjoerg   if (DepOpts.ShowHeaderIncludes)
5237330f729Sjoerg     AttachHeaderIncludeGen(*PP, DepOpts);
5247330f729Sjoerg   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
5257330f729Sjoerg     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
5267330f729Sjoerg     if (OutputPath == "-")
5277330f729Sjoerg       OutputPath = "";
5287330f729Sjoerg     AttachHeaderIncludeGen(*PP, DepOpts,
5297330f729Sjoerg                            /*ShowAllHeaders=*/true, OutputPath,
5307330f729Sjoerg                            /*ShowDepth=*/false);
5317330f729Sjoerg   }
5327330f729Sjoerg 
5337330f729Sjoerg   if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
5347330f729Sjoerg     AttachHeaderIncludeGen(*PP, DepOpts,
5357330f729Sjoerg                            /*ShowAllHeaders=*/true, /*OutputPath=*/"",
5367330f729Sjoerg                            /*ShowDepth=*/true, /*MSStyle=*/true);
5377330f729Sjoerg   }
5387330f729Sjoerg }
5397330f729Sjoerg 
getSpecificModuleCachePath(StringRef ModuleHash)540*e038c9c4Sjoerg std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
541*e038c9c4Sjoerg   // Set up the module path, including the hash for the module-creation options.
5427330f729Sjoerg   SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
5437330f729Sjoerg   if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
544*e038c9c4Sjoerg     llvm::sys::path::append(SpecificModuleCache, ModuleHash);
545*e038c9c4Sjoerg   return std::string(SpecificModuleCache.str());
5467330f729Sjoerg }
5477330f729Sjoerg 
5487330f729Sjoerg // ASTContext
5497330f729Sjoerg 
createASTContext()5507330f729Sjoerg void CompilerInstance::createASTContext() {
5517330f729Sjoerg   Preprocessor &PP = getPreprocessor();
5527330f729Sjoerg   auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
5537330f729Sjoerg                                  PP.getIdentifierTable(), PP.getSelectorTable(),
5547330f729Sjoerg                                  PP.getBuiltinInfo());
5557330f729Sjoerg   Context->InitBuiltinTypes(getTarget(), getAuxTarget());
5567330f729Sjoerg   setASTContext(Context);
5577330f729Sjoerg }
5587330f729Sjoerg 
5597330f729Sjoerg // ExternalASTSource
5607330f729Sjoerg 
createPCHExternalASTSource(StringRef Path,DisableValidationForModuleKind DisableValidation,bool AllowPCHWithCompilerErrors,void * DeserializationListener,bool OwnDeserializationListener)5617330f729Sjoerg void CompilerInstance::createPCHExternalASTSource(
562*e038c9c4Sjoerg     StringRef Path, DisableValidationForModuleKind DisableValidation,
563*e038c9c4Sjoerg     bool AllowPCHWithCompilerErrors, void *DeserializationListener,
564*e038c9c4Sjoerg     bool OwnDeserializationListener) {
5657330f729Sjoerg   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
566*e038c9c4Sjoerg   TheASTReader = createPCHExternalASTSource(
567*e038c9c4Sjoerg       Path, getHeaderSearchOpts().Sysroot, DisableValidation,
5687330f729Sjoerg       AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
5697330f729Sjoerg       getASTContext(), getPCHContainerReader(),
5707330f729Sjoerg       getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
5717330f729Sjoerg       DeserializationListener, OwnDeserializationListener, Preamble,
5727330f729Sjoerg       getFrontendOpts().UseGlobalModuleIndex);
5737330f729Sjoerg }
5747330f729Sjoerg 
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)5757330f729Sjoerg IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
576*e038c9c4Sjoerg     StringRef Path, StringRef Sysroot,
577*e038c9c4Sjoerg     DisableValidationForModuleKind DisableValidation,
5787330f729Sjoerg     bool AllowPCHWithCompilerErrors, Preprocessor &PP,
5797330f729Sjoerg     InMemoryModuleCache &ModuleCache, ASTContext &Context,
5807330f729Sjoerg     const PCHContainerReader &PCHContainerRdr,
5817330f729Sjoerg     ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
5827330f729Sjoerg     ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
5837330f729Sjoerg     void *DeserializationListener, bool OwnDeserializationListener,
5847330f729Sjoerg     bool Preamble, bool UseGlobalModuleIndex) {
5857330f729Sjoerg   HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
5867330f729Sjoerg 
5877330f729Sjoerg   IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
5887330f729Sjoerg       PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
589*e038c9c4Sjoerg       Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
5907330f729Sjoerg       AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
5917330f729Sjoerg       HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
5927330f729Sjoerg       UseGlobalModuleIndex));
5937330f729Sjoerg 
5947330f729Sjoerg   // We need the external source to be set up before we read the AST, because
5957330f729Sjoerg   // eagerly-deserialized declarations may use it.
5967330f729Sjoerg   Context.setExternalSource(Reader.get());
5977330f729Sjoerg 
5987330f729Sjoerg   Reader->setDeserializationListener(
5997330f729Sjoerg       static_cast<ASTDeserializationListener *>(DeserializationListener),
6007330f729Sjoerg       /*TakeOwnership=*/OwnDeserializationListener);
6017330f729Sjoerg 
6027330f729Sjoerg   for (auto &Listener : DependencyCollectors)
6037330f729Sjoerg     Listener->attachToASTReader(*Reader);
6047330f729Sjoerg 
6057330f729Sjoerg   switch (Reader->ReadAST(Path,
6067330f729Sjoerg                           Preamble ? serialization::MK_Preamble
6077330f729Sjoerg                                    : serialization::MK_PCH,
6087330f729Sjoerg                           SourceLocation(),
6097330f729Sjoerg                           ASTReader::ARR_None)) {
6107330f729Sjoerg   case ASTReader::Success:
6117330f729Sjoerg     // Set the predefines buffer as suggested by the PCH reader. Typically, the
6127330f729Sjoerg     // predefines buffer will be empty.
6137330f729Sjoerg     PP.setPredefines(Reader->getSuggestedPredefines());
6147330f729Sjoerg     return Reader;
6157330f729Sjoerg 
6167330f729Sjoerg   case ASTReader::Failure:
6177330f729Sjoerg     // Unrecoverable failure: don't even try to process the input file.
6187330f729Sjoerg     break;
6197330f729Sjoerg 
6207330f729Sjoerg   case ASTReader::Missing:
6217330f729Sjoerg   case ASTReader::OutOfDate:
6227330f729Sjoerg   case ASTReader::VersionMismatch:
6237330f729Sjoerg   case ASTReader::ConfigurationMismatch:
6247330f729Sjoerg   case ASTReader::HadErrors:
6257330f729Sjoerg     // No suitable PCH file could be found. Return an error.
6267330f729Sjoerg     break;
6277330f729Sjoerg   }
6287330f729Sjoerg 
6297330f729Sjoerg   Context.setExternalSource(nullptr);
6307330f729Sjoerg   return nullptr;
6317330f729Sjoerg }
6327330f729Sjoerg 
6337330f729Sjoerg // Code Completion
6347330f729Sjoerg 
EnableCodeCompletion(Preprocessor & PP,StringRef Filename,unsigned Line,unsigned Column)6357330f729Sjoerg static bool EnableCodeCompletion(Preprocessor &PP,
6367330f729Sjoerg                                  StringRef Filename,
6377330f729Sjoerg                                  unsigned Line,
6387330f729Sjoerg                                  unsigned Column) {
6397330f729Sjoerg   // Tell the source manager to chop off the given file at a specific
6407330f729Sjoerg   // line and column.
6417330f729Sjoerg   auto Entry = PP.getFileManager().getFile(Filename);
6427330f729Sjoerg   if (!Entry) {
6437330f729Sjoerg     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
6447330f729Sjoerg       << Filename;
6457330f729Sjoerg     return true;
6467330f729Sjoerg   }
6477330f729Sjoerg 
6487330f729Sjoerg   // Truncate the named file at the given line/column.
6497330f729Sjoerg   PP.SetCodeCompletionPoint(*Entry, Line, Column);
6507330f729Sjoerg   return false;
6517330f729Sjoerg }
6527330f729Sjoerg 
createCodeCompletionConsumer()6537330f729Sjoerg void CompilerInstance::createCodeCompletionConsumer() {
6547330f729Sjoerg   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
6557330f729Sjoerg   if (!CompletionConsumer) {
6567330f729Sjoerg     setCodeCompletionConsumer(
6577330f729Sjoerg       createCodeCompletionConsumer(getPreprocessor(),
6587330f729Sjoerg                                    Loc.FileName, Loc.Line, Loc.Column,
6597330f729Sjoerg                                    getFrontendOpts().CodeCompleteOpts,
6607330f729Sjoerg                                    llvm::outs()));
6617330f729Sjoerg     if (!CompletionConsumer)
6627330f729Sjoerg       return;
6637330f729Sjoerg   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
6647330f729Sjoerg                                   Loc.Line, Loc.Column)) {
6657330f729Sjoerg     setCodeCompletionConsumer(nullptr);
6667330f729Sjoerg     return;
6677330f729Sjoerg   }
6687330f729Sjoerg }
6697330f729Sjoerg 
createFrontendTimer()6707330f729Sjoerg void CompilerInstance::createFrontendTimer() {
6717330f729Sjoerg   FrontendTimerGroup.reset(
6727330f729Sjoerg       new llvm::TimerGroup("frontend", "Clang front-end time report"));
6737330f729Sjoerg   FrontendTimer.reset(
6747330f729Sjoerg       new llvm::Timer("frontend", "Clang front-end timer",
6757330f729Sjoerg                       *FrontendTimerGroup));
6767330f729Sjoerg }
6777330f729Sjoerg 
6787330f729Sjoerg CodeCompleteConsumer *
createCodeCompletionConsumer(Preprocessor & PP,StringRef Filename,unsigned Line,unsigned Column,const CodeCompleteOptions & Opts,raw_ostream & OS)6797330f729Sjoerg CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
6807330f729Sjoerg                                                StringRef Filename,
6817330f729Sjoerg                                                unsigned Line,
6827330f729Sjoerg                                                unsigned Column,
6837330f729Sjoerg                                                const CodeCompleteOptions &Opts,
6847330f729Sjoerg                                                raw_ostream &OS) {
6857330f729Sjoerg   if (EnableCodeCompletion(PP, Filename, Line, Column))
6867330f729Sjoerg     return nullptr;
6877330f729Sjoerg 
6887330f729Sjoerg   // Set up the creation routine for code-completion.
6897330f729Sjoerg   return new PrintingCodeCompleteConsumer(Opts, OS);
6907330f729Sjoerg }
6917330f729Sjoerg 
createSema(TranslationUnitKind TUKind,CodeCompleteConsumer * CompletionConsumer)6927330f729Sjoerg void CompilerInstance::createSema(TranslationUnitKind TUKind,
6937330f729Sjoerg                                   CodeCompleteConsumer *CompletionConsumer) {
6947330f729Sjoerg   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
6957330f729Sjoerg                          TUKind, CompletionConsumer));
6967330f729Sjoerg   // Attach the external sema source if there is any.
6977330f729Sjoerg   if (ExternalSemaSrc) {
6987330f729Sjoerg     TheSema->addExternalSource(ExternalSemaSrc.get());
6997330f729Sjoerg     ExternalSemaSrc->InitializeSema(*TheSema);
7007330f729Sjoerg   }
7017330f729Sjoerg }
7027330f729Sjoerg 
7037330f729Sjoerg // Output Files
7047330f729Sjoerg 
clearOutputFiles(bool EraseFiles)7057330f729Sjoerg void CompilerInstance::clearOutputFiles(bool EraseFiles) {
7067330f729Sjoerg   for (OutputFile &OF : OutputFiles) {
7077330f729Sjoerg     if (EraseFiles) {
708*e038c9c4Sjoerg       if (!OF.TempFilename.empty()) {
7097330f729Sjoerg         llvm::sys::fs::remove(OF.TempFilename);
710*e038c9c4Sjoerg         continue;
711*e038c9c4Sjoerg       }
712*e038c9c4Sjoerg       if (!OF.Filename.empty())
713*e038c9c4Sjoerg         llvm::sys::fs::remove(OF.Filename);
714*e038c9c4Sjoerg       continue;
715*e038c9c4Sjoerg     }
716*e038c9c4Sjoerg 
717*e038c9c4Sjoerg     if (OF.TempFilename.empty())
718*e038c9c4Sjoerg       continue;
7197330f729Sjoerg 
7207330f729Sjoerg     // If '-working-directory' was passed, the output filename should be
7217330f729Sjoerg     // relative to that.
722*e038c9c4Sjoerg     SmallString<128> NewOutFile(OF.Filename);
7237330f729Sjoerg     FileMgr->FixupRelativePath(NewOutFile);
724*e038c9c4Sjoerg     std::error_code EC = llvm::sys::fs::rename(OF.TempFilename, NewOutFile);
725*e038c9c4Sjoerg     if (!EC)
726*e038c9c4Sjoerg       continue;
7277330f729Sjoerg     getDiagnostics().Report(diag::err_unable_to_rename_temp)
728*e038c9c4Sjoerg         << OF.TempFilename << OF.Filename << EC.message();
7297330f729Sjoerg 
7307330f729Sjoerg     llvm::sys::fs::remove(OF.TempFilename);
7317330f729Sjoerg   }
7327330f729Sjoerg   OutputFiles.clear();
7337330f729Sjoerg   if (DeleteBuiltModules) {
7347330f729Sjoerg     for (auto &Module : BuiltModules)
7357330f729Sjoerg       llvm::sys::fs::remove(Module.second);
7367330f729Sjoerg     BuiltModules.clear();
7377330f729Sjoerg   }
7387330f729Sjoerg }
7397330f729Sjoerg 
7407330f729Sjoerg std::unique_ptr<raw_pwrite_stream>
createDefaultOutputFile(bool Binary,StringRef InFile,StringRef Extension,bool RemoveFileOnSignal,bool CreateMissingDirectories)7417330f729Sjoerg CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
742*e038c9c4Sjoerg                                           StringRef Extension,
743*e038c9c4Sjoerg                                           bool RemoveFileOnSignal,
744*e038c9c4Sjoerg                                           bool CreateMissingDirectories) {
745*e038c9c4Sjoerg   StringRef OutputPath = getFrontendOpts().OutputFile;
746*e038c9c4Sjoerg   Optional<SmallString<128>> PathStorage;
747*e038c9c4Sjoerg   if (OutputPath.empty()) {
748*e038c9c4Sjoerg     if (InFile == "-" || Extension.empty()) {
749*e038c9c4Sjoerg       OutputPath = "-";
750*e038c9c4Sjoerg     } else {
751*e038c9c4Sjoerg       PathStorage.emplace(InFile);
752*e038c9c4Sjoerg       llvm::sys::path::replace_extension(*PathStorage, Extension);
753*e038c9c4Sjoerg       OutputPath = *PathStorage;
754*e038c9c4Sjoerg     }
755*e038c9c4Sjoerg   }
756*e038c9c4Sjoerg 
757*e038c9c4Sjoerg   // Force a temporary file if RemoveFileOnSignal was disabled.
758*e038c9c4Sjoerg   return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
759*e038c9c4Sjoerg                           getFrontendOpts().UseTemporary || !RemoveFileOnSignal,
760*e038c9c4Sjoerg                           CreateMissingDirectories);
7617330f729Sjoerg }
7627330f729Sjoerg 
createNullOutputFile()7637330f729Sjoerg std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
7647330f729Sjoerg   return std::make_unique<llvm::raw_null_ostream>();
7657330f729Sjoerg }
7667330f729Sjoerg 
7677330f729Sjoerg std::unique_ptr<raw_pwrite_stream>
createOutputFile(StringRef OutputPath,bool Binary,bool RemoveFileOnSignal,bool UseTemporary,bool CreateMissingDirectories)7687330f729Sjoerg CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
769*e038c9c4Sjoerg                                    bool RemoveFileOnSignal, bool UseTemporary,
7707330f729Sjoerg                                    bool CreateMissingDirectories) {
771*e038c9c4Sjoerg   Expected<std::unique_ptr<raw_pwrite_stream>> OS =
772*e038c9c4Sjoerg       createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
773*e038c9c4Sjoerg                            CreateMissingDirectories);
774*e038c9c4Sjoerg   if (OS)
775*e038c9c4Sjoerg     return std::move(*OS);
776*e038c9c4Sjoerg   getDiagnostics().Report(diag::err_fe_unable_to_open_output)
777*e038c9c4Sjoerg       << OutputPath << errorToErrorCode(OS.takeError()).message();
7787330f729Sjoerg   return nullptr;
7797330f729Sjoerg }
7807330f729Sjoerg 
781*e038c9c4Sjoerg Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
createOutputFileImpl(StringRef OutputPath,bool Binary,bool RemoveFileOnSignal,bool UseTemporary,bool CreateMissingDirectories)782*e038c9c4Sjoerg CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
783*e038c9c4Sjoerg                                        bool RemoveFileOnSignal,
784*e038c9c4Sjoerg                                        bool UseTemporary,
785*e038c9c4Sjoerg                                        bool CreateMissingDirectories) {
7867330f729Sjoerg   assert((!CreateMissingDirectories || UseTemporary) &&
7877330f729Sjoerg          "CreateMissingDirectories is only allowed when using temporary files");
7887330f729Sjoerg 
7897330f729Sjoerg   std::unique_ptr<llvm::raw_fd_ostream> OS;
790*e038c9c4Sjoerg   Optional<StringRef> OSFile;
7917330f729Sjoerg 
7927330f729Sjoerg   if (UseTemporary) {
793*e038c9c4Sjoerg     if (OutputPath == "-")
7947330f729Sjoerg       UseTemporary = false;
7957330f729Sjoerg     else {
7967330f729Sjoerg       llvm::sys::fs::file_status Status;
7977330f729Sjoerg       llvm::sys::fs::status(OutputPath, Status);
7987330f729Sjoerg       if (llvm::sys::fs::exists(Status)) {
7997330f729Sjoerg         // Fail early if we can't write to the final destination.
800*e038c9c4Sjoerg         if (!llvm::sys::fs::can_write(OutputPath))
801*e038c9c4Sjoerg           return llvm::errorCodeToError(
802*e038c9c4Sjoerg               make_error_code(llvm::errc::operation_not_permitted));
8037330f729Sjoerg 
8047330f729Sjoerg         // Don't use a temporary if the output is a special file. This handles
8057330f729Sjoerg         // things like '-o /dev/null'
8067330f729Sjoerg         if (!llvm::sys::fs::is_regular_file(Status))
8077330f729Sjoerg           UseTemporary = false;
8087330f729Sjoerg       }
8097330f729Sjoerg     }
8107330f729Sjoerg   }
8117330f729Sjoerg 
812*e038c9c4Sjoerg   std::string TempFile;
8137330f729Sjoerg   if (UseTemporary) {
8147330f729Sjoerg     // Create a temporary file.
8157330f729Sjoerg     // Insert -%%%%%%%% before the extension (if any), and because some tools
8167330f729Sjoerg     // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
8177330f729Sjoerg     // artifacts, also append .tmp.
818*e038c9c4Sjoerg     StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
8197330f729Sjoerg     SmallString<128> TempPath =
820*e038c9c4Sjoerg         StringRef(OutputPath).drop_back(OutputExtension.size());
8217330f729Sjoerg     TempPath += "-%%%%%%%%";
8227330f729Sjoerg     TempPath += OutputExtension;
8237330f729Sjoerg     TempPath += ".tmp";
8247330f729Sjoerg     int fd;
825*e038c9c4Sjoerg     std::error_code EC = llvm::sys::fs::createUniqueFile(
826*e038c9c4Sjoerg         TempPath, fd, TempPath,
827*e038c9c4Sjoerg         Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text);
8287330f729Sjoerg 
8297330f729Sjoerg     if (CreateMissingDirectories &&
8307330f729Sjoerg         EC == llvm::errc::no_such_file_or_directory) {
8317330f729Sjoerg       StringRef Parent = llvm::sys::path::parent_path(OutputPath);
8327330f729Sjoerg       EC = llvm::sys::fs::create_directories(Parent);
8337330f729Sjoerg       if (!EC) {
834*e038c9c4Sjoerg         EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath,
835*e038c9c4Sjoerg                                              Binary ? llvm::sys::fs::OF_None
836*e038c9c4Sjoerg                                                     : llvm::sys::fs::OF_Text);
8377330f729Sjoerg       }
8387330f729Sjoerg     }
8397330f729Sjoerg 
8407330f729Sjoerg     if (!EC) {
8417330f729Sjoerg       OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
842*e038c9c4Sjoerg       OSFile = TempFile = std::string(TempPath.str());
8437330f729Sjoerg     }
8447330f729Sjoerg     // If we failed to create the temporary, fallback to writing to the file
8457330f729Sjoerg     // directly. This handles the corner case where we cannot write to the
8467330f729Sjoerg     // directory, but can write to the file.
8477330f729Sjoerg   }
8487330f729Sjoerg 
8497330f729Sjoerg   if (!OS) {
850*e038c9c4Sjoerg     OSFile = OutputPath;
851*e038c9c4Sjoerg     std::error_code EC;
8527330f729Sjoerg     OS.reset(new llvm::raw_fd_ostream(
853*e038c9c4Sjoerg         *OSFile, EC,
854*e038c9c4Sjoerg         (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
855*e038c9c4Sjoerg     if (EC)
856*e038c9c4Sjoerg       return llvm::errorCodeToError(EC);
8577330f729Sjoerg   }
8587330f729Sjoerg 
8597330f729Sjoerg   // Make sure the out stream file gets removed if we crash.
8607330f729Sjoerg   if (RemoveFileOnSignal)
861*e038c9c4Sjoerg     llvm::sys::RemoveFileOnSignal(*OSFile);
8627330f729Sjoerg 
863*e038c9c4Sjoerg   // Add the output file -- but don't try to remove "-", since this means we are
864*e038c9c4Sjoerg   // using stdin.
865*e038c9c4Sjoerg   OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
866*e038c9c4Sjoerg                            std::move(TempFile));
8677330f729Sjoerg 
8687330f729Sjoerg   if (!Binary || OS->supportsSeeking())
8697330f729Sjoerg     return std::move(OS);
8707330f729Sjoerg 
871*e038c9c4Sjoerg   return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
8727330f729Sjoerg }
8737330f729Sjoerg 
8747330f729Sjoerg // Initialization Utilities
8757330f729Sjoerg 
InitializeSourceManager(const FrontendInputFile & Input)8767330f729Sjoerg bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
877*e038c9c4Sjoerg   return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
878*e038c9c4Sjoerg                                  getSourceManager());
8797330f729Sjoerg }
8807330f729Sjoerg 
8817330f729Sjoerg // static
InitializeSourceManager(const FrontendInputFile & Input,DiagnosticsEngine & Diags,FileManager & FileMgr,SourceManager & SourceMgr)882*e038c9c4Sjoerg bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
883*e038c9c4Sjoerg                                                DiagnosticsEngine &Diags,
884*e038c9c4Sjoerg                                                FileManager &FileMgr,
885*e038c9c4Sjoerg                                                SourceManager &SourceMgr) {
8867330f729Sjoerg   SrcMgr::CharacteristicKind Kind =
8877330f729Sjoerg       Input.getKind().getFormat() == InputKind::ModuleMap
8887330f729Sjoerg           ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
8897330f729Sjoerg                              : SrcMgr::C_User_ModuleMap
8907330f729Sjoerg           : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
8917330f729Sjoerg 
8927330f729Sjoerg   if (Input.isBuffer()) {
893*e038c9c4Sjoerg     SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
8947330f729Sjoerg     assert(SourceMgr.getMainFileID().isValid() &&
8957330f729Sjoerg            "Couldn't establish MainFileID!");
8967330f729Sjoerg     return true;
8977330f729Sjoerg   }
8987330f729Sjoerg 
8997330f729Sjoerg   StringRef InputFile = Input.getFile();
9007330f729Sjoerg 
9017330f729Sjoerg   // Figure out where to get and map in the main file.
902*e038c9c4Sjoerg   auto FileOrErr = InputFile == "-"
903*e038c9c4Sjoerg                        ? FileMgr.getSTDIN()
904*e038c9c4Sjoerg                        : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
9057330f729Sjoerg   if (!FileOrErr) {
906*e038c9c4Sjoerg     // FIXME: include the error in the diagnostic even when it's not stdin.
907*e038c9c4Sjoerg     auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
908*e038c9c4Sjoerg     if (InputFile != "-")
9097330f729Sjoerg       Diags.Report(diag::err_fe_error_reading) << InputFile;
910*e038c9c4Sjoerg     else
9117330f729Sjoerg       Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
9127330f729Sjoerg     return false;
9137330f729Sjoerg   }
9147330f729Sjoerg 
9157330f729Sjoerg   SourceMgr.setMainFileID(
916*e038c9c4Sjoerg       SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
9177330f729Sjoerg 
9187330f729Sjoerg   assert(SourceMgr.getMainFileID().isValid() &&
9197330f729Sjoerg          "Couldn't establish MainFileID!");
9207330f729Sjoerg   return true;
9217330f729Sjoerg }
9227330f729Sjoerg 
9237330f729Sjoerg // High-Level Operations
9247330f729Sjoerg 
ExecuteAction(FrontendAction & Act)9257330f729Sjoerg bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
9267330f729Sjoerg   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
9277330f729Sjoerg   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
9287330f729Sjoerg   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
9297330f729Sjoerg 
9307330f729Sjoerg   // Mark this point as the bottom of the stack if we don't have somewhere
9317330f729Sjoerg   // better. We generally expect frontend actions to be invoked with (nearly)
9327330f729Sjoerg   // DesiredStackSpace available.
9337330f729Sjoerg   noteBottomOfStack();
9347330f729Sjoerg 
9357330f729Sjoerg   raw_ostream &OS = getVerboseOutputStream();
9367330f729Sjoerg 
9377330f729Sjoerg   if (!Act.PrepareToExecute(*this))
9387330f729Sjoerg     return false;
9397330f729Sjoerg 
940*e038c9c4Sjoerg   if (!createTarget())
9417330f729Sjoerg     return false;
9427330f729Sjoerg 
9437330f729Sjoerg   // rewriter project will change target built-in bool type from its default.
9447330f729Sjoerg   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
9457330f729Sjoerg     getTarget().noSignedCharForObjCBool();
9467330f729Sjoerg 
9477330f729Sjoerg   // Validate/process some options.
9487330f729Sjoerg   if (getHeaderSearchOpts().Verbose)
9497330f729Sjoerg     OS << "clang -cc1 version " CLANG_VERSION_STRING
9507330f729Sjoerg        << " based upon " << BACKEND_PACKAGE_STRING
9517330f729Sjoerg        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
9527330f729Sjoerg 
953*e038c9c4Sjoerg   if (getCodeGenOpts().TimePasses)
9547330f729Sjoerg     createFrontendTimer();
9557330f729Sjoerg 
9567330f729Sjoerg   if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
9577330f729Sjoerg     llvm::EnableStatistics(false);
9587330f729Sjoerg 
9597330f729Sjoerg   for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
9607330f729Sjoerg     // Reset the ID tables if we are reusing the SourceManager and parsing
9617330f729Sjoerg     // regular files.
9627330f729Sjoerg     if (hasSourceManager() && !Act.isModelParsingAction())
9637330f729Sjoerg       getSourceManager().clearIDTables();
9647330f729Sjoerg 
9657330f729Sjoerg     if (Act.BeginSourceFile(*this, FIF)) {
9667330f729Sjoerg       if (llvm::Error Err = Act.Execute()) {
9677330f729Sjoerg         consumeError(std::move(Err)); // FIXME this drops errors on the floor.
9687330f729Sjoerg       }
9697330f729Sjoerg       Act.EndSourceFile();
9707330f729Sjoerg     }
9717330f729Sjoerg   }
9727330f729Sjoerg 
9737330f729Sjoerg   // Notify the diagnostic client that all files were processed.
9747330f729Sjoerg   getDiagnostics().getClient()->finish();
9757330f729Sjoerg 
9767330f729Sjoerg   if (getDiagnosticOpts().ShowCarets) {
9777330f729Sjoerg     // We can have multiple diagnostics sharing one diagnostic client.
9787330f729Sjoerg     // Get the total number of warnings/errors from the client.
9797330f729Sjoerg     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
9807330f729Sjoerg     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
9817330f729Sjoerg 
9827330f729Sjoerg     if (NumWarnings)
9837330f729Sjoerg       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
9847330f729Sjoerg     if (NumWarnings && NumErrors)
9857330f729Sjoerg       OS << " and ";
9867330f729Sjoerg     if (NumErrors)
9877330f729Sjoerg       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
9887330f729Sjoerg     if (NumWarnings || NumErrors) {
9897330f729Sjoerg       OS << " generated";
9907330f729Sjoerg       if (getLangOpts().CUDA) {
9917330f729Sjoerg         if (!getLangOpts().CUDAIsDevice) {
9927330f729Sjoerg           OS << " when compiling for host";
9937330f729Sjoerg         } else {
9947330f729Sjoerg           OS << " when compiling for " << getTargetOpts().CPU;
9957330f729Sjoerg         }
9967330f729Sjoerg       }
9977330f729Sjoerg       OS << ".\n";
9987330f729Sjoerg     }
9997330f729Sjoerg   }
10007330f729Sjoerg 
10017330f729Sjoerg   if (getFrontendOpts().ShowStats) {
10027330f729Sjoerg     if (hasFileManager()) {
10037330f729Sjoerg       getFileManager().PrintStats();
10047330f729Sjoerg       OS << '\n';
10057330f729Sjoerg     }
10067330f729Sjoerg     llvm::PrintStatistics(OS);
10077330f729Sjoerg   }
10087330f729Sjoerg   StringRef StatsFile = getFrontendOpts().StatsFile;
10097330f729Sjoerg   if (!StatsFile.empty()) {
10107330f729Sjoerg     std::error_code EC;
10117330f729Sjoerg     auto StatS = std::make_unique<llvm::raw_fd_ostream>(
1012*e038c9c4Sjoerg         StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF);
10137330f729Sjoerg     if (EC) {
10147330f729Sjoerg       getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
10157330f729Sjoerg           << StatsFile << EC.message();
10167330f729Sjoerg     } else {
10177330f729Sjoerg       llvm::PrintStatisticsJSON(*StatS);
10187330f729Sjoerg     }
10197330f729Sjoerg   }
10207330f729Sjoerg 
10217330f729Sjoerg   return !getDiagnostics().getClient()->getNumErrors();
10227330f729Sjoerg }
10237330f729Sjoerg 
10247330f729Sjoerg /// Determine the appropriate source input kind based on language
10257330f729Sjoerg /// options.
getLanguageFromOptions(const LangOptions & LangOpts)10267330f729Sjoerg static Language getLanguageFromOptions(const LangOptions &LangOpts) {
10277330f729Sjoerg   if (LangOpts.OpenCL)
10287330f729Sjoerg     return Language::OpenCL;
10297330f729Sjoerg   if (LangOpts.CUDA)
10307330f729Sjoerg     return Language::CUDA;
10317330f729Sjoerg   if (LangOpts.ObjC)
10327330f729Sjoerg     return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
10337330f729Sjoerg   return LangOpts.CPlusPlus ? Language::CXX : Language::C;
10347330f729Sjoerg }
10357330f729Sjoerg 
10367330f729Sjoerg /// Compile a module file for the given module, using the options
10377330f729Sjoerg /// provided by the importing compiler instance. Returns true if the module
10387330f729Sjoerg /// was built without errors.
10397330f729Sjoerg 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 &){})10407330f729Sjoerg compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
10417330f729Sjoerg                   StringRef ModuleName, FrontendInputFile Input,
10427330f729Sjoerg                   StringRef OriginalModuleMapFile, StringRef ModuleFileName,
10437330f729Sjoerg                   llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
10447330f729Sjoerg                       [](CompilerInstance &) {},
10457330f729Sjoerg                   llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
__anon502c5ec40202(CompilerInstance &) 10467330f729Sjoerg                       [](CompilerInstance &) {}) {
10477330f729Sjoerg   llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
10487330f729Sjoerg 
10497330f729Sjoerg   // Construct a compiler invocation for creating this module.
10507330f729Sjoerg   auto Invocation =
10517330f729Sjoerg       std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
10527330f729Sjoerg 
10537330f729Sjoerg   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
10547330f729Sjoerg 
10557330f729Sjoerg   // For any options that aren't intended to affect how a module is built,
10567330f729Sjoerg   // reset them to their default values.
10577330f729Sjoerg   Invocation->getLangOpts()->resetNonModularOptions();
10587330f729Sjoerg   PPOpts.resetNonModularOptions();
10597330f729Sjoerg 
10607330f729Sjoerg   // Remove any macro definitions that are explicitly ignored by the module.
10617330f729Sjoerg   // They aren't supposed to affect how the module is built anyway.
10627330f729Sjoerg   HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
10637330f729Sjoerg   PPOpts.Macros.erase(
10647330f729Sjoerg       std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
__anon502c5ec40302(const std::pair<std::string, bool> &def) 10657330f729Sjoerg                      [&HSOpts](const std::pair<std::string, bool> &def) {
10667330f729Sjoerg         StringRef MacroDef = def.first;
10677330f729Sjoerg         return HSOpts.ModulesIgnoreMacros.count(
10687330f729Sjoerg                    llvm::CachedHashString(MacroDef.split('=').first)) > 0;
10697330f729Sjoerg       }),
10707330f729Sjoerg       PPOpts.Macros.end());
10717330f729Sjoerg 
10727330f729Sjoerg   // If the original compiler invocation had -fmodule-name, pass it through.
10737330f729Sjoerg   Invocation->getLangOpts()->ModuleName =
10747330f729Sjoerg       ImportingInstance.getInvocation().getLangOpts()->ModuleName;
10757330f729Sjoerg 
10767330f729Sjoerg   // Note the name of the module we're building.
1077*e038c9c4Sjoerg   Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
10787330f729Sjoerg 
10797330f729Sjoerg   // Make sure that the failed-module structure has been allocated in
10807330f729Sjoerg   // the importing instance, and propagate the pointer to the newly-created
10817330f729Sjoerg   // instance.
10827330f729Sjoerg   PreprocessorOptions &ImportingPPOpts
10837330f729Sjoerg     = ImportingInstance.getInvocation().getPreprocessorOpts();
10847330f729Sjoerg   if (!ImportingPPOpts.FailedModules)
10857330f729Sjoerg     ImportingPPOpts.FailedModules =
10867330f729Sjoerg         std::make_shared<PreprocessorOptions::FailedModulesSet>();
10877330f729Sjoerg   PPOpts.FailedModules = ImportingPPOpts.FailedModules;
10887330f729Sjoerg 
10897330f729Sjoerg   // If there is a module map file, build the module using the module map.
10907330f729Sjoerg   // Set up the inputs/outputs so that we build the module from its umbrella
10917330f729Sjoerg   // header.
10927330f729Sjoerg   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
10937330f729Sjoerg   FrontendOpts.OutputFile = ModuleFileName.str();
10947330f729Sjoerg   FrontendOpts.DisableFree = false;
10957330f729Sjoerg   FrontendOpts.GenerateGlobalModuleIndex = false;
10967330f729Sjoerg   FrontendOpts.BuildingImplicitModule = true;
1097*e038c9c4Sjoerg   FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
10987330f729Sjoerg   // Force implicitly-built modules to hash the content of the module file.
10997330f729Sjoerg   HSOpts.ModulesHashContent = true;
11007330f729Sjoerg   FrontendOpts.Inputs = {Input};
11017330f729Sjoerg 
11027330f729Sjoerg   // Don't free the remapped file buffers; they are owned by our caller.
11037330f729Sjoerg   PPOpts.RetainRemappedFileBuffers = true;
11047330f729Sjoerg 
11057330f729Sjoerg   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
11067330f729Sjoerg   assert(ImportingInstance.getInvocation().getModuleHash() ==
11077330f729Sjoerg          Invocation->getModuleHash() && "Module hash mismatch!");
11087330f729Sjoerg 
11097330f729Sjoerg   // Construct a compiler instance that will be used to actually create the
11107330f729Sjoerg   // module.  Since we're sharing an in-memory module cache,
11117330f729Sjoerg   // CompilerInstance::CompilerInstance is responsible for finalizing the
11127330f729Sjoerg   // buffers to prevent use-after-frees.
11137330f729Sjoerg   CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
11147330f729Sjoerg                             &ImportingInstance.getModuleCache());
11157330f729Sjoerg   auto &Inv = *Invocation;
11167330f729Sjoerg   Instance.setInvocation(std::move(Invocation));
11177330f729Sjoerg 
11187330f729Sjoerg   Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
11197330f729Sjoerg                                    ImportingInstance.getDiagnosticClient()),
11207330f729Sjoerg                              /*ShouldOwnClient=*/true);
11217330f729Sjoerg 
11227330f729Sjoerg   // Note that this module is part of the module build stack, so that we
11237330f729Sjoerg   // can detect cycles in the module graph.
11247330f729Sjoerg   Instance.setFileManager(&ImportingInstance.getFileManager());
11257330f729Sjoerg   Instance.createSourceManager(Instance.getFileManager());
11267330f729Sjoerg   SourceManager &SourceMgr = Instance.getSourceManager();
11277330f729Sjoerg   SourceMgr.setModuleBuildStack(
11287330f729Sjoerg     ImportingInstance.getSourceManager().getModuleBuildStack());
11297330f729Sjoerg   SourceMgr.pushModuleBuildStack(ModuleName,
11307330f729Sjoerg     FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
11317330f729Sjoerg 
11327330f729Sjoerg   // If we're collecting module dependencies, we need to share a collector
11337330f729Sjoerg   // between all of the module CompilerInstances. Other than that, we don't
11347330f729Sjoerg   // want to produce any dependency output from the module build.
11357330f729Sjoerg   Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
11367330f729Sjoerg   Inv.getDependencyOutputOpts() = DependencyOutputOptions();
11377330f729Sjoerg 
11387330f729Sjoerg   ImportingInstance.getDiagnostics().Report(ImportLoc,
11397330f729Sjoerg                                             diag::remark_module_build)
11407330f729Sjoerg     << ModuleName << ModuleFileName;
11417330f729Sjoerg 
11427330f729Sjoerg   PreBuildStep(Instance);
11437330f729Sjoerg 
11447330f729Sjoerg   // Execute the action to actually build the module in-place. Use a separate
11457330f729Sjoerg   // thread so that we get a stack large enough.
11467330f729Sjoerg   llvm::CrashRecoveryContext CRC;
11477330f729Sjoerg   CRC.RunSafelyOnThread(
__anon502c5ec40402() 11487330f729Sjoerg       [&]() {
11497330f729Sjoerg         GenerateModuleFromModuleMapAction Action;
11507330f729Sjoerg         Instance.ExecuteAction(Action);
11517330f729Sjoerg       },
11527330f729Sjoerg       DesiredStackSize);
11537330f729Sjoerg 
11547330f729Sjoerg   PostBuildStep(Instance);
11557330f729Sjoerg 
11567330f729Sjoerg   ImportingInstance.getDiagnostics().Report(ImportLoc,
11577330f729Sjoerg                                             diag::remark_module_build_done)
11587330f729Sjoerg     << ModuleName;
11597330f729Sjoerg 
1160*e038c9c4Sjoerg   // Delete any remaining temporary files related to Instance, in case the
1161*e038c9c4Sjoerg   // module generation thread crashed.
11627330f729Sjoerg   Instance.clearOutputFiles(/*EraseFiles=*/true);
11637330f729Sjoerg 
1164*e038c9c4Sjoerg   // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1165*e038c9c4Sjoerg   // occurred.
1166*e038c9c4Sjoerg   return !Instance.getDiagnostics().hasErrorOccurred() ||
1167*e038c9c4Sjoerg          Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
11687330f729Sjoerg }
11697330f729Sjoerg 
getPublicModuleMap(const FileEntry * File,FileManager & FileMgr)11707330f729Sjoerg static const FileEntry *getPublicModuleMap(const FileEntry *File,
11717330f729Sjoerg                                            FileManager &FileMgr) {
11727330f729Sjoerg   StringRef Filename = llvm::sys::path::filename(File->getName());
11737330f729Sjoerg   SmallString<128> PublicFilename(File->getDir()->getName());
11747330f729Sjoerg   if (Filename == "module_private.map")
11757330f729Sjoerg     llvm::sys::path::append(PublicFilename, "module.map");
11767330f729Sjoerg   else if (Filename == "module.private.modulemap")
11777330f729Sjoerg     llvm::sys::path::append(PublicFilename, "module.modulemap");
11787330f729Sjoerg   else
11797330f729Sjoerg     return nullptr;
11807330f729Sjoerg   if (auto FE = FileMgr.getFile(PublicFilename))
11817330f729Sjoerg     return *FE;
11827330f729Sjoerg   return nullptr;
11837330f729Sjoerg }
11847330f729Sjoerg 
1185*e038c9c4Sjoerg /// Compile a module file for the given module in a separate compiler instance,
1186*e038c9c4Sjoerg /// using the options provided by the importing compiler instance. Returns true
1187*e038c9c4Sjoerg /// if the module was built without errors.
compileModule(CompilerInstance & ImportingInstance,SourceLocation ImportLoc,Module * Module,StringRef ModuleFileName)1188*e038c9c4Sjoerg static bool compileModule(CompilerInstance &ImportingInstance,
1189*e038c9c4Sjoerg                           SourceLocation ImportLoc, Module *Module,
11907330f729Sjoerg                           StringRef ModuleFileName) {
11917330f729Sjoerg   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
11927330f729Sjoerg                InputKind::ModuleMap);
11937330f729Sjoerg 
11947330f729Sjoerg   // Get or create the module map that we'll use to build this module.
11957330f729Sjoerg   ModuleMap &ModMap
11967330f729Sjoerg     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
11977330f729Sjoerg   bool Result;
11987330f729Sjoerg   if (const FileEntry *ModuleMapFile =
11997330f729Sjoerg           ModMap.getContainingModuleMapFile(Module)) {
12007330f729Sjoerg     // Canonicalize compilation to start with the public module map. This is
12017330f729Sjoerg     // vital for submodules declarations in the private module maps to be
12027330f729Sjoerg     // correctly parsed when depending on a top level module in the public one.
12037330f729Sjoerg     if (const FileEntry *PublicMMFile = getPublicModuleMap(
12047330f729Sjoerg             ModuleMapFile, ImportingInstance.getFileManager()))
12057330f729Sjoerg       ModuleMapFile = PublicMMFile;
12067330f729Sjoerg 
12077330f729Sjoerg     // Use the module map where this module resides.
12087330f729Sjoerg     Result = compileModuleImpl(
12097330f729Sjoerg         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
12107330f729Sjoerg         FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
12117330f729Sjoerg         ModMap.getModuleMapFileForUniquing(Module)->getName(),
12127330f729Sjoerg         ModuleFileName);
12137330f729Sjoerg   } else {
12147330f729Sjoerg     // FIXME: We only need to fake up an input file here as a way of
12157330f729Sjoerg     // transporting the module's directory to the module map parser. We should
12167330f729Sjoerg     // be able to do that more directly, and parse from a memory buffer without
12177330f729Sjoerg     // inventing this file.
12187330f729Sjoerg     SmallString<128> FakeModuleMapFile(Module->Directory->getName());
12197330f729Sjoerg     llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
12207330f729Sjoerg 
12217330f729Sjoerg     std::string InferredModuleMapContent;
12227330f729Sjoerg     llvm::raw_string_ostream OS(InferredModuleMapContent);
12237330f729Sjoerg     Module->print(OS);
12247330f729Sjoerg     OS.flush();
12257330f729Sjoerg 
12267330f729Sjoerg     Result = compileModuleImpl(
12277330f729Sjoerg         ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
12287330f729Sjoerg         FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
12297330f729Sjoerg         ModMap.getModuleMapFileForUniquing(Module)->getName(),
12307330f729Sjoerg         ModuleFileName,
12317330f729Sjoerg         [&](CompilerInstance &Instance) {
12327330f729Sjoerg       std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
12337330f729Sjoerg           llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
12347330f729Sjoerg       ModuleMapFile = Instance.getFileManager().getVirtualFile(
12357330f729Sjoerg           FakeModuleMapFile, InferredModuleMapContent.size(), 0);
12367330f729Sjoerg       Instance.getSourceManager().overrideFileContents(
12377330f729Sjoerg           ModuleMapFile, std::move(ModuleMapBuffer));
12387330f729Sjoerg     });
12397330f729Sjoerg   }
12407330f729Sjoerg 
12417330f729Sjoerg   // We've rebuilt a module. If we're allowed to generate or update the global
12427330f729Sjoerg   // module index, record that fact in the importing compiler instance.
12437330f729Sjoerg   if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
12447330f729Sjoerg     ImportingInstance.setBuildGlobalModuleIndex(true);
12457330f729Sjoerg   }
12467330f729Sjoerg 
12477330f729Sjoerg   return Result;
12487330f729Sjoerg }
12497330f729Sjoerg 
1250*e038c9c4Sjoerg /// Compile a module in a separate compiler instance and read the AST,
1251*e038c9c4Sjoerg /// returning true if the module compiles without errors.
1252*e038c9c4Sjoerg ///
1253*e038c9c4Sjoerg /// Uses a lock file manager and exponential backoff to reduce the chances that
1254*e038c9c4Sjoerg /// multiple instances will compete to create the same module.  On timeout,
1255*e038c9c4Sjoerg /// deletes the lock file in order to avoid deadlock from crashing processes or
1256*e038c9c4Sjoerg /// bugs in the lock file manager.
compileModuleAndReadAST(CompilerInstance & ImportingInstance,SourceLocation ImportLoc,SourceLocation ModuleNameLoc,Module * Module,StringRef ModuleFileName)1257*e038c9c4Sjoerg static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
12587330f729Sjoerg                                     SourceLocation ImportLoc,
1259*e038c9c4Sjoerg                                     SourceLocation ModuleNameLoc,
1260*e038c9c4Sjoerg                                     Module *Module, StringRef ModuleFileName) {
12617330f729Sjoerg   DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
12627330f729Sjoerg 
12637330f729Sjoerg   auto diagnoseBuildFailure = [&] {
12647330f729Sjoerg     Diags.Report(ModuleNameLoc, diag::err_module_not_built)
12657330f729Sjoerg         << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
12667330f729Sjoerg   };
12677330f729Sjoerg 
12687330f729Sjoerg   // FIXME: have LockFileManager return an error_code so that we can
12697330f729Sjoerg   // avoid the mkdir when the directory already exists.
12707330f729Sjoerg   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
12717330f729Sjoerg   llvm::sys::fs::create_directories(Dir);
12727330f729Sjoerg 
12737330f729Sjoerg   while (1) {
12747330f729Sjoerg     unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
12757330f729Sjoerg     llvm::LockFileManager Locked(ModuleFileName);
12767330f729Sjoerg     switch (Locked) {
12777330f729Sjoerg     case llvm::LockFileManager::LFS_Error:
12787330f729Sjoerg       // ModuleCache takes care of correctness and locks are only necessary for
12797330f729Sjoerg       // performance. Fallback to building the module in case of any lock
12807330f729Sjoerg       // related errors.
12817330f729Sjoerg       Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
12827330f729Sjoerg           << Module->Name << Locked.getErrorMessage();
12837330f729Sjoerg       // Clear out any potential leftover.
12847330f729Sjoerg       Locked.unsafeRemoveLockFile();
12857330f729Sjoerg       LLVM_FALLTHROUGH;
12867330f729Sjoerg     case llvm::LockFileManager::LFS_Owned:
12877330f729Sjoerg       // We're responsible for building the module ourselves.
1288*e038c9c4Sjoerg       if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
12897330f729Sjoerg                          ModuleFileName)) {
12907330f729Sjoerg         diagnoseBuildFailure();
12917330f729Sjoerg         return false;
12927330f729Sjoerg       }
12937330f729Sjoerg       break;
12947330f729Sjoerg 
12957330f729Sjoerg     case llvm::LockFileManager::LFS_Shared:
12967330f729Sjoerg       // Someone else is responsible for building the module. Wait for them to
12977330f729Sjoerg       // finish.
12987330f729Sjoerg       switch (Locked.waitForUnlock()) {
12997330f729Sjoerg       case llvm::LockFileManager::Res_Success:
13007330f729Sjoerg         ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
13017330f729Sjoerg         break;
13027330f729Sjoerg       case llvm::LockFileManager::Res_OwnerDied:
13037330f729Sjoerg         continue; // try again to get the lock.
13047330f729Sjoerg       case llvm::LockFileManager::Res_Timeout:
13057330f729Sjoerg         // Since ModuleCache takes care of correctness, we try waiting for
13067330f729Sjoerg         // another process to complete the build so clang does not do it done
13077330f729Sjoerg         // twice. If case of timeout, build it ourselves.
13087330f729Sjoerg         Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
13097330f729Sjoerg             << Module->Name;
13107330f729Sjoerg         // Clear the lock file so that future invocations can make progress.
13117330f729Sjoerg         Locked.unsafeRemoveLockFile();
13127330f729Sjoerg         continue;
13137330f729Sjoerg       }
13147330f729Sjoerg       break;
13157330f729Sjoerg     }
13167330f729Sjoerg 
13177330f729Sjoerg     // Try to read the module file, now that we've compiled it.
13187330f729Sjoerg     ASTReader::ASTReadResult ReadResult =
1319*e038c9c4Sjoerg         ImportingInstance.getASTReader()->ReadAST(
13207330f729Sjoerg             ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
13217330f729Sjoerg             ModuleLoadCapabilities);
13227330f729Sjoerg 
13237330f729Sjoerg     if (ReadResult == ASTReader::OutOfDate &&
13247330f729Sjoerg         Locked == llvm::LockFileManager::LFS_Shared) {
13257330f729Sjoerg       // The module may be out of date in the presence of file system races,
13267330f729Sjoerg       // or if one of its imports depends on header search paths that are not
13277330f729Sjoerg       // consistent with this ImportingInstance.  Try again...
13287330f729Sjoerg       continue;
13297330f729Sjoerg     } else if (ReadResult == ASTReader::Missing) {
13307330f729Sjoerg       diagnoseBuildFailure();
13317330f729Sjoerg     } else if (ReadResult != ASTReader::Success &&
13327330f729Sjoerg                !Diags.hasErrorOccurred()) {
13337330f729Sjoerg       // The ASTReader didn't diagnose the error, so conservatively report it.
13347330f729Sjoerg       diagnoseBuildFailure();
13357330f729Sjoerg     }
13367330f729Sjoerg     return ReadResult == ASTReader::Success;
13377330f729Sjoerg   }
13387330f729Sjoerg }
13397330f729Sjoerg 
13407330f729Sjoerg /// Diagnose differences between the current definition of the given
13417330f729Sjoerg /// configuration macro and the definition provided on the command line.
checkConfigMacro(Preprocessor & PP,StringRef ConfigMacro,Module * Mod,SourceLocation ImportLoc)13427330f729Sjoerg static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
13437330f729Sjoerg                              Module *Mod, SourceLocation ImportLoc) {
13447330f729Sjoerg   IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
13457330f729Sjoerg   SourceManager &SourceMgr = PP.getSourceManager();
13467330f729Sjoerg 
13477330f729Sjoerg   // If this identifier has never had a macro definition, then it could
13487330f729Sjoerg   // not have changed.
13497330f729Sjoerg   if (!Id->hadMacroDefinition())
13507330f729Sjoerg     return;
13517330f729Sjoerg   auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
13527330f729Sjoerg 
13537330f729Sjoerg   // Find the macro definition from the command line.
13547330f729Sjoerg   MacroInfo *CmdLineDefinition = nullptr;
13557330f729Sjoerg   for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
13567330f729Sjoerg     // We only care about the predefines buffer.
13577330f729Sjoerg     FileID FID = SourceMgr.getFileID(MD->getLocation());
13587330f729Sjoerg     if (FID.isInvalid() || FID != PP.getPredefinesFileID())
13597330f729Sjoerg       continue;
13607330f729Sjoerg     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
13617330f729Sjoerg       CmdLineDefinition = DMD->getMacroInfo();
13627330f729Sjoerg     break;
13637330f729Sjoerg   }
13647330f729Sjoerg 
13657330f729Sjoerg   auto *CurrentDefinition = PP.getMacroInfo(Id);
13667330f729Sjoerg   if (CurrentDefinition == CmdLineDefinition) {
13677330f729Sjoerg     // Macro matches. Nothing to do.
13687330f729Sjoerg   } else if (!CurrentDefinition) {
13697330f729Sjoerg     // This macro was defined on the command line, then #undef'd later.
13707330f729Sjoerg     // Complain.
13717330f729Sjoerg     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
13727330f729Sjoerg       << true << ConfigMacro << Mod->getFullModuleName();
13737330f729Sjoerg     auto LatestDef = LatestLocalMD->getDefinition();
13747330f729Sjoerg     assert(LatestDef.isUndefined() &&
13757330f729Sjoerg            "predefined macro went away with no #undef?");
13767330f729Sjoerg     PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
13777330f729Sjoerg       << true;
13787330f729Sjoerg     return;
13797330f729Sjoerg   } else if (!CmdLineDefinition) {
13807330f729Sjoerg     // There was no definition for this macro in the predefines buffer,
13817330f729Sjoerg     // but there was a local definition. Complain.
13827330f729Sjoerg     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
13837330f729Sjoerg       << false << ConfigMacro << Mod->getFullModuleName();
13847330f729Sjoerg     PP.Diag(CurrentDefinition->getDefinitionLoc(),
13857330f729Sjoerg             diag::note_module_def_undef_here)
13867330f729Sjoerg       << false;
13877330f729Sjoerg   } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
13887330f729Sjoerg                                                /*Syntactically=*/true)) {
13897330f729Sjoerg     // The macro definitions differ.
13907330f729Sjoerg     PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
13917330f729Sjoerg       << false << ConfigMacro << Mod->getFullModuleName();
13927330f729Sjoerg     PP.Diag(CurrentDefinition->getDefinitionLoc(),
13937330f729Sjoerg             diag::note_module_def_undef_here)
13947330f729Sjoerg       << false;
13957330f729Sjoerg   }
13967330f729Sjoerg }
13977330f729Sjoerg 
13987330f729Sjoerg /// Write a new timestamp file with the given path.
writeTimestampFile(StringRef TimestampFile)13997330f729Sjoerg static void writeTimestampFile(StringRef TimestampFile) {
14007330f729Sjoerg   std::error_code EC;
14017330f729Sjoerg   llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
14027330f729Sjoerg }
14037330f729Sjoerg 
14047330f729Sjoerg /// Prune the module cache of modules that haven't been accessed in
14057330f729Sjoerg /// a long time.
pruneModuleCache(const HeaderSearchOptions & HSOpts)14067330f729Sjoerg static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
14077330f729Sjoerg   llvm::sys::fs::file_status StatBuf;
14087330f729Sjoerg   llvm::SmallString<128> TimestampFile;
14097330f729Sjoerg   TimestampFile = HSOpts.ModuleCachePath;
14107330f729Sjoerg   assert(!TimestampFile.empty());
14117330f729Sjoerg   llvm::sys::path::append(TimestampFile, "modules.timestamp");
14127330f729Sjoerg 
14137330f729Sjoerg   // Try to stat() the timestamp file.
14147330f729Sjoerg   if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
14157330f729Sjoerg     // If the timestamp file wasn't there, create one now.
14167330f729Sjoerg     if (EC == std::errc::no_such_file_or_directory) {
14177330f729Sjoerg       writeTimestampFile(TimestampFile);
14187330f729Sjoerg     }
14197330f729Sjoerg     return;
14207330f729Sjoerg   }
14217330f729Sjoerg 
14227330f729Sjoerg   // Check whether the time stamp is older than our pruning interval.
14237330f729Sjoerg   // If not, do nothing.
14247330f729Sjoerg   time_t TimeStampModTime =
14257330f729Sjoerg       llvm::sys::toTimeT(StatBuf.getLastModificationTime());
14267330f729Sjoerg   time_t CurrentTime = time(nullptr);
14277330f729Sjoerg   if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
14287330f729Sjoerg     return;
14297330f729Sjoerg 
14307330f729Sjoerg   // Write a new timestamp file so that nobody else attempts to prune.
14317330f729Sjoerg   // There is a benign race condition here, if two Clang instances happen to
14327330f729Sjoerg   // notice at the same time that the timestamp is out-of-date.
14337330f729Sjoerg   writeTimestampFile(TimestampFile);
14347330f729Sjoerg 
14357330f729Sjoerg   // Walk the entire module cache, looking for unused module files and module
14367330f729Sjoerg   // indices.
14377330f729Sjoerg   std::error_code EC;
14387330f729Sjoerg   SmallString<128> ModuleCachePathNative;
14397330f729Sjoerg   llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
14407330f729Sjoerg   for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
14417330f729Sjoerg        Dir != DirEnd && !EC; Dir.increment(EC)) {
14427330f729Sjoerg     // If we don't have a directory, there's nothing to look into.
14437330f729Sjoerg     if (!llvm::sys::fs::is_directory(Dir->path()))
14447330f729Sjoerg       continue;
14457330f729Sjoerg 
14467330f729Sjoerg     // Walk all of the files within this directory.
14477330f729Sjoerg     for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
14487330f729Sjoerg          File != FileEnd && !EC; File.increment(EC)) {
14497330f729Sjoerg       // We only care about module and global module index files.
14507330f729Sjoerg       StringRef Extension = llvm::sys::path::extension(File->path());
14517330f729Sjoerg       if (Extension != ".pcm" && Extension != ".timestamp" &&
14527330f729Sjoerg           llvm::sys::path::filename(File->path()) != "modules.idx")
14537330f729Sjoerg         continue;
14547330f729Sjoerg 
14557330f729Sjoerg       // Look at this file. If we can't stat it, there's nothing interesting
14567330f729Sjoerg       // there.
14577330f729Sjoerg       if (llvm::sys::fs::status(File->path(), StatBuf))
14587330f729Sjoerg         continue;
14597330f729Sjoerg 
14607330f729Sjoerg       // If the file has been used recently enough, leave it there.
14617330f729Sjoerg       time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
14627330f729Sjoerg       if (CurrentTime - FileAccessTime <=
14637330f729Sjoerg               time_t(HSOpts.ModuleCachePruneAfter)) {
14647330f729Sjoerg         continue;
14657330f729Sjoerg       }
14667330f729Sjoerg 
14677330f729Sjoerg       // Remove the file.
14687330f729Sjoerg       llvm::sys::fs::remove(File->path());
14697330f729Sjoerg 
14707330f729Sjoerg       // Remove the timestamp file.
14717330f729Sjoerg       std::string TimpestampFilename = File->path() + ".timestamp";
14727330f729Sjoerg       llvm::sys::fs::remove(TimpestampFilename);
14737330f729Sjoerg     }
14747330f729Sjoerg 
14757330f729Sjoerg     // If we removed all of the files in the directory, remove the directory
14767330f729Sjoerg     // itself.
14777330f729Sjoerg     if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
14787330f729Sjoerg             llvm::sys::fs::directory_iterator() && !EC)
14797330f729Sjoerg       llvm::sys::fs::remove(Dir->path());
14807330f729Sjoerg   }
14817330f729Sjoerg }
14827330f729Sjoerg 
createASTReader()1483*e038c9c4Sjoerg void CompilerInstance::createASTReader() {
1484*e038c9c4Sjoerg   if (TheASTReader)
1485*e038c9c4Sjoerg     return;
1486*e038c9c4Sjoerg 
14877330f729Sjoerg   if (!hasASTContext())
14887330f729Sjoerg     createASTContext();
14897330f729Sjoerg 
14907330f729Sjoerg   // If we're implicitly building modules but not currently recursively
14917330f729Sjoerg   // building a module, check whether we need to prune the module cache.
14927330f729Sjoerg   if (getSourceManager().getModuleBuildStack().empty() &&
14937330f729Sjoerg       !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
14947330f729Sjoerg       getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
14957330f729Sjoerg       getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
14967330f729Sjoerg     pruneModuleCache(getHeaderSearchOpts());
14977330f729Sjoerg   }
14987330f729Sjoerg 
14997330f729Sjoerg   HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
15007330f729Sjoerg   std::string Sysroot = HSOpts.Sysroot;
15017330f729Sjoerg   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1502*e038c9c4Sjoerg   const FrontendOptions &FEOpts = getFrontendOpts();
15037330f729Sjoerg   std::unique_ptr<llvm::Timer> ReadTimer;
1504*e038c9c4Sjoerg 
15057330f729Sjoerg   if (FrontendTimerGroup)
15067330f729Sjoerg     ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
15077330f729Sjoerg                                                 "Reading modules",
15087330f729Sjoerg                                                 *FrontendTimerGroup);
1509*e038c9c4Sjoerg   TheASTReader = new ASTReader(
15107330f729Sjoerg       getPreprocessor(), getModuleCache(), &getASTContext(),
15117330f729Sjoerg       getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
1512*e038c9c4Sjoerg       Sysroot.empty() ? "" : Sysroot.c_str(),
1513*e038c9c4Sjoerg       PPOpts.DisablePCHOrModuleValidation,
1514*e038c9c4Sjoerg       /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1515*e038c9c4Sjoerg       /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
15167330f729Sjoerg       HSOpts.ValidateASTInputFilesContent,
15177330f729Sjoerg       getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
15187330f729Sjoerg   if (hasASTConsumer()) {
1519*e038c9c4Sjoerg     TheASTReader->setDeserializationListener(
15207330f729Sjoerg         getASTConsumer().GetASTDeserializationListener());
15217330f729Sjoerg     getASTContext().setASTMutationListener(
15227330f729Sjoerg       getASTConsumer().GetASTMutationListener());
15237330f729Sjoerg   }
1524*e038c9c4Sjoerg   getASTContext().setExternalSource(TheASTReader);
15257330f729Sjoerg   if (hasSema())
1526*e038c9c4Sjoerg     TheASTReader->InitializeSema(getSema());
15277330f729Sjoerg   if (hasASTConsumer())
1528*e038c9c4Sjoerg     TheASTReader->StartTranslationUnit(&getASTConsumer());
15297330f729Sjoerg 
15307330f729Sjoerg   for (auto &Listener : DependencyCollectors)
1531*e038c9c4Sjoerg     Listener->attachToASTReader(*TheASTReader);
15327330f729Sjoerg }
15337330f729Sjoerg 
loadModuleFile(StringRef FileName)15347330f729Sjoerg bool CompilerInstance::loadModuleFile(StringRef FileName) {
15357330f729Sjoerg   llvm::Timer Timer;
15367330f729Sjoerg   if (FrontendTimerGroup)
15377330f729Sjoerg     Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
15387330f729Sjoerg                *FrontendTimerGroup);
15397330f729Sjoerg   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
15407330f729Sjoerg 
15417330f729Sjoerg   // Helper to recursively read the module names for all modules we're adding.
15427330f729Sjoerg   // We mark these as known and redirect any attempt to load that module to
15437330f729Sjoerg   // the files we were handed.
15447330f729Sjoerg   struct ReadModuleNames : ASTReaderListener {
15457330f729Sjoerg     CompilerInstance &CI;
15467330f729Sjoerg     llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
15477330f729Sjoerg 
15487330f729Sjoerg     ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
15497330f729Sjoerg 
15507330f729Sjoerg     void ReadModuleName(StringRef ModuleName) override {
15517330f729Sjoerg       LoadedModules.push_back(
15527330f729Sjoerg           CI.getPreprocessor().getIdentifierInfo(ModuleName));
15537330f729Sjoerg     }
15547330f729Sjoerg 
15557330f729Sjoerg     void registerAll() {
1556*e038c9c4Sjoerg       ModuleMap &MM = CI.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1557*e038c9c4Sjoerg       for (auto *II : LoadedModules)
1558*e038c9c4Sjoerg         MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
15597330f729Sjoerg       LoadedModules.clear();
15607330f729Sjoerg     }
15617330f729Sjoerg 
15627330f729Sjoerg     void markAllUnavailable() {
15637330f729Sjoerg       for (auto *II : LoadedModules) {
15647330f729Sjoerg         if (Module *M = CI.getPreprocessor()
15657330f729Sjoerg                             .getHeaderSearchInfo()
15667330f729Sjoerg                             .getModuleMap()
15677330f729Sjoerg                             .findModule(II->getName())) {
15687330f729Sjoerg           M->HasIncompatibleModuleFile = true;
15697330f729Sjoerg 
15707330f729Sjoerg           // Mark module as available if the only reason it was unavailable
15717330f729Sjoerg           // was missing headers.
15727330f729Sjoerg           SmallVector<Module *, 2> Stack;
15737330f729Sjoerg           Stack.push_back(M);
15747330f729Sjoerg           while (!Stack.empty()) {
15757330f729Sjoerg             Module *Current = Stack.pop_back_val();
1576*e038c9c4Sjoerg             if (Current->IsUnimportable) continue;
15777330f729Sjoerg             Current->IsAvailable = true;
15787330f729Sjoerg             Stack.insert(Stack.end(),
15797330f729Sjoerg                          Current->submodule_begin(), Current->submodule_end());
15807330f729Sjoerg           }
15817330f729Sjoerg         }
15827330f729Sjoerg       }
15837330f729Sjoerg       LoadedModules.clear();
15847330f729Sjoerg     }
15857330f729Sjoerg   };
15867330f729Sjoerg 
15877330f729Sjoerg   // If we don't already have an ASTReader, create one now.
1588*e038c9c4Sjoerg   if (!TheASTReader)
1589*e038c9c4Sjoerg     createASTReader();
15907330f729Sjoerg 
15917330f729Sjoerg   // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
15927330f729Sjoerg   // ASTReader to diagnose it, since it can produce better errors that we can.
15937330f729Sjoerg   bool ConfigMismatchIsRecoverable =
15947330f729Sjoerg       getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
15957330f729Sjoerg                                           SourceLocation())
15967330f729Sjoerg         <= DiagnosticsEngine::Warning;
15977330f729Sjoerg 
15987330f729Sjoerg   auto Listener = std::make_unique<ReadModuleNames>(*this);
15997330f729Sjoerg   auto &ListenerRef = *Listener;
1600*e038c9c4Sjoerg   ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
16017330f729Sjoerg                                                    std::move(Listener));
16027330f729Sjoerg 
16037330f729Sjoerg   // Try to load the module file.
1604*e038c9c4Sjoerg   switch (TheASTReader->ReadAST(
16057330f729Sjoerg       FileName, serialization::MK_ExplicitModule, SourceLocation(),
16067330f729Sjoerg       ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
16077330f729Sjoerg   case ASTReader::Success:
16087330f729Sjoerg     // We successfully loaded the module file; remember the set of provided
16097330f729Sjoerg     // modules so that we don't try to load implicit modules for them.
16107330f729Sjoerg     ListenerRef.registerAll();
16117330f729Sjoerg     return true;
16127330f729Sjoerg 
16137330f729Sjoerg   case ASTReader::ConfigurationMismatch:
16147330f729Sjoerg     // Ignore unusable module files.
16157330f729Sjoerg     getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
16167330f729Sjoerg         << FileName;
16177330f729Sjoerg     // All modules provided by any files we tried and failed to load are now
16187330f729Sjoerg     // unavailable; includes of those modules should now be handled textually.
16197330f729Sjoerg     ListenerRef.markAllUnavailable();
16207330f729Sjoerg     return true;
16217330f729Sjoerg 
16227330f729Sjoerg   default:
16237330f729Sjoerg     return false;
16247330f729Sjoerg   }
16257330f729Sjoerg }
16267330f729Sjoerg 
1627*e038c9c4Sjoerg namespace {
16287330f729Sjoerg enum ModuleSource {
1629*e038c9c4Sjoerg   MS_ModuleNotFound,
1630*e038c9c4Sjoerg   MS_ModuleCache,
1631*e038c9c4Sjoerg   MS_PrebuiltModulePath,
1632*e038c9c4Sjoerg   MS_ModuleBuildPragma
1633*e038c9c4Sjoerg };
1634*e038c9c4Sjoerg } // end namespace
1635*e038c9c4Sjoerg 
1636*e038c9c4Sjoerg /// Select a source for loading the named module and compute the filename to
1637*e038c9c4Sjoerg /// load it from.
selectModuleSource(Module * M,StringRef ModuleName,std::string & ModuleFilename,const std::map<std::string,std::string,std::less<>> & BuiltModules,HeaderSearch & HS)1638*e038c9c4Sjoerg static ModuleSource selectModuleSource(
1639*e038c9c4Sjoerg     Module *M, StringRef ModuleName, std::string &ModuleFilename,
1640*e038c9c4Sjoerg     const std::map<std::string, std::string, std::less<>> &BuiltModules,
1641*e038c9c4Sjoerg     HeaderSearch &HS) {
1642*e038c9c4Sjoerg   assert(ModuleFilename.empty() && "Already has a module source?");
16437330f729Sjoerg 
16447330f729Sjoerg   // Check to see if the module has been built as part of this compilation
16457330f729Sjoerg   // via a module build pragma.
16467330f729Sjoerg   auto BuiltModuleIt = BuiltModules.find(ModuleName);
16477330f729Sjoerg   if (BuiltModuleIt != BuiltModules.end()) {
1648*e038c9c4Sjoerg     ModuleFilename = BuiltModuleIt->second;
1649*e038c9c4Sjoerg     return MS_ModuleBuildPragma;
16507330f729Sjoerg   }
16517330f729Sjoerg 
16527330f729Sjoerg   // Try to load the module from the prebuilt module path.
1653*e038c9c4Sjoerg   const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1654*e038c9c4Sjoerg   if (!HSOpts.PrebuiltModuleFiles.empty() ||
1655*e038c9c4Sjoerg       !HSOpts.PrebuiltModulePaths.empty()) {
1656*e038c9c4Sjoerg     ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1657*e038c9c4Sjoerg     if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1658*e038c9c4Sjoerg       ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1659*e038c9c4Sjoerg     if (!ModuleFilename.empty())
1660*e038c9c4Sjoerg       return MS_PrebuiltModulePath;
16617330f729Sjoerg   }
16627330f729Sjoerg 
16637330f729Sjoerg   // Try to load the module from the module cache.
1664*e038c9c4Sjoerg   if (M) {
1665*e038c9c4Sjoerg     ModuleFilename = HS.getCachedModuleFileName(M);
1666*e038c9c4Sjoerg     return MS_ModuleCache;
16677330f729Sjoerg   }
16687330f729Sjoerg 
1669*e038c9c4Sjoerg   return MS_ModuleNotFound;
1670*e038c9c4Sjoerg }
1671*e038c9c4Sjoerg 
findOrCompileModuleAndReadAST(StringRef ModuleName,SourceLocation ImportLoc,SourceLocation ModuleNameLoc,bool IsInclusionDirective)1672*e038c9c4Sjoerg ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1673*e038c9c4Sjoerg     StringRef ModuleName, SourceLocation ImportLoc,
1674*e038c9c4Sjoerg     SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
1675*e038c9c4Sjoerg   // Search for a module with the given name.
1676*e038c9c4Sjoerg   HeaderSearch &HS = PP->getHeaderSearchInfo();
1677*e038c9c4Sjoerg   Module *M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1678*e038c9c4Sjoerg 
1679*e038c9c4Sjoerg   // Select the source and filename for loading the named module.
1680*e038c9c4Sjoerg   std::string ModuleFilename;
1681*e038c9c4Sjoerg   ModuleSource Source =
1682*e038c9c4Sjoerg       selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1683*e038c9c4Sjoerg   if (Source == MS_ModuleNotFound) {
16847330f729Sjoerg     // We can't find a module, error out here.
16857330f729Sjoerg     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
16867330f729Sjoerg         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1687*e038c9c4Sjoerg     return nullptr;
16887330f729Sjoerg   }
1689*e038c9c4Sjoerg   if (ModuleFilename.empty()) {
1690*e038c9c4Sjoerg     if (M && M->HasIncompatibleModuleFile) {
16917330f729Sjoerg       // We tried and failed to load a module file for this module. Fall
16927330f729Sjoerg       // back to textual inclusion for its headers.
16937330f729Sjoerg       return ModuleLoadResult::ConfigMismatch;
16947330f729Sjoerg     }
16957330f729Sjoerg 
16967330f729Sjoerg     getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
16977330f729Sjoerg         << ModuleName;
1698*e038c9c4Sjoerg     return nullptr;
16997330f729Sjoerg   }
17007330f729Sjoerg 
1701*e038c9c4Sjoerg   // Create an ASTReader on demand.
1702*e038c9c4Sjoerg   if (!getASTReader())
1703*e038c9c4Sjoerg     createASTReader();
17047330f729Sjoerg 
1705*e038c9c4Sjoerg   // Time how long it takes to load the module.
17067330f729Sjoerg   llvm::Timer Timer;
17077330f729Sjoerg   if (FrontendTimerGroup)
1708*e038c9c4Sjoerg     Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
17097330f729Sjoerg                *FrontendTimerGroup);
17107330f729Sjoerg   llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
17117330f729Sjoerg   llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
17127330f729Sjoerg 
17137330f729Sjoerg   // Try to load the module file. If we are not trying to load from the
17147330f729Sjoerg   // module cache, we don't know how to rebuild modules.
1715*e038c9c4Sjoerg   unsigned ARRFlags = Source == MS_ModuleCache
1716*e038c9c4Sjoerg                           ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1717*e038c9c4Sjoerg                                 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1718*e038c9c4Sjoerg                           : Source == MS_PrebuiltModulePath
1719*e038c9c4Sjoerg                                 ? 0
1720*e038c9c4Sjoerg                                 : ASTReader::ARR_ConfigurationMismatch;
1721*e038c9c4Sjoerg   switch (getASTReader()->ReadAST(ModuleFilename,
1722*e038c9c4Sjoerg                                   Source == MS_PrebuiltModulePath
17237330f729Sjoerg                                       ? serialization::MK_PrebuiltModule
1724*e038c9c4Sjoerg                                       : Source == MS_ModuleBuildPragma
17257330f729Sjoerg                                             ? serialization::MK_ExplicitModule
17267330f729Sjoerg                                             : serialization::MK_ImplicitModule,
17277330f729Sjoerg                                   ImportLoc, ARRFlags)) {
17287330f729Sjoerg   case ASTReader::Success: {
1729*e038c9c4Sjoerg     if (M)
1730*e038c9c4Sjoerg       return M;
1731*e038c9c4Sjoerg     assert(Source != MS_ModuleCache &&
1732*e038c9c4Sjoerg            "missing module, but file loaded from cache");
1733*e038c9c4Sjoerg 
1734*e038c9c4Sjoerg     // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1735*e038c9c4Sjoerg     // until the first call to ReadAST.  Look it up now.
1736*e038c9c4Sjoerg     M = HS.lookupModule(ModuleName, true, !IsInclusionDirective);
1737*e038c9c4Sjoerg 
1738*e038c9c4Sjoerg     // Check whether M refers to the file in the prebuilt module path.
1739*e038c9c4Sjoerg     if (M && M->getASTFile())
1740*e038c9c4Sjoerg       if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
1741*e038c9c4Sjoerg         if (*ModuleFile == M->getASTFile())
1742*e038c9c4Sjoerg           return M;
1743*e038c9c4Sjoerg 
17447330f729Sjoerg     getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
17457330f729Sjoerg         << ModuleName;
17467330f729Sjoerg     return ModuleLoadResult();
17477330f729Sjoerg   }
17487330f729Sjoerg 
17497330f729Sjoerg   case ASTReader::OutOfDate:
1750*e038c9c4Sjoerg   case ASTReader::Missing:
1751*e038c9c4Sjoerg     // The most interesting case.
1752*e038c9c4Sjoerg     break;
1753*e038c9c4Sjoerg 
1754*e038c9c4Sjoerg   case ASTReader::ConfigurationMismatch:
1755*e038c9c4Sjoerg     if (Source == MS_PrebuiltModulePath)
1756*e038c9c4Sjoerg       // FIXME: We shouldn't be setting HadFatalFailure below if we only
1757*e038c9c4Sjoerg       // produce a warning here!
1758*e038c9c4Sjoerg       getDiagnostics().Report(SourceLocation(),
1759*e038c9c4Sjoerg                               diag::warn_module_config_mismatch)
1760*e038c9c4Sjoerg           << ModuleFilename;
1761*e038c9c4Sjoerg     // Fall through to error out.
1762*e038c9c4Sjoerg     LLVM_FALLTHROUGH;
1763*e038c9c4Sjoerg   case ASTReader::VersionMismatch:
1764*e038c9c4Sjoerg   case ASTReader::HadErrors:
1765*e038c9c4Sjoerg     ModuleLoader::HadFatalFailure = true;
1766*e038c9c4Sjoerg     // FIXME: The ASTReader will already have complained, but can we shoehorn
1767*e038c9c4Sjoerg     // that diagnostic information into a more useful form?
1768*e038c9c4Sjoerg     return ModuleLoadResult();
1769*e038c9c4Sjoerg 
1770*e038c9c4Sjoerg   case ASTReader::Failure:
1771*e038c9c4Sjoerg     ModuleLoader::HadFatalFailure = true;
1772*e038c9c4Sjoerg     return ModuleLoadResult();
1773*e038c9c4Sjoerg   }
1774*e038c9c4Sjoerg 
1775*e038c9c4Sjoerg   // ReadAST returned Missing or OutOfDate.
1776*e038c9c4Sjoerg   if (Source != MS_ModuleCache) {
17777330f729Sjoerg     // We don't know the desired configuration for this module and don't
17787330f729Sjoerg     // necessarily even have a module map. Since ReadAST already produces
17797330f729Sjoerg     // diagnostics for these two cases, we simply error out here.
17807330f729Sjoerg     return ModuleLoadResult();
17817330f729Sjoerg   }
17827330f729Sjoerg 
17837330f729Sjoerg   // The module file is missing or out-of-date. Build it.
1784*e038c9c4Sjoerg   assert(M && "missing module, but trying to compile for cache");
1785*e038c9c4Sjoerg 
17867330f729Sjoerg   // Check whether there is a cycle in the module graph.
17877330f729Sjoerg   ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
17887330f729Sjoerg   ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
17897330f729Sjoerg   for (; Pos != PosEnd; ++Pos) {
17907330f729Sjoerg     if (Pos->first == ModuleName)
17917330f729Sjoerg       break;
17927330f729Sjoerg   }
17937330f729Sjoerg 
17947330f729Sjoerg   if (Pos != PosEnd) {
17957330f729Sjoerg     SmallString<256> CyclePath;
17967330f729Sjoerg     for (; Pos != PosEnd; ++Pos) {
17977330f729Sjoerg       CyclePath += Pos->first;
17987330f729Sjoerg       CyclePath += " -> ";
17997330f729Sjoerg     }
18007330f729Sjoerg     CyclePath += ModuleName;
18017330f729Sjoerg 
18027330f729Sjoerg     getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
18037330f729Sjoerg         << ModuleName << CyclePath;
1804*e038c9c4Sjoerg     return nullptr;
18057330f729Sjoerg   }
18067330f729Sjoerg 
18077330f729Sjoerg   // Check whether we have already attempted to build this module (but
18087330f729Sjoerg   // failed).
18097330f729Sjoerg   if (getPreprocessorOpts().FailedModules &&
18107330f729Sjoerg       getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
18117330f729Sjoerg     getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1812*e038c9c4Sjoerg         << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1813*e038c9c4Sjoerg     return nullptr;
18147330f729Sjoerg   }
18157330f729Sjoerg 
1816*e038c9c4Sjoerg   // Try to compile and then read the AST.
1817*e038c9c4Sjoerg   if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1818*e038c9c4Sjoerg                                ModuleFilename)) {
18197330f729Sjoerg     assert(getDiagnostics().hasErrorOccurred() &&
1820*e038c9c4Sjoerg            "undiagnosed error in compileModuleAndReadAST");
18217330f729Sjoerg     if (getPreprocessorOpts().FailedModules)
18227330f729Sjoerg       getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1823*e038c9c4Sjoerg     return nullptr;
18247330f729Sjoerg   }
18257330f729Sjoerg 
18267330f729Sjoerg   // Okay, we've rebuilt and now loaded the module.
1827*e038c9c4Sjoerg   return M;
18287330f729Sjoerg }
18297330f729Sjoerg 
1830*e038c9c4Sjoerg ModuleLoadResult
loadModule(SourceLocation ImportLoc,ModuleIdPath Path,Module::NameVisibilityKind Visibility,bool IsInclusionDirective)1831*e038c9c4Sjoerg CompilerInstance::loadModule(SourceLocation ImportLoc,
1832*e038c9c4Sjoerg                              ModuleIdPath Path,
1833*e038c9c4Sjoerg                              Module::NameVisibilityKind Visibility,
1834*e038c9c4Sjoerg                              bool IsInclusionDirective) {
1835*e038c9c4Sjoerg   // Determine what file we're searching from.
1836*e038c9c4Sjoerg   StringRef ModuleName = Path[0].first->getName();
1837*e038c9c4Sjoerg   SourceLocation ModuleNameLoc = Path[0].second;
18387330f729Sjoerg 
1839*e038c9c4Sjoerg   // If we've already handled this import, just return the cached result.
1840*e038c9c4Sjoerg   // This one-element cache is important to eliminate redundant diagnostics
1841*e038c9c4Sjoerg   // when both the preprocessor and parser see the same import declaration.
1842*e038c9c4Sjoerg   if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1843*e038c9c4Sjoerg     // Make the named module visible.
1844*e038c9c4Sjoerg     if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1845*e038c9c4Sjoerg       TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1846*e038c9c4Sjoerg                                       ImportLoc);
1847*e038c9c4Sjoerg     return LastModuleImportResult;
18487330f729Sjoerg   }
18497330f729Sjoerg 
1850*e038c9c4Sjoerg   // If we don't already have information on this module, load the module now.
1851*e038c9c4Sjoerg   Module *Module = nullptr;
1852*e038c9c4Sjoerg   ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1853*e038c9c4Sjoerg   if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
1854*e038c9c4Sjoerg     // Use the cached result, which may be nullptr.
1855*e038c9c4Sjoerg     Module = *MaybeModule;
1856*e038c9c4Sjoerg   } else if (ModuleName == getLangOpts().CurrentModule) {
1857*e038c9c4Sjoerg     // This is the module we're building.
1858*e038c9c4Sjoerg     Module = PP->getHeaderSearchInfo().lookupModule(
1859*e038c9c4Sjoerg         ModuleName, /*AllowSearch*/ true,
1860*e038c9c4Sjoerg         /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1861*e038c9c4Sjoerg     /// FIXME: perhaps we should (a) look for a module using the module name
1862*e038c9c4Sjoerg     //  to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
1863*e038c9c4Sjoerg     //if (Module == nullptr) {
1864*e038c9c4Sjoerg     //  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1865*e038c9c4Sjoerg     //    << ModuleName;
1866*e038c9c4Sjoerg     //  DisableGeneratingGlobalModuleIndex = true;
1867*e038c9c4Sjoerg     //  return ModuleLoadResult();
1868*e038c9c4Sjoerg     //}
1869*e038c9c4Sjoerg     MM.cacheModuleLoad(*Path[0].first, Module);
1870*e038c9c4Sjoerg   } else {
1871*e038c9c4Sjoerg     ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1872*e038c9c4Sjoerg         ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
1873*e038c9c4Sjoerg     if (!Result.isNormal())
1874*e038c9c4Sjoerg       return Result;
1875*e038c9c4Sjoerg     if (!Result)
1876*e038c9c4Sjoerg       DisableGeneratingGlobalModuleIndex = true;
1877*e038c9c4Sjoerg     Module = Result;
1878*e038c9c4Sjoerg     MM.cacheModuleLoad(*Path[0].first, Module);
18797330f729Sjoerg   }
18807330f729Sjoerg 
1881*e038c9c4Sjoerg   // If we never found the module, fail.  Otherwise, verify the module and link
1882*e038c9c4Sjoerg   // it up.
18837330f729Sjoerg   if (!Module)
18847330f729Sjoerg     return ModuleLoadResult();
18857330f729Sjoerg 
18867330f729Sjoerg   // Verify that the rest of the module path actually corresponds to
18877330f729Sjoerg   // a submodule.
18887330f729Sjoerg   bool MapPrivateSubModToTopLevel = false;
18897330f729Sjoerg   if (Path.size() > 1) {
18907330f729Sjoerg     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
18917330f729Sjoerg       StringRef Name = Path[I].first->getName();
18927330f729Sjoerg       clang::Module *Sub = Module->findSubmodule(Name);
18937330f729Sjoerg 
18947330f729Sjoerg       // If the user is requesting Foo.Private and it doesn't exist, try to
18957330f729Sjoerg       // match Foo_Private and emit a warning asking for the user to write
18967330f729Sjoerg       // @import Foo_Private instead. FIXME: remove this when existing clients
18977330f729Sjoerg       // migrate off of Foo.Private syntax.
18987330f729Sjoerg       if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
18997330f729Sjoerg           Module == Module->getTopLevelModule()) {
19007330f729Sjoerg         SmallString<128> PrivateModule(Module->Name);
19017330f729Sjoerg         PrivateModule.append("_Private");
19027330f729Sjoerg 
19037330f729Sjoerg         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
19047330f729Sjoerg         auto &II = PP->getIdentifierTable().get(
19057330f729Sjoerg             PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
19067330f729Sjoerg         PrivPath.push_back(std::make_pair(&II, Path[0].second));
19077330f729Sjoerg 
19087330f729Sjoerg         if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
19097330f729Sjoerg                                                    !IsInclusionDirective))
19107330f729Sjoerg           Sub =
19117330f729Sjoerg               loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
19127330f729Sjoerg         if (Sub) {
19137330f729Sjoerg           MapPrivateSubModToTopLevel = true;
19147330f729Sjoerg           if (!getDiagnostics().isIgnored(
19157330f729Sjoerg                   diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
19167330f729Sjoerg             getDiagnostics().Report(Path[I].second,
19177330f729Sjoerg                                     diag::warn_no_priv_submodule_use_toplevel)
19187330f729Sjoerg                 << Path[I].first << Module->getFullModuleName() << PrivateModule
19197330f729Sjoerg                 << SourceRange(Path[0].second, Path[I].second)
19207330f729Sjoerg                 << FixItHint::CreateReplacement(SourceRange(Path[0].second),
19217330f729Sjoerg                                                 PrivateModule);
19227330f729Sjoerg             getDiagnostics().Report(Sub->DefinitionLoc,
19237330f729Sjoerg                                     diag::note_private_top_level_defined);
19247330f729Sjoerg           }
19257330f729Sjoerg         }
19267330f729Sjoerg       }
19277330f729Sjoerg 
19287330f729Sjoerg       if (!Sub) {
19297330f729Sjoerg         // Attempt to perform typo correction to find a module name that works.
19307330f729Sjoerg         SmallVector<StringRef, 2> Best;
19317330f729Sjoerg         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
19327330f729Sjoerg 
19337330f729Sjoerg         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
19347330f729Sjoerg                                             JEnd = Module->submodule_end();
19357330f729Sjoerg              J != JEnd; ++J) {
19367330f729Sjoerg           unsigned ED = Name.edit_distance((*J)->Name,
19377330f729Sjoerg                                            /*AllowReplacements=*/true,
19387330f729Sjoerg                                            BestEditDistance);
19397330f729Sjoerg           if (ED <= BestEditDistance) {
19407330f729Sjoerg             if (ED < BestEditDistance) {
19417330f729Sjoerg               Best.clear();
19427330f729Sjoerg               BestEditDistance = ED;
19437330f729Sjoerg             }
19447330f729Sjoerg 
19457330f729Sjoerg             Best.push_back((*J)->Name);
19467330f729Sjoerg           }
19477330f729Sjoerg         }
19487330f729Sjoerg 
19497330f729Sjoerg         // If there was a clear winner, user it.
19507330f729Sjoerg         if (Best.size() == 1) {
19517330f729Sjoerg           getDiagnostics().Report(Path[I].second,
19527330f729Sjoerg                                   diag::err_no_submodule_suggest)
19537330f729Sjoerg             << Path[I].first << Module->getFullModuleName() << Best[0]
19547330f729Sjoerg             << SourceRange(Path[0].second, Path[I-1].second)
19557330f729Sjoerg             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
19567330f729Sjoerg                                             Best[0]);
19577330f729Sjoerg 
19587330f729Sjoerg           Sub = Module->findSubmodule(Best[0]);
19597330f729Sjoerg         }
19607330f729Sjoerg       }
19617330f729Sjoerg 
19627330f729Sjoerg       if (!Sub) {
19637330f729Sjoerg         // No submodule by this name. Complain, and don't look for further
19647330f729Sjoerg         // submodules.
19657330f729Sjoerg         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
19667330f729Sjoerg           << Path[I].first << Module->getFullModuleName()
19677330f729Sjoerg           << SourceRange(Path[0].second, Path[I-1].second);
19687330f729Sjoerg         break;
19697330f729Sjoerg       }
19707330f729Sjoerg 
19717330f729Sjoerg       Module = Sub;
19727330f729Sjoerg     }
19737330f729Sjoerg   }
19747330f729Sjoerg 
19757330f729Sjoerg   // Make the named module visible, if it's not already part of the module
19767330f729Sjoerg   // we are parsing.
19777330f729Sjoerg   if (ModuleName != getLangOpts().CurrentModule) {
19787330f729Sjoerg     if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
19797330f729Sjoerg       // We have an umbrella header or directory that doesn't actually include
19807330f729Sjoerg       // all of the headers within the directory it covers. Complain about
19817330f729Sjoerg       // this missing submodule and recover by forgetting that we ever saw
19827330f729Sjoerg       // this submodule.
19837330f729Sjoerg       // FIXME: Should we detect this at module load time? It seems fairly
19847330f729Sjoerg       // expensive (and rare).
19857330f729Sjoerg       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
19867330f729Sjoerg         << Module->getFullModuleName()
19877330f729Sjoerg         << SourceRange(Path.front().second, Path.back().second);
19887330f729Sjoerg 
19897330f729Sjoerg       return ModuleLoadResult::MissingExpected;
19907330f729Sjoerg     }
19917330f729Sjoerg 
19927330f729Sjoerg     // Check whether this module is available.
19937330f729Sjoerg     if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
19947330f729Sjoerg                                              getDiagnostics(), Module)) {
19957330f729Sjoerg       getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
19967330f729Sjoerg         << SourceRange(Path.front().second, Path.back().second);
19977330f729Sjoerg       LastModuleImportLoc = ImportLoc;
19987330f729Sjoerg       LastModuleImportResult = ModuleLoadResult();
19997330f729Sjoerg       return ModuleLoadResult();
20007330f729Sjoerg     }
20017330f729Sjoerg 
2002*e038c9c4Sjoerg     TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
20037330f729Sjoerg   }
20047330f729Sjoerg 
20057330f729Sjoerg   // Check for any configuration macros that have changed.
20067330f729Sjoerg   clang::Module *TopModule = Module->getTopLevelModule();
20077330f729Sjoerg   for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
20087330f729Sjoerg     checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
20097330f729Sjoerg                      Module, ImportLoc);
20107330f729Sjoerg   }
20117330f729Sjoerg 
20127330f729Sjoerg   // Resolve any remaining module using export_as for this one.
20137330f729Sjoerg   getPreprocessor()
20147330f729Sjoerg       .getHeaderSearchInfo()
20157330f729Sjoerg       .getModuleMap()
20167330f729Sjoerg       .resolveLinkAsDependencies(TopModule);
20177330f729Sjoerg 
20187330f729Sjoerg   LastModuleImportLoc = ImportLoc;
20197330f729Sjoerg   LastModuleImportResult = ModuleLoadResult(Module);
20207330f729Sjoerg   return LastModuleImportResult;
20217330f729Sjoerg }
20227330f729Sjoerg 
createModuleFromSource(SourceLocation ImportLoc,StringRef ModuleName,StringRef Source)2023*e038c9c4Sjoerg void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
20247330f729Sjoerg                                               StringRef ModuleName,
20257330f729Sjoerg                                               StringRef Source) {
20267330f729Sjoerg   // Avoid creating filenames with special characters.
20277330f729Sjoerg   SmallString<128> CleanModuleName(ModuleName);
20287330f729Sjoerg   for (auto &C : CleanModuleName)
20297330f729Sjoerg     if (!isAlphanumeric(C))
20307330f729Sjoerg       C = '_';
20317330f729Sjoerg 
20327330f729Sjoerg   // FIXME: Using a randomized filename here means that our intermediate .pcm
20337330f729Sjoerg   // output is nondeterministic (as .pcm files refer to each other by name).
20347330f729Sjoerg   // Can this affect the output in any way?
20357330f729Sjoerg   SmallString<128> ModuleFileName;
20367330f729Sjoerg   if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
20377330f729Sjoerg           CleanModuleName, "pcm", ModuleFileName)) {
20387330f729Sjoerg     getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
20397330f729Sjoerg         << ModuleFileName << EC.message();
20407330f729Sjoerg     return;
20417330f729Sjoerg   }
20427330f729Sjoerg   std::string ModuleMapFileName = (CleanModuleName + ".map").str();
20437330f729Sjoerg 
20447330f729Sjoerg   FrontendInputFile Input(
20457330f729Sjoerg       ModuleMapFileName,
20467330f729Sjoerg       InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
20477330f729Sjoerg                 InputKind::ModuleMap, /*Preprocessed*/true));
20487330f729Sjoerg 
20497330f729Sjoerg   std::string NullTerminatedSource(Source.str());
20507330f729Sjoerg 
20517330f729Sjoerg   auto PreBuildStep = [&](CompilerInstance &Other) {
20527330f729Sjoerg     // Create a virtual file containing our desired source.
20537330f729Sjoerg     // FIXME: We shouldn't need to do this.
20547330f729Sjoerg     const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
20557330f729Sjoerg         ModuleMapFileName, NullTerminatedSource.size(), 0);
20567330f729Sjoerg     Other.getSourceManager().overrideFileContents(
20577330f729Sjoerg         ModuleMapFile,
20587330f729Sjoerg         llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
20597330f729Sjoerg 
20607330f729Sjoerg     Other.BuiltModules = std::move(BuiltModules);
20617330f729Sjoerg     Other.DeleteBuiltModules = false;
20627330f729Sjoerg   };
20637330f729Sjoerg 
20647330f729Sjoerg   auto PostBuildStep = [this](CompilerInstance &Other) {
20657330f729Sjoerg     BuiltModules = std::move(Other.BuiltModules);
20667330f729Sjoerg   };
20677330f729Sjoerg 
20687330f729Sjoerg   // Build the module, inheriting any modules that we've built locally.
20697330f729Sjoerg   if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
20707330f729Sjoerg                         ModuleFileName, PreBuildStep, PostBuildStep)) {
2071*e038c9c4Sjoerg     BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
20727330f729Sjoerg     llvm::sys::RemoveFileOnSignal(ModuleFileName);
20737330f729Sjoerg   }
20747330f729Sjoerg }
20757330f729Sjoerg 
makeModuleVisible(Module * Mod,Module::NameVisibilityKind Visibility,SourceLocation ImportLoc)20767330f729Sjoerg void CompilerInstance::makeModuleVisible(Module *Mod,
20777330f729Sjoerg                                          Module::NameVisibilityKind Visibility,
20787330f729Sjoerg                                          SourceLocation ImportLoc) {
2079*e038c9c4Sjoerg   if (!TheASTReader)
2080*e038c9c4Sjoerg     createASTReader();
2081*e038c9c4Sjoerg   if (!TheASTReader)
20827330f729Sjoerg     return;
20837330f729Sjoerg 
2084*e038c9c4Sjoerg   TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
20857330f729Sjoerg }
20867330f729Sjoerg 
loadGlobalModuleIndex(SourceLocation TriggerLoc)20877330f729Sjoerg GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
20887330f729Sjoerg     SourceLocation TriggerLoc) {
20897330f729Sjoerg   if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
20907330f729Sjoerg     return nullptr;
2091*e038c9c4Sjoerg   if (!TheASTReader)
2092*e038c9c4Sjoerg     createASTReader();
20937330f729Sjoerg   // Can't do anything if we don't have the module manager.
2094*e038c9c4Sjoerg   if (!TheASTReader)
20957330f729Sjoerg     return nullptr;
20967330f729Sjoerg   // Get an existing global index.  This loads it if not already
20977330f729Sjoerg   // loaded.
2098*e038c9c4Sjoerg   TheASTReader->loadGlobalIndex();
2099*e038c9c4Sjoerg   GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
21007330f729Sjoerg   // If the global index doesn't exist, create it.
21017330f729Sjoerg   if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
21027330f729Sjoerg       hasPreprocessor()) {
21037330f729Sjoerg     llvm::sys::fs::create_directories(
21047330f729Sjoerg       getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
21057330f729Sjoerg     if (llvm::Error Err = GlobalModuleIndex::writeIndex(
21067330f729Sjoerg             getFileManager(), getPCHContainerReader(),
21077330f729Sjoerg             getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
21087330f729Sjoerg       // FIXME this drops the error on the floor. This code is only used for
21097330f729Sjoerg       // typo correction and drops more than just this one source of errors
21107330f729Sjoerg       // (such as the directory creation failure above). It should handle the
21117330f729Sjoerg       // error.
21127330f729Sjoerg       consumeError(std::move(Err));
21137330f729Sjoerg       return nullptr;
21147330f729Sjoerg     }
2115*e038c9c4Sjoerg     TheASTReader->resetForReload();
2116*e038c9c4Sjoerg     TheASTReader->loadGlobalIndex();
2117*e038c9c4Sjoerg     GlobalIndex = TheASTReader->getGlobalIndex();
21187330f729Sjoerg   }
21197330f729Sjoerg   // For finding modules needing to be imported for fixit messages,
21207330f729Sjoerg   // we need to make the global index cover all modules, so we do that here.
21217330f729Sjoerg   if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
21227330f729Sjoerg     ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
21237330f729Sjoerg     bool RecreateIndex = false;
21247330f729Sjoerg     for (ModuleMap::module_iterator I = MMap.module_begin(),
21257330f729Sjoerg         E = MMap.module_end(); I != E; ++I) {
21267330f729Sjoerg       Module *TheModule = I->second;
21277330f729Sjoerg       const FileEntry *Entry = TheModule->getASTFile();
21287330f729Sjoerg       if (!Entry) {
21297330f729Sjoerg         SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
21307330f729Sjoerg         Path.push_back(std::make_pair(
21317330f729Sjoerg             getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
21327330f729Sjoerg         std::reverse(Path.begin(), Path.end());
21337330f729Sjoerg         // Load a module as hidden.  This also adds it to the global index.
21347330f729Sjoerg         loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
21357330f729Sjoerg         RecreateIndex = true;
21367330f729Sjoerg       }
21377330f729Sjoerg     }
21387330f729Sjoerg     if (RecreateIndex) {
21397330f729Sjoerg       if (llvm::Error Err = GlobalModuleIndex::writeIndex(
21407330f729Sjoerg               getFileManager(), getPCHContainerReader(),
21417330f729Sjoerg               getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
21427330f729Sjoerg         // FIXME As above, this drops the error on the floor.
21437330f729Sjoerg         consumeError(std::move(Err));
21447330f729Sjoerg         return nullptr;
21457330f729Sjoerg       }
2146*e038c9c4Sjoerg       TheASTReader->resetForReload();
2147*e038c9c4Sjoerg       TheASTReader->loadGlobalIndex();
2148*e038c9c4Sjoerg       GlobalIndex = TheASTReader->getGlobalIndex();
21497330f729Sjoerg     }
21507330f729Sjoerg     HaveFullGlobalModuleIndex = true;
21517330f729Sjoerg   }
21527330f729Sjoerg   return GlobalIndex;
21537330f729Sjoerg }
21547330f729Sjoerg 
21557330f729Sjoerg // Check global module index for missing imports.
21567330f729Sjoerg bool
lookupMissingImports(StringRef Name,SourceLocation TriggerLoc)21577330f729Sjoerg CompilerInstance::lookupMissingImports(StringRef Name,
21587330f729Sjoerg                                        SourceLocation TriggerLoc) {
21597330f729Sjoerg   // Look for the symbol in non-imported modules, but only if an error
21607330f729Sjoerg   // actually occurred.
21617330f729Sjoerg   if (!buildingModule()) {
21627330f729Sjoerg     // Load global module index, or retrieve a previously loaded one.
21637330f729Sjoerg     GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
21647330f729Sjoerg       TriggerLoc);
21657330f729Sjoerg 
21667330f729Sjoerg     // Only if we have a global index.
21677330f729Sjoerg     if (GlobalIndex) {
21687330f729Sjoerg       GlobalModuleIndex::HitSet FoundModules;
21697330f729Sjoerg 
21707330f729Sjoerg       // Find the modules that reference the identifier.
21717330f729Sjoerg       // Note that this only finds top-level modules.
21727330f729Sjoerg       // We'll let diagnoseTypo find the actual declaration module.
21737330f729Sjoerg       if (GlobalIndex->lookupIdentifier(Name, FoundModules))
21747330f729Sjoerg         return true;
21757330f729Sjoerg     }
21767330f729Sjoerg   }
21777330f729Sjoerg 
21787330f729Sjoerg   return false;
21797330f729Sjoerg }
resetAndLeakSema()21807330f729Sjoerg void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
21817330f729Sjoerg 
setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS)21827330f729Sjoerg void CompilerInstance::setExternalSemaSource(
21837330f729Sjoerg     IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
21847330f729Sjoerg   ExternalSemaSrc = std::move(ESS);
21857330f729Sjoerg }
2186