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