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