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