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