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