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