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