clang 23.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"
45#include "llvm/ADT/IntrusiveRefCntPtr.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/ScopeExit.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/Plugins/PassPlugin.h"
51#include "llvm/Support/AdvisoryLock.h"
52#include "llvm/Support/BuryPointer.h"
53#include "llvm/Support/CrashRecoveryContext.h"
54#include "llvm/Support/Errc.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/Signals.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/Timer.h"
61#include "llvm/Support/VirtualFileSystem.h"
62#include "llvm/Support/VirtualOutputBackends.h"
63#include "llvm/Support/VirtualOutputError.h"
64#include "llvm/Support/raw_ostream.h"
65#include "llvm/TargetParser/Host.h"
66#include <optional>
67#include <time.h>
68#include <utility>
69
70using namespace clang;
71
72CompilerInstance::CompilerInstance(
73 std::shared_ptr<CompilerInvocation> Invocation,
74 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
75 std::shared_ptr<ModuleCache> ModCache)
76 : ModuleLoader(/*BuildingModule=*/ModCache != nullptr),
77 Invocation(std::move(Invocation)),
78 ModCache(ModCache ? std::move(ModCache)
80 ThePCHContainerOperations(std::move(PCHContainerOps)) {
81 assert(this->Invocation && "Invocation must not be null");
82}
83
85 assert(OutputFiles.empty() && "Still output files in flight?");
86}
87
89 return (BuildGlobalModuleIndex ||
90 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
91 getFrontendOpts().GenerateGlobalModuleIndex)) &&
92 !DisableGeneratingGlobalModuleIndex;
93}
94
99
101 OwnedVerboseOutputStream.reset();
102 VerboseOutputStream = &Value;
103}
104
105void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
106 OwnedVerboseOutputStream.swap(Value);
107 VerboseOutputStream = OwnedVerboseOutputStream.get();
108}
109
112
114 // Create the target instance.
117 if (!hasTarget())
118 return false;
119
120 // Check whether AuxTarget exists, if not, then create TargetInfo for the
121 // other side of CUDA/OpenMP/SYCL compilation.
122 if (!getAuxTarget() &&
123 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
124 !getFrontendOpts().AuxTriple.empty()) {
125 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
126 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
127 if (getFrontendOpts().AuxTargetCPU)
128 TO->CPU = *getFrontendOpts().AuxTargetCPU;
129 if (getFrontendOpts().AuxTargetFeatures)
130 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
131 TO->HostTriple = getTarget().getTriple().str();
133 }
134
135 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
136 if (getLangOpts().RoundingMath) {
137 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
138 getLangOpts().RoundingMath = false;
139 }
140 auto FPExc = getLangOpts().getFPExceptionMode();
141 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
142 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
143 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
144 }
145 // FIXME: can we disable FEnvAccess?
146 }
147
148 // We should do it here because target knows nothing about
149 // language options when it's being created.
150 if (getLangOpts().OpenCL &&
151 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
152 return false;
153
154 // Inform the target of the language options.
155 // FIXME: We shouldn't need to do this, the target should be immutable once
156 // created. This complexity should be lifted elsewhere.
158
159 if (auto *Aux = getAuxTarget())
160 getTarget().setAuxTarget(Aux);
161
162 return true;
163}
164
166 assert(Value == nullptr ||
167 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
168 FileMgr = std::move(Value);
169}
170
175
176void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
177 PP = std::move(Value);
178}
179
182 Context = std::move(Value);
183
184 if (Context && Consumer)
186}
187
189 TheSema.reset(S);
190}
191
192void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
193 Consumer = std::move(Value);
194
195 if (Context && Consumer)
197}
198
202
203std::unique_ptr<Sema> CompilerInstance::takeSema() {
204 return std::move(TheSema);
205}
206
208 return TheASTReader;
209}
211 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
212 "Expected ASTReader to use the same PCM cache");
213 TheASTReader = std::move(Reader);
214}
215
216std::shared_ptr<ModuleDependencyCollector>
218 return ModuleDepCollector;
219}
220
222 std::shared_ptr<ModuleDependencyCollector> Collector) {
223 ModuleDepCollector = std::move(Collector);
224}
225
226static void collectHeaderMaps(const HeaderSearch &HS,
227 std::shared_ptr<ModuleDependencyCollector> MDC) {
228 SmallVector<std::string, 4> HeaderMapFileNames;
229 HS.getHeaderMapFileNames(HeaderMapFileNames);
230 for (auto &Name : HeaderMapFileNames)
231 MDC->addFile(Name);
232}
233
235 std::shared_ptr<ModuleDependencyCollector> MDC) {
236 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
237 if (PPOpts.ImplicitPCHInclude.empty())
238 return;
239
240 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
242 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
243 if (!PCHDir) {
244 MDC->addFile(PCHInclude);
245 return;
246 }
247
248 std::error_code EC;
249 SmallString<128> DirNative;
250 llvm::sys::path::native(PCHDir->getName(), DirNative);
251 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
253 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
254 Dir != DirEnd && !EC; Dir.increment(EC)) {
255 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
256 // used here since we're not interested in validating the PCH at this time,
257 // but only to check whether this is a file containing an AST.
259 Dir->path(), FileMgr, CI.getModuleCache(),
261 /*FindModuleFileExtensions=*/false, Validator,
262 /*ValidateDiagnosticOptions=*/false))
263 MDC->addFile(Dir->path());
264 }
265}
266
268 std::shared_ptr<ModuleDependencyCollector> MDC) {
269 // Collect all VFS found.
271 CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) {
272 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
273 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
274 });
275
276 for (auto &E : VFSEntries)
277 MDC->addFile(E.VPath, E.RPath);
278}
279
282 DiagnosticOptions DiagOpts;
283 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
284 /*ShouldOwnClient=*/false);
285
287 std::move(BaseFS));
288 // FIXME: Should this go into createVFSFromCompilerInvocation?
289 if (getFrontendOpts().ShowStats)
290 VFS =
291 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
292}
293
294// Diagnostics
296 const CodeGenOptions *CodeGenOpts,
297 DiagnosticsEngine &Diags) {
298 std::error_code EC;
299 std::unique_ptr<raw_ostream> StreamOwner;
300 raw_ostream *OS = &llvm::errs();
301 if (DiagOpts.DiagnosticLogFile != "-") {
302 // Create the output stream.
303 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
304 DiagOpts.DiagnosticLogFile, EC,
305 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
306 if (EC) {
307 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
308 << DiagOpts.DiagnosticLogFile << EC.message();
309 } else {
310 FileOS->SetUnbuffered();
311 OS = FileOS.get();
312 StreamOwner = std::move(FileOS);
313 }
314 }
315
316 // Chain in the diagnostic client which will log the diagnostics.
317 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
318 std::move(StreamOwner));
319 if (CodeGenOpts)
320 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
321 if (Diags.ownsClient()) {
322 Diags.setClient(
323 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
324 } else {
325 Diags.setClient(
326 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
327 }
328}
329
331 DiagnosticsEngine &Diags,
332 StringRef OutputFile) {
333 auto SerializedConsumer =
334 clang::serialized_diags::create(OutputFile, DiagOpts);
335
336 if (Diags.ownsClient()) {
338 Diags.takeClient(), std::move(SerializedConsumer)));
339 } else {
341 Diags.getClient(), std::move(SerializedConsumer)));
342 }
343}
344
346 bool ShouldOwnClient) {
348 Client, ShouldOwnClient, &getCodeGenOpts());
349}
350
352 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
353 DiagnosticConsumer *Client, bool ShouldOwnClient,
354 const CodeGenOptions *CodeGenOpts) {
355 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
356 DiagnosticIDs::create(), Opts);
357
358 // Create the diagnostic client for reporting errors or for
359 // implementing -verify.
360 if (Client) {
361 Diags->setClient(Client, ShouldOwnClient);
362 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
363 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
364 } else
365 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
366
367 // Chain in -verify checker, if requested.
368 if (Opts.VerifyDiagnostics)
369 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
370
371 // Chain in -diagnostic-log-file dumper, if requested.
372 if (!Opts.DiagnosticLogFile.empty())
373 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
374
375 if (!Opts.DiagnosticSerializationFile.empty())
377
378 // Configure our handling of diagnostics.
379 ProcessWarningOptions(*Diags, Opts, VFS);
380
381 return Diags;
382}
383
384// File Manager
385
387 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
388 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), VFS);
389}
390
391// Source Manager
392
394 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
395 assert(FileMgr && "FileManager needed for creating SourceManager");
396 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(),
398}
399
400// Initialize the remapping of files to alternative contents, e.g.,
401// those specified through other files.
403 SourceManager &SourceMgr,
405 const PreprocessorOptions &InitOpts) {
406 // Remap files in the source manager (with buffers).
407 for (const auto &RB : InitOpts.RemappedFileBuffers) {
408 // Create the file entry for the file that we're mapping from.
409 FileEntryRef FromFile =
410 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
411
412 // Override the contents of the "from" file with the contents of the
413 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
414 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
415 // to the SourceManager.
416 if (InitOpts.RetainRemappedFileBuffers)
417 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
418 else
419 SourceMgr.overrideFileContents(
420 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
421 }
422
423 // Remap files in the source manager (with other files).
424 for (const auto &RF : InitOpts.RemappedFiles) {
425 // Find the file that we're mapping to.
426 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
427 if (!ToFile) {
428 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
429 continue;
430 }
431
432 // Create the file entry for the file that we're mapping from.
433 FileEntryRef FromFile =
434 FileMgr.getVirtualFileRef(RF.first, ToFile->getSize(), 0);
435
436 // Override the contents of the "from" file with the contents of
437 // the "to" file.
438 SourceMgr.overrideFileContents(FromFile, *ToFile);
439 }
440
441 SourceMgr.setOverridenFilesKeepOriginalName(
443}
444
445// Preprocessor
446
449
450 // The AST reader holds a reference to the old preprocessor (if any).
451 TheASTReader.reset();
452
453 // Create the Preprocessor.
454 HeaderSearch *HeaderInfo =
457 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
459 getSourceManager(), *HeaderInfo, *this,
460 /*IdentifierInfoLookup=*/nullptr,
461 /*OwnsHeaderSearch=*/true, TUKind);
463 PP->Initialize(getTarget(), getAuxTarget());
464
465 if (PPOpts.DetailedRecord)
466 PP->createPreprocessingRecord();
467
468 // Apply remappings to the source manager.
469 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
470 PP->getFileManager(), PPOpts);
471
472 // Predefine macros and configure the preprocessor.
475
476 // Initialize the header search object. In CUDA compilations, we use the aux
477 // triple (the host triple) to initialize our header search, since we need to
478 // find the host headers in order to compile the CUDA code.
479 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
480 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
481 PP->getAuxTargetInfo())
482 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
483
484 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
485 PP->getLangOpts(), *HeaderSearchTriple);
486
487 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
488
489 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
490 std::string ContextHash = getInvocation().computeContextHash();
491 PP->getHeaderSearchInfo().setContextHash(ContextHash);
492 PP->getHeaderSearchInfo().setSpecificModuleCachePath(
493 getSpecificModuleCachePath(ContextHash));
494 }
495
496 // Handle generating dependencies, if requested.
498 if (!DepOpts.OutputFile.empty())
499 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
500 if (!DepOpts.DOTOutputFile.empty())
502 getHeaderSearchOpts().Sysroot);
503
504 // If we don't have a collector, but we are collecting module dependencies,
505 // then we're the top level compiler instance and need to create one.
506 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
507 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
509 }
510
511 // If there is a module dep collector, register with other dep collectors
512 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
513 if (ModuleDepCollector) {
514 addDependencyCollector(ModuleDepCollector);
515 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
516 collectIncludePCH(*this, ModuleDepCollector);
517 collectVFSEntries(*this, ModuleDepCollector);
518 }
519
520 // Modules need an output manager.
521 if (!hasOutputManager())
523
524 for (auto &Listener : DependencyCollectors)
525 Listener->attachToPreprocessor(*PP);
526
527 // Handle generating header include information, if requested.
528 if (DepOpts.ShowHeaderIncludes)
529 AttachHeaderIncludeGen(*PP, DepOpts);
530 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
531 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
532 if (OutputPath == "-")
533 OutputPath = "";
534 AttachHeaderIncludeGen(*PP, DepOpts,
535 /*ShowAllHeaders=*/true, OutputPath,
536 /*ShowDepth=*/false);
537 }
538
540 AttachHeaderIncludeGen(*PP, DepOpts,
541 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
542 /*ShowDepth=*/true, /*MSStyle=*/true);
543 }
544
545 if (GetDependencyDirectives)
546 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
547}
548
549std::string
551 assert(FileMgr && "Specific module cache path requires a FileManager");
552
553 // Set up the module path, including the hash for the module-creation options.
554 SmallString<256> SpecificModuleCache;
555 normalizeModuleCachePath(*FileMgr, getHeaderSearchOpts().ModuleCachePath,
556 SpecificModuleCache);
557 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
558 llvm::sys::path::append(SpecificModuleCache, ContextHash);
559 return std::string(SpecificModuleCache);
560}
561
562// ASTContext
563
566 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
567 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
568 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
569 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
570 setASTContext(std::move(Context));
571}
572
573// ExternalASTSource
574
575namespace {
576// Helper to recursively read the module names for all modules we're adding.
577// We mark these as known and redirect any attempt to load that module to
578// the files we were handed.
579struct ReadModuleNames : ASTReaderListener {
580 Preprocessor &PP;
582
583 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
584
585 void ReadModuleName(StringRef ModuleName) override {
586 // Keep the module name as a string for now. It's not safe to create a new
587 // IdentifierInfo from an ASTReader callback.
588 LoadedModules.push_back(ModuleName.str());
589 }
590
591 void registerAll() {
592 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
593 for (const std::string &LoadedModule : LoadedModules)
594 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
595 MM.findOrLoadModule(LoadedModule));
596 LoadedModules.clear();
597 }
598
599 void markAllUnavailable() {
600 for (const std::string &LoadedModule : LoadedModules) {
602 LoadedModule)) {
603 M->HasIncompatibleModuleFile = true;
604
605 // Mark module as available if the only reason it was unavailable
606 // was missing headers.
607 SmallVector<Module *, 2> Stack;
608 Stack.push_back(M);
609 while (!Stack.empty()) {
610 Module *Current = Stack.pop_back_val();
611 if (Current->IsUnimportable) continue;
612 Current->IsAvailable = true;
613 auto SubmodulesRange = Current->submodules();
614 llvm::append_range(Stack, SubmodulesRange);
615 }
616 }
617 }
618 LoadedModules.clear();
619 }
620};
621} // namespace
622
624 StringRef Path, DisableValidationForModuleKind DisableValidation,
625 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
626 bool OwnDeserializationListener) {
628 TheASTReader = createPCHExternalASTSource(
629 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
630 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
632 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
633 DeserializationListener, OwnDeserializationListener, Preamble,
634 getFrontendOpts().UseGlobalModuleIndex);
635}
636
638 StringRef Path, StringRef Sysroot,
639 DisableValidationForModuleKind DisableValidation,
640 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
641 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
642 const CodeGenOptions &CodeGenOpts,
643 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
644 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
645 void *DeserializationListener, bool OwnDeserializationListener,
646 bool Preamble, bool UseGlobalModuleIndex) {
647 const HeaderSearchOptions &HSOpts =
648 PP.getHeaderSearchInfo().getHeaderSearchOpts();
649
650 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
651 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
652 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
653 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
656 HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
657
658 // We need the external source to be set up before we read the AST, because
659 // eagerly-deserialized declarations may use it.
660 Context.setExternalSource(Reader);
661
662 Reader->setDeserializationListener(
663 static_cast<ASTDeserializationListener *>(DeserializationListener),
664 /*TakeOwnership=*/OwnDeserializationListener);
665
666 for (auto &Listener : DependencyCollectors)
667 Listener->attachToASTReader(*Reader);
668
669 auto Listener = std::make_unique<ReadModuleNames>(PP);
670 auto &ListenerRef = *Listener;
671 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
672 std::move(Listener));
673
674 switch (Reader->ReadAST(Path,
680 // Set the predefines buffer as suggested by the PCH reader. Typically, the
681 // predefines buffer will be empty.
682 PP.setPredefines(Reader->getSuggestedPredefines());
683 ListenerRef.registerAll();
684 return Reader;
685
687 // Unrecoverable failure: don't even try to process the input file.
688 break;
689
695 // No suitable PCH file could be found. Return an error.
696 break;
697 }
698
699 ListenerRef.markAllUnavailable();
700 Context.setExternalSource(nullptr);
701 return nullptr;
702}
703
704// Code Completion
705
707 StringRef Filename,
708 unsigned Line,
709 unsigned Column) {
710 // Tell the source manager to chop off the given file at a specific
711 // line and column.
712 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
713 if (!Entry) {
714 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
715 << Filename;
716 return true;
717 }
718
719 // Truncate the named file at the given line/column.
721 return false;
722}
723
726 if (!CompletionConsumer) {
728 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
729 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
730 return;
732 Loc.Line, Loc.Column)) {
734 return;
735 }
736}
737
739 timerGroup.reset(new llvm::TimerGroup("clang", "Clang time report"));
740 FrontendTimer.reset(new llvm::Timer("frontend", "Front end", *timerGroup));
741}
742
745 StringRef Filename,
746 unsigned Line,
747 unsigned Column,
748 const CodeCompleteOptions &Opts,
749 raw_ostream &OS) {
750 if (EnableCodeCompletion(PP, Filename, Line, Column))
751 return nullptr;
752
753 // Set up the creation routine for code-completion.
754 return new PrintingCodeCompleteConsumer(Opts, OS);
755}
756
758 CodeCompleteConsumer *CompletionConsumer) {
759 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
760 TUKind, CompletionConsumer));
761
762 // Set up API notes.
763 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
764
765 // Attach the external sema source if there is any.
766 if (ExternalSemaSrc) {
767 TheSema->addExternalSource(ExternalSemaSrc);
768 ExternalSemaSrc->InitializeSema(*TheSema);
769 }
770
771 // If we're building a module and are supposed to load API notes,
772 // notify the API notes manager.
773 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
774 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
775 currentModule, getLangOpts().APINotesModules,
776 getAPINotesOpts().ModuleSearchPaths);
777 }
778}
779
780// Output Files
781
783 // The ASTConsumer can own streams that write to the output files.
784 assert(!hasASTConsumer() && "ASTConsumer should be reset");
785 if (!EraseFiles) {
786 for (auto &O : OutputFiles)
787 llvm::handleAllErrors(
788 O.keep(),
789 [&](const llvm::vfs::TempFileOutputError &E) {
790 getDiagnostics().Report(diag::err_unable_to_rename_temp)
791 << E.getTempPath() << E.getOutputPath()
792 << E.convertToErrorCode().message();
793 },
794 [&](const llvm::vfs::OutputError &E) {
795 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
796 << E.getOutputPath() << E.convertToErrorCode().message();
797 },
798 [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
799 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
800 << O.getPath() << EIB.message();
801 });
802 }
803 OutputFiles.clear();
804 if (DeleteBuiltModules) {
805 for (auto &Module : BuiltModules)
806 llvm::sys::fs::remove(Module.second);
807 BuiltModules.clear();
808 }
809}
810
811std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
812 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
813 bool CreateMissingDirectories, bool ForceUseTemporary) {
814 StringRef OutputPath = getFrontendOpts().OutputFile;
815 std::optional<SmallString<128>> PathStorage;
816 if (OutputPath.empty()) {
817 if (InFile == "-" || Extension.empty()) {
818 OutputPath = "-";
819 } else {
820 PathStorage.emplace(InFile);
821 llvm::sys::path::replace_extension(*PathStorage, Extension);
822 OutputPath = *PathStorage;
823 }
824 }
825
826 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
827 getFrontendOpts().UseTemporary || ForceUseTemporary,
828 CreateMissingDirectories);
829}
830
831std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
832 return std::make_unique<llvm::raw_null_ostream>();
833}
834
835// Output Manager
836
839 assert(!OutputMgr && "Already has an output manager");
840 OutputMgr = std::move(NewOutputs);
841}
842
844 assert(!OutputMgr && "Already has an output manager");
845 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
846}
847
848llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
849 assert(OutputMgr);
850 return *OutputMgr;
851}
852
854 if (!hasOutputManager())
856 return getOutputManager();
857}
858
859std::unique_ptr<raw_pwrite_stream>
861 bool RemoveFileOnSignal, bool UseTemporary,
862 bool CreateMissingDirectories) {
864 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
865 CreateMissingDirectories);
866 if (OS)
867 return std::move(*OS);
868 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
869 << OutputPath << errorToErrorCode(OS.takeError()).message();
870 return nullptr;
871}
872
874CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
875 bool RemoveFileOnSignal,
876 bool UseTemporary,
877 bool CreateMissingDirectories) {
878 assert((!CreateMissingDirectories || UseTemporary) &&
879 "CreateMissingDirectories is only allowed when using temporary files");
880
881 // If '-working-directory' was passed, the output filename should be
882 // relative to that.
883 std::optional<SmallString<128>> AbsPath;
884 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
885 assert(hasFileManager() &&
886 "File Manager is required to fix up relative path.\n");
887
888 AbsPath.emplace(OutputPath);
890 OutputPath = *AbsPath;
891 }
892
893 using namespace llvm::vfs;
895 OutputPath,
896 OutputConfig()
897 .setTextWithCRLF(!Binary)
898 .setDiscardOnSignal(RemoveFileOnSignal)
899 .setAtomicWrite(UseTemporary)
900 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
901 if (!O)
902 return O.takeError();
903
904 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
905 OutputFiles.push_back(std::move(*O));
906 return OutputFiles.back().createProxy();
907}
908
909// Initialization Utilities
910
915
916// static
918 DiagnosticsEngine &Diags,
919 FileManager &FileMgr,
920 SourceManager &SourceMgr) {
926
927 if (Input.isBuffer()) {
928 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
929 assert(SourceMgr.getMainFileID().isValid() &&
930 "Couldn't establish MainFileID!");
931 return true;
932 }
933
934 StringRef InputFile = Input.getFile();
935
936 // Figure out where to get and map in the main file.
937 auto FileOrErr = InputFile == "-"
938 ? FileMgr.getSTDIN()
939 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
940 if (!FileOrErr) {
941 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
942 if (InputFile != "-")
943 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
944 else
945 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
946 return false;
947 }
948
949 SourceMgr.setMainFileID(
950 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
951
952 assert(SourceMgr.getMainFileID().isValid() &&
953 "Couldn't establish MainFileID!");
954 return true;
955}
956
957// High-Level Operations
958
960 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
961 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
962 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
963
964 // Mark this point as the bottom of the stack if we don't have somewhere
965 // better. We generally expect frontend actions to be invoked with (nearly)
966 // DesiredStackSpace available.
968
969 llvm::scope_exit FinishDiagnosticClient([&]() {
970 // Notify the diagnostic client that all files were processed.
972 });
973
974 raw_ostream &OS = getVerboseOutputStream();
975
976 if (!Act.PrepareToExecute(*this))
977 return false;
978
979 if (!createTarget())
980 return false;
981
982 // rewriter project will change target built-in bool type from its default.
983 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
985
986 // Validate/process some options.
987 if (getHeaderSearchOpts().Verbose)
988 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
989 << LLVM_VERSION_STRING << " default target "
990 << llvm::sys::getDefaultTargetTriple() << "\n";
991
992 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
993 llvm::EnableStatistics(false);
994
995 // Sort vectors containing toc data and no toc data variables to facilitate
996 // binary search later.
997 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
998 llvm::sort(getCodeGenOpts().NoTocDataVars);
999
1000 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1001 // Reset the ID tables if we are reusing the SourceManager and parsing
1002 // regular files.
1003 if (hasSourceManager() && !Act.isModelParsingAction())
1005
1006 if (Act.BeginSourceFile(*this, FIF)) {
1007 if (llvm::Error Err = Act.Execute()) {
1008 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1009 }
1010 Act.EndSourceFile();
1011 }
1012 }
1013
1015
1016 if (getFrontendOpts().ShowStats) {
1017 if (hasFileManager()) {
1019 OS << '\n';
1020 }
1021 llvm::PrintStatistics(OS);
1022 }
1023 StringRef StatsFile = getFrontendOpts().StatsFile;
1024 if (!StatsFile.empty()) {
1025 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1026 if (getFrontendOpts().AppendStats)
1027 FileFlags |= llvm::sys::fs::OF_Append;
1028 std::error_code EC;
1029 auto StatS =
1030 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1031 if (EC) {
1032 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1033 << StatsFile << EC.message();
1034 } else {
1035 llvm::PrintStatisticsJSON(*StatS);
1036 }
1037 }
1038
1039 return !getDiagnostics().getClient()->getNumErrors();
1040}
1041
1043 if (!getDiagnosticOpts().ShowCarets)
1044 return;
1045
1046 raw_ostream &OS = getVerboseOutputStream();
1047
1048 // We can have multiple diagnostics sharing one diagnostic client.
1049 // Get the total number of warnings/errors from the client.
1050 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1051 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1052
1053 if (NumWarnings)
1054 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1055 if (NumWarnings && NumErrors)
1056 OS << " and ";
1057 if (NumErrors)
1058 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1059 if (NumWarnings || NumErrors) {
1060 OS << " generated";
1061 if (getLangOpts().CUDA) {
1062 if (!getLangOpts().CUDAIsDevice) {
1063 OS << " when compiling for host";
1064 } else {
1065 OS << " when compiling for "
1066 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1067 : getTarget().getTriple().str());
1068 }
1069 }
1070 OS << ".\n";
1071 }
1072}
1073
1075 // Load any requested plugins.
1076 for (const std::string &Path : getFrontendOpts().Plugins) {
1077 std::string Error;
1078 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1079 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1080 << Path << Error;
1081 }
1082
1083 // Load and store pass plugins for the back-end.
1084 for (const std::string &Path : getCodeGenOpts().PassPlugins) {
1085 if (auto PassPlugin = llvm::PassPlugin::Load(Path)) {
1086 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1087 } else {
1088 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1089 << Path << toString(PassPlugin.takeError());
1090 }
1091 }
1092
1093 // Check if any of the loaded plugins replaces the main AST action
1094 for (const FrontendPluginRegistry::entry &Plugin :
1095 FrontendPluginRegistry::entries()) {
1096 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1097 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1099 getFrontendOpts().ActionName = Plugin.getName().str();
1100 break;
1101 }
1102 }
1103}
1104
1105/// Determine the appropriate source input kind based on language
1106/// options.
1108 if (LangOpts.OpenCL)
1109 return Language::OpenCL;
1110 if (LangOpts.CUDA)
1111 return Language::CUDA;
1112 if (LangOpts.ObjC)
1113 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1114 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1115}
1116
1117std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1118 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1119 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1120 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1121 // Construct a compiler invocation for creating this module.
1122 auto Invocation = std::make_shared<CompilerInvocation>(getInvocation());
1123
1124 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1125
1126 // For any options that aren't intended to affect how a module is built,
1127 // reset them to their default values.
1128 Invocation->resetNonModularOptions();
1129
1130 // Remove any macro definitions that are explicitly ignored by the module.
1131 // They aren't supposed to affect how the module is built anyway.
1132 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1133 llvm::erase_if(PPOpts.Macros,
1134 [&HSOpts](const std::pair<std::string, bool> &def) {
1135 StringRef MacroDef = def.first;
1136 return HSOpts.ModulesIgnoreMacros.contains(
1137 llvm::CachedHashString(MacroDef.split('=').first));
1138 });
1139
1140 // If the original compiler invocation had -fmodule-name, pass it through.
1141 Invocation->getLangOpts().ModuleName =
1143
1144 // Note the name of the module we're building.
1145 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1146
1147 // If there is a module map file, build the module using the module map.
1148 // Set up the inputs/outputs so that we build the module from its umbrella
1149 // header.
1150 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1151 FrontendOpts.OutputFile = ModuleFileName.str();
1152 FrontendOpts.DisableFree = false;
1153 FrontendOpts.GenerateGlobalModuleIndex = false;
1154 FrontendOpts.BuildingImplicitModule = true;
1155 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1156 // Force implicitly-built modules to hash the content of the module file.
1157 HSOpts.ModulesHashContent = true;
1158 FrontendOpts.Inputs = {std::move(Input)};
1159
1160 // Don't free the remapped file buffers; they are owned by our caller.
1161 PPOpts.RetainRemappedFileBuffers = true;
1162
1163 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1164
1165 DiagOpts.VerifyDiagnostics = 0;
1166 assert(getInvocation().computeContextHash() ==
1167 Invocation->computeContextHash() &&
1168 "Module hash mismatch!");
1169
1170 // Construct a compiler instance that will be used to actually create the
1171 // module. Since we're sharing an in-memory module cache,
1172 // CompilerInstance::CompilerInstance is responsible for finalizing the
1173 // buffers to prevent use-after-frees.
1174 auto InstancePtr = std::make_unique<CompilerInstance>(
1175 std::move(Invocation), getPCHContainerOperations(), ModCache);
1176 auto &Instance = *InstancePtr;
1177
1178 auto &Inv = Instance.getInvocation();
1179
1180 if (ThreadSafeConfig) {
1181 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1182 Instance.createFileManager();
1183 } else if (FrontendOpts.ModulesShareFileManager) {
1184 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1185 Instance.setFileManager(getFileManagerPtr());
1186 } else {
1187 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1188 Instance.createFileManager();
1189 }
1190
1191 if (ThreadSafeConfig) {
1192 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1193 /*ShouldOwnClient=*/false);
1194 } else {
1195 Instance.createDiagnostics(
1196 new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1197 /*ShouldOwnClient=*/true);
1198 }
1199 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1200 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1201
1202 Instance.createSourceManager();
1203 SourceManager &SourceMgr = Instance.getSourceManager();
1204
1205 if (ThreadSafeConfig) {
1206 // Detecting cycles in the module graph is responsibility of the client.
1207 } else {
1208 // Note that this module is part of the module build stack, so that we
1209 // can detect cycles in the module graph.
1210 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1211 SourceMgr.pushModuleBuildStack(
1212 ModuleName, FullSourceLoc(ImportLoc, getSourceManager()));
1213 }
1214
1215 // Make a copy for the new instance.
1216 Instance.FailedModules = FailedModules;
1217
1218 if (GetDependencyDirectives)
1219 Instance.GetDependencyDirectives =
1220 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1221
1222 if (ThreadSafeConfig) {
1223 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1224 } else {
1225 // If we're collecting module dependencies, we need to share a collector
1226 // between all of the module CompilerInstances. Other than that, we don't
1227 // want to produce any dependency output from the module build.
1228 Instance.setModuleDepCollector(getModuleDepCollector());
1229 }
1230 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1231
1232 return InstancePtr;
1233}
1234
1235namespace {
1236class PrettyStackTraceBuildModule : public llvm::PrettyStackTraceEntry {
1237 StringRef ModuleName;
1238 StringRef ModuleFileName;
1239
1240public:
1241 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1242 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1243 void print(raw_ostream &OS) const override {
1244 OS << "Building module '" << ModuleName << "' as '" << ModuleFileName
1245 << "'\n";
1246 }
1247};
1248} // namespace
1249
1251 StringRef ModuleName,
1252 StringRef ModuleFileName,
1253 CompilerInstance &Instance) {
1254 PrettyStackTraceBuildModule CrashInfo(ModuleName, ModuleFileName);
1255 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1256
1257 // Never compile a module that's already finalized - this would cause the
1258 // existing module to be freed, causing crashes if it is later referenced
1259 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1260 getDiagnostics().Report(ImportLoc, diag::err_module_rebuild_finalized)
1261 << ModuleName;
1262 return false;
1263 }
1264
1265 getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1266 << ModuleName << ModuleFileName;
1267
1268 // Execute the action to actually build the module in-place. Use a separate
1269 // thread so that we get a stack large enough.
1270 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1271 [&]() {
1273 Instance.ExecuteAction(Action);
1274 },
1276
1277 getDiagnostics().Report(ImportLoc, diag::remark_module_build_done)
1278 << ModuleName;
1279
1280 // Propagate the statistics to the parent FileManager.
1281 if (!getFrontendOpts().ModulesShareFileManager)
1282 getFileManager().AddStats(Instance.getFileManager());
1283
1284 // Propagate the failed modules to the parent instance.
1285 FailedModules = std::move(Instance.FailedModules);
1286
1287 if (Crashed) {
1288 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1289 // that must be closed before clearing output files.
1290 Instance.setSema(nullptr);
1291 Instance.setASTConsumer(nullptr);
1292
1293 // Delete any remaining temporary files related to Instance.
1294 Instance.clearOutputFiles(/*EraseFiles=*/true);
1295 }
1296
1297 // We've rebuilt a module. If we're allowed to generate or update the global
1298 // module index, record that fact in the importing compiler instance.
1299 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1301 }
1302
1303 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1304 // occurred.
1305 return !Instance.getDiagnostics().hasErrorOccurred() ||
1306 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1307}
1308
1311 StringRef Filename = llvm::sys::path::filename(File.getName());
1312 SmallString<128> PublicFilename(File.getDir().getName());
1313 if (Filename == "module_private.map")
1314 llvm::sys::path::append(PublicFilename, "module.map");
1315 else if (Filename == "module.private.modulemap")
1316 llvm::sys::path::append(PublicFilename, "module.modulemap");
1317 else
1318 return std::nullopt;
1319 return FileMgr.getOptionalFileRef(PublicFilename);
1320}
1321
1322std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1323 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
1324 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1325 StringRef ModuleName = Module->getTopLevelModuleName();
1326
1328
1329 // Get or create the module map that we'll use to build this module.
1331 SourceManager &SourceMgr = getSourceManager();
1332
1333 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1334 ModuleMapFID.isValid()) {
1335 // We want to use the top-level module map. If we don't, the compiling
1336 // instance may think the containing module map is a top-level one, while
1337 // the importing instance knows it's included from a parent module map via
1338 // the extern directive. This mismatch could bite us later.
1339 SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1340 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1341 ModuleMapFID = SourceMgr.getFileID(Loc);
1342 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1343 }
1344
1345 OptionalFileEntryRef ModuleMapFile =
1346 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1347 assert(ModuleMapFile && "Top-level module map with no FileID");
1348
1349 // Canonicalize compilation to start with the public module map. This is
1350 // vital for submodules declarations in the private module maps to be
1351 // correctly parsed when depending on a top level module in the public one.
1352 if (OptionalFileEntryRef PublicMMFile =
1353 getPublicModuleMap(*ModuleMapFile, getFileManager()))
1354 ModuleMapFile = PublicMMFile;
1355
1356 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1357
1358 // Use the systemness of the module map as parsed instead of using the
1359 // IsSystem attribute of the module. If the module has [system] but the
1360 // module map is not in a system path, then this would incorrectly parse
1361 // any other modules in that module map as system too.
1362 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(ModuleMapFID);
1363 bool IsSystem = isSystem(SLoc.getFile().getFileCharacteristic());
1364
1365 // Use the module map where this module resides.
1366 return cloneForModuleCompileImpl(
1367 ImportLoc, ModuleName,
1368 FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1369 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1370 std::move(ThreadSafeConfig));
1371 }
1372
1373 // FIXME: We only need to fake up an input file here as a way of
1374 // transporting the module's directory to the module map parser. We should
1375 // be able to do that more directly, and parse from a memory buffer without
1376 // inventing this file.
1377 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1378 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1379
1380 std::string InferredModuleMapContent;
1381 llvm::raw_string_ostream OS(InferredModuleMapContent);
1382 Module->print(OS);
1383
1384 auto Instance = cloneForModuleCompileImpl(
1385 ImportLoc, ModuleName,
1386 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1387 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName,
1388 std::move(ThreadSafeConfig));
1389
1390 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1391 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1392 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1393 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1394 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1395 std::move(ModuleMapBuffer));
1396
1397 return Instance;
1398}
1399
1400/// Read the AST right after compiling the module.
1401static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1402 SourceLocation ImportLoc,
1404 Module *Module, StringRef ModuleFileName,
1405 bool *OutOfDate, bool *Missing) {
1406 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1407
1408 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1409 if (OutOfDate)
1410 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1411
1412 // Try to read the module file, now that we've compiled it.
1413 ASTReader::ASTReadResult ReadResult =
1414 ImportingInstance.getASTReader()->ReadAST(
1415 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1416 ModuleLoadCapabilities);
1417 if (ReadResult == ASTReader::Success)
1418 return true;
1419
1420 // The caller wants to handle out-of-date failures.
1421 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1422 *OutOfDate = true;
1423 return false;
1424 }
1425
1426 // The caller wants to handle missing module files.
1427 if (Missing && ReadResult == ASTReader::Missing) {
1428 *Missing = true;
1429 return false;
1430 }
1431
1432 // The ASTReader didn't diagnose the error, so conservatively report it.
1433 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1434 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1435 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1436
1437 return false;
1438}
1439
1440/// Compile a module in a separate compiler instance and read the AST,
1441/// returning true if the module compiles without errors.
1442static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
1443 SourceLocation ImportLoc,
1445 Module *Module,
1446 StringRef ModuleFileName) {
1447 {
1448 auto Instance = ImportingInstance.cloneForModuleCompile(
1449 ModuleNameLoc, Module, ModuleFileName);
1450
1451 if (!ImportingInstance.compileModule(ModuleNameLoc,
1453 ModuleFileName, *Instance)) {
1454 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1455 diag::err_module_not_built)
1456 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1457 return false;
1458 }
1459 }
1460
1461 // The module is built successfully, we can update its timestamp now.
1462 if (ImportingInstance.getPreprocessor()
1466 ImportingInstance.getModuleCache().updateModuleTimestamp(ModuleFileName);
1467 }
1468
1469 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1470 Module, ModuleFileName,
1471 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1472}
1473
1474/// Compile a module in a separate compiler instance and read the AST,
1475/// returning true if the module compiles without errors, using a lock manager
1476/// to avoid building the same module in multiple compiler instances.
1477///
1478/// Uses a lock file manager and exponential backoff to reduce the chances that
1479/// multiple instances will compete to create the same module. On timeout,
1480/// deletes the lock file in order to avoid deadlock from crashing processes or
1481/// bugs in the lock file manager.
1483 CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1484 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1485 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1486
1487 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1488 << ModuleFileName << Module->Name;
1489
1490 auto &ModuleCache = ImportingInstance.getModuleCache();
1491 ModuleCache.prepareForGetLock(ModuleFileName);
1492
1493 while (true) {
1494 auto Lock = ModuleCache.getLock(ModuleFileName);
1495 bool Owned;
1496 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1497 // ModuleCache takes care of correctness and locks are only necessary for
1498 // performance. Fallback to building the module in case of any lock
1499 // related errors.
1500 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1501 << Module->Name << toString(std::move(Err));
1502 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1503 ModuleNameLoc, Module, ModuleFileName);
1504 }
1505 if (Owned) {
1506 // We're responsible for building the module ourselves.
1507 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1508 ModuleNameLoc, Module, ModuleFileName);
1509 }
1510
1511 // Someone else is responsible for building the module. Wait for them to
1512 // finish.
1513 switch (Lock->waitForUnlockFor(std::chrono::seconds(90))) {
1514 case llvm::WaitForUnlockResult::Success:
1515 break; // The interesting case.
1516 case llvm::WaitForUnlockResult::OwnerDied:
1517 continue; // try again to get the lock.
1518 case llvm::WaitForUnlockResult::Timeout:
1519 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1520 // for someone else to complete the build so that it does not happen
1521 // twice. In case of timeout, build it ourselves.
1522 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1523 << Module->Name;
1524 // Clear the lock file so that future invocations can make progress.
1525 Lock->unsafeMaybeUnlock();
1526 continue;
1527 }
1528
1529 // Read the module that was just written by someone else.
1530 bool OutOfDate = false;
1531 bool Missing = false;
1532 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1533 Module, ModuleFileName, &OutOfDate, &Missing))
1534 return true;
1535 if (!OutOfDate && !Missing)
1536 return false;
1537
1538 // The module may be missing or out of date in the presence of file system
1539 // races. It may also be out of date if one of its imports depends on header
1540 // search paths that are not consistent with this ImportingInstance.
1541 // Try again...
1542 }
1543}
1544
1545/// Compile a module in a separate compiler instance and read the AST,
1546/// returning true if the module compiles without errors, potentially using a
1547/// lock manager to avoid building the same module in multiple compiler
1548/// instances.
1549static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1550 SourceLocation ImportLoc,
1552 Module *Module, StringRef ModuleFileName) {
1553 return ImportingInstance.getInvocation()
1556 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
1558 ModuleFileName)
1559 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
1561 ModuleFileName);
1562}
1563
1564/// Diagnose differences between the current definition of the given
1565/// configuration macro and the definition provided on the command line.
1566static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1567 Module *Mod, SourceLocation ImportLoc) {
1568 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1569 SourceManager &SourceMgr = PP.getSourceManager();
1570
1571 // If this identifier has never had a macro definition, then it could
1572 // not have changed.
1573 if (!Id->hadMacroDefinition())
1574 return;
1575 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1576
1577 // Find the macro definition from the command line.
1578 MacroInfo *CmdLineDefinition = nullptr;
1579 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1580 // We only care about the predefines buffer.
1581 FileID FID = SourceMgr.getFileID(MD->getLocation());
1582 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1583 continue;
1584 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1585 CmdLineDefinition = DMD->getMacroInfo();
1586 break;
1587 }
1588
1589 auto *CurrentDefinition = PP.getMacroInfo(Id);
1590 if (CurrentDefinition == CmdLineDefinition) {
1591 // Macro matches. Nothing to do.
1592 } else if (!CurrentDefinition) {
1593 // This macro was defined on the command line, then #undef'd later.
1594 // Complain.
1595 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1596 << true << ConfigMacro << Mod->getFullModuleName();
1597 auto LatestDef = LatestLocalMD->getDefinition();
1598 assert(LatestDef.isUndefined() &&
1599 "predefined macro went away with no #undef?");
1600 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1601 << true;
1602 return;
1603 } else if (!CmdLineDefinition) {
1604 // There was no definition for this macro in the predefines buffer,
1605 // but there was a local definition. Complain.
1606 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1607 << false << ConfigMacro << Mod->getFullModuleName();
1608 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1609 diag::note_module_def_undef_here)
1610 << false;
1611 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1612 /*Syntactically=*/true)) {
1613 // The macro definitions differ.
1614 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1615 << false << ConfigMacro << Mod->getFullModuleName();
1616 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1617 diag::note_module_def_undef_here)
1618 << false;
1619 }
1620}
1621
1623 SourceLocation ImportLoc) {
1624 clang::Module *TopModule = M->getTopLevelModule();
1625 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1626 checkConfigMacro(PP, ConMacro, M, ImportLoc);
1627 }
1628}
1629
1631 if (TheASTReader)
1632 return;
1633
1634 if (!hasASTContext())
1636
1637 // If we're implicitly building modules but not currently recursively
1638 // building a module, check whether we need to prune the module cache.
1639 if (getSourceManager().getModuleBuildStack().empty() &&
1641 .getHeaderSearchInfo()
1643 .empty())
1644 ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath,
1645 getHeaderSearchOpts().ModuleCachePruneInterval,
1646 getHeaderSearchOpts().ModuleCachePruneAfter);
1647
1649 std::string Sysroot = HSOpts.Sysroot;
1650 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1651 const FrontendOptions &FEOpts = getFrontendOpts();
1652 std::unique_ptr<llvm::Timer> ReadTimer;
1653
1654 if (timerGroup)
1655 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1656 "Reading modules", *timerGroup);
1657 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1660 getFrontendOpts().ModuleFileExtensions,
1661 Sysroot.empty() ? "" : Sysroot.c_str(),
1663 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1664 /*AllowConfigurationMismatch=*/false,
1668 +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1669 if (hasASTConsumer()) {
1670 TheASTReader->setDeserializationListener(
1671 getASTConsumer().GetASTDeserializationListener());
1673 getASTConsumer().GetASTMutationListener());
1674 }
1675 getASTContext().setExternalSource(TheASTReader);
1676 if (hasSema())
1677 TheASTReader->InitializeSema(getSema());
1678 if (hasASTConsumer())
1679 TheASTReader->StartTranslationUnit(&getASTConsumer());
1680
1681 for (auto &Listener : DependencyCollectors)
1682 Listener->attachToASTReader(*TheASTReader);
1683}
1684
1686 StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1687 llvm::Timer Timer;
1688 if (timerGroup)
1689 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
1690 *timerGroup);
1691 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1692
1693 // If we don't already have an ASTReader, create one now.
1694 if (!TheASTReader)
1696
1697 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1698 // ASTReader to diagnose it, since it can produce better errors that we can.
1699 bool ConfigMismatchIsRecoverable =
1700 getDiagnostics().getDiagnosticLevel(diag::warn_ast_file_config_mismatch,
1701 SourceLocation()) <=
1703
1704 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1705 auto &ListenerRef = *Listener;
1706 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1707 std::move(Listener));
1708
1709 // Try to load the module file.
1710 switch (TheASTReader->ReadAST(
1712 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1713 &LoadedModuleFile)) {
1714 case ASTReader::Success:
1715 // We successfully loaded the module file; remember the set of provided
1716 // modules so that we don't try to load implicit modules for them.
1717 ListenerRef.registerAll();
1718 return true;
1719
1721 // Ignore unusable module files.
1723 diag::warn_ast_file_config_mismatch)
1724 << FileName;
1725 // All modules provided by any files we tried and failed to load are now
1726 // unavailable; includes of those modules should now be handled textually.
1727 ListenerRef.markAllUnavailable();
1728 return true;
1729
1730 default:
1731 return false;
1732 }
1733}
1734
1735namespace {
1736enum ModuleSource {
1737 MS_ModuleNotFound,
1738 MS_ModuleCache,
1739 MS_PrebuiltModulePath,
1740 MS_ModuleBuildPragma
1741};
1742} // end namespace
1743
1744/// Select a source for loading the named module and compute the filename to
1745/// load it from.
1746static ModuleSource selectModuleSource(
1747 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1748 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1749 HeaderSearch &HS) {
1750 assert(ModuleFilename.empty() && "Already has a module source?");
1751
1752 // Check to see if the module has been built as part of this compilation
1753 // via a module build pragma.
1754 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1755 if (BuiltModuleIt != BuiltModules.end()) {
1756 ModuleFilename = BuiltModuleIt->second;
1757 return MS_ModuleBuildPragma;
1758 }
1759
1760 // Try to load the module from the prebuilt module path.
1761 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1762 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1763 !HSOpts.PrebuiltModulePaths.empty()) {
1764 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1765 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1766 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1767 if (!ModuleFilename.empty())
1768 return MS_PrebuiltModulePath;
1769 }
1770
1771 // Try to load the module from the module cache.
1772 if (M) {
1773 ModuleFilename = HS.getCachedModuleFileName(M);
1774 return MS_ModuleCache;
1775 }
1776
1777 return MS_ModuleNotFound;
1778}
1779
1780ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1781 StringRef ModuleName, SourceLocation ImportLoc, SourceRange ModuleNameRange,
1782 bool IsInclusionDirective) {
1783 // Search for a module with the given name.
1784 HeaderSearch &HS = PP->getHeaderSearchInfo();
1785 Module *M =
1786 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1787
1788 // Check for any configuration macros that have changed. This is done
1789 // immediately before potentially building a module in case this module
1790 // depends on having one of its configuration macros defined to successfully
1791 // build. If this is not done the user will never see the warning.
1792 if (M)
1793 checkConfigMacros(getPreprocessor(), M, ImportLoc);
1794
1795 // Select the source and filename for loading the named module.
1796 std::string ModuleFilename;
1797 ModuleSource Source =
1798 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1799 SourceLocation ModuleNameLoc = ModuleNameRange.getBegin();
1800 if (Source == MS_ModuleNotFound) {
1801 // We can't find a module, error out here.
1802 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1803 << ModuleName << ModuleNameRange;
1804 return nullptr;
1805 }
1806 if (ModuleFilename.empty()) {
1807 if (M && M->HasIncompatibleModuleFile) {
1808 // We tried and failed to load a module file for this module. Fall
1809 // back to textual inclusion for its headers.
1811 }
1812
1813 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1814 << ModuleName;
1815 return nullptr;
1816 }
1817
1818 // Create an ASTReader on demand.
1819 if (!getASTReader())
1821
1822 // Time how long it takes to load the module.
1823 llvm::Timer Timer;
1824 if (timerGroup)
1825 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
1826 *timerGroup);
1827 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1828 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1829
1830 // Try to load the module file. If we are not trying to load from the
1831 // module cache, we don't know how to rebuild modules.
1832 unsigned ARRFlags = Source == MS_ModuleCache
1835 : Source == MS_PrebuiltModulePath
1836 ? 0
1838 switch (getASTReader()->ReadAST(ModuleFilename,
1839 Source == MS_PrebuiltModulePath
1841 : Source == MS_ModuleBuildPragma
1844 ImportLoc, ARRFlags)) {
1845 case ASTReader::Success: {
1846 if (M)
1847 return M;
1848 assert(Source != MS_ModuleCache &&
1849 "missing module, but file loaded from cache");
1850
1851 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1852 // until the first call to ReadAST. Look it up now.
1853 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1854
1855 // Check whether M refers to the file in the prebuilt module path.
1856 if (M && M->getASTFile())
1857 if (auto ModuleFile = FileMgr->getOptionalFileRef(ModuleFilename))
1858 if (*ModuleFile == M->getASTFile())
1859 return M;
1860
1861 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
1862 << ModuleName;
1863 return ModuleLoadResult();
1864 }
1865
1867 case ASTReader::Missing:
1868 // The most interesting case.
1869 break;
1870
1872 if (Source == MS_PrebuiltModulePath)
1873 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1874 // produce a warning here!
1875 getDiagnostics().Report(SourceLocation(),
1876 diag::warn_ast_file_config_mismatch)
1877 << ModuleFilename;
1878 // Fall through to error out.
1879 [[fallthrough]];
1883 // FIXME: The ASTReader will already have complained, but can we shoehorn
1884 // that diagnostic information into a more useful form?
1885 return ModuleLoadResult();
1886
1887 case ASTReader::Failure:
1889 return ModuleLoadResult();
1890 }
1891
1892 // ReadAST returned Missing or OutOfDate.
1893 if (Source != MS_ModuleCache) {
1894 // We don't know the desired configuration for this module and don't
1895 // necessarily even have a module map. Since ReadAST already produces
1896 // diagnostics for these two cases, we simply error out here.
1897 return ModuleLoadResult();
1898 }
1899
1900 // The module file is missing or out-of-date. Build it.
1901 assert(M && "missing module, but trying to compile for cache");
1902
1903 // Check whether there is a cycle in the module graph.
1905 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1906 for (; Pos != PosEnd; ++Pos) {
1907 if (Pos->first == ModuleName)
1908 break;
1909 }
1910
1911 if (Pos != PosEnd) {
1912 SmallString<256> CyclePath;
1913 for (; Pos != PosEnd; ++Pos) {
1914 CyclePath += Pos->first;
1915 CyclePath += " -> ";
1916 }
1917 CyclePath += ModuleName;
1918
1919 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1920 << ModuleName << CyclePath;
1921 return nullptr;
1922 }
1923
1924 // Check whether we have already attempted to build this module (but failed).
1925 if (FailedModules.contains(ModuleName)) {
1926 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1927 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1928 return nullptr;
1929 }
1930
1931 // Try to compile and then read the AST.
1932 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
1933 ModuleFilename)) {
1934 assert(getDiagnostics().hasErrorOccurred() &&
1935 "undiagnosed error in compileModuleAndReadAST");
1936 FailedModules.insert(ModuleName);
1937 return nullptr;
1938 }
1939
1940 // Okay, we've rebuilt and now loaded the module.
1941 return M;
1942}
1943
1946 ModuleIdPath Path,
1948 bool IsInclusionDirective) {
1949 // Determine what file we're searching from.
1950 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
1951 SourceLocation ModuleNameLoc = Path[0].getLoc();
1952
1953 // If we've already handled this import, just return the cached result.
1954 // This one-element cache is important to eliminate redundant diagnostics
1955 // when both the preprocessor and parser see the same import declaration.
1956 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1957 // Make the named module visible.
1958 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1959 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
1960 ImportLoc);
1961 return LastModuleImportResult;
1962 }
1963
1964 // If we don't already have information on this module, load the module now.
1965 Module *Module = nullptr;
1967 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].getIdentifierInfo())) {
1968 // Use the cached result, which may be nullptr.
1969 Module = *MaybeModule;
1970 // Config macros are already checked before building a module, but they need
1971 // to be checked at each import location in case any of the config macros
1972 // have a new value at the current `ImportLoc`.
1973 if (Module)
1975 } else if (ModuleName == getLangOpts().CurrentModule) {
1976 // This is the module we're building.
1977 Module = PP->getHeaderSearchInfo().lookupModule(
1978 ModuleName, ImportLoc, /*AllowSearch*/ true,
1979 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
1980
1981 // Config macros do not need to be checked here for two reasons.
1982 // * This will always be textual inclusion, and thus the config macros
1983 // actually do impact the content of the header.
1984 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
1985 // function as the `#include` or `#import` is textual.
1986
1987 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
1988 } else {
1989 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
1990 Path.back().getIdentifierInfo()->getLength());
1991 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
1992 ModuleName, ImportLoc, SourceRange{ModuleNameLoc, ModuleNameEndLoc},
1993 IsInclusionDirective);
1994 if (!Result.isNormal())
1995 return Result;
1996 if (!Result)
1997 DisableGeneratingGlobalModuleIndex = true;
1998 Module = Result;
1999 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2000 }
2001
2002 // If we never found the module, fail. Otherwise, verify the module and link
2003 // it up.
2004 if (!Module)
2005 return ModuleLoadResult();
2006
2007 // Verify that the rest of the module path actually corresponds to
2008 // a submodule.
2009 bool MapPrivateSubModToTopLevel = false;
2010 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2011 StringRef Name = Path[I].getIdentifierInfo()->getName();
2012 clang::Module *Sub = Module->findSubmodule(Name);
2013
2014 // If the user is requesting Foo.Private and it doesn't exist, try to
2015 // match Foo_Private and emit a warning asking for the user to write
2016 // @import Foo_Private instead. FIXME: remove this when existing clients
2017 // migrate off of Foo.Private syntax.
2018 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2019 SmallString<128> PrivateModule(Module->Name);
2020 PrivateModule.append("_Private");
2021
2023 auto &II = PP->getIdentifierTable().get(
2024 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2025 PrivPath.emplace_back(Path[0].getLoc(), &II);
2026
2027 std::string FileName;
2028 // If there is a modulemap module or prebuilt module, load it.
2029 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2030 !IsInclusionDirective) ||
2031 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2032 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2033 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2034 if (Sub) {
2035 MapPrivateSubModToTopLevel = true;
2036 PP->markClangModuleAsAffecting(Module);
2037 if (!getDiagnostics().isIgnored(
2038 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2039 getDiagnostics().Report(Path[I].getLoc(),
2040 diag::warn_no_priv_submodule_use_toplevel)
2041 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2042 << PrivateModule
2043 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2044 << FixItHint::CreateReplacement(SourceRange(Path[0].getLoc()),
2045 PrivateModule);
2046 getDiagnostics().Report(Sub->DefinitionLoc,
2047 diag::note_private_top_level_defined);
2048 }
2049 }
2050 }
2051
2052 if (!Sub) {
2053 // Attempt to perform typo correction to find a module name that works.
2055 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2056
2057 for (class Module *SubModule : Module->submodules()) {
2058 unsigned ED =
2059 Name.edit_distance(SubModule->Name,
2060 /*AllowReplacements=*/true, BestEditDistance);
2061 if (ED <= BestEditDistance) {
2062 if (ED < BestEditDistance) {
2063 Best.clear();
2064 BestEditDistance = ED;
2065 }
2066
2067 Best.push_back(SubModule->Name);
2068 }
2069 }
2070
2071 // If there was a clear winner, user it.
2072 if (Best.size() == 1) {
2073 getDiagnostics().Report(Path[I].getLoc(),
2074 diag::err_no_submodule_suggest)
2075 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2076 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2077 << FixItHint::CreateReplacement(SourceRange(Path[I].getLoc()),
2078 Best[0]);
2079
2080 Sub = Module->findSubmodule(Best[0]);
2081 }
2082 }
2083
2084 if (!Sub) {
2085 // No submodule by this name. Complain, and don't look for further
2086 // submodules.
2087 getDiagnostics().Report(Path[I].getLoc(), diag::err_no_submodule)
2088 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2089 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2090 break;
2091 }
2092
2093 Module = Sub;
2094 }
2095
2096 // Make the named module visible, if it's not already part of the module
2097 // we are parsing.
2098 if (ModuleName != getLangOpts().CurrentModule) {
2099 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2100 // We have an umbrella header or directory that doesn't actually include
2101 // all of the headers within the directory it covers. Complain about
2102 // this missing submodule and recover by forgetting that we ever saw
2103 // this submodule.
2104 // FIXME: Should we detect this at module load time? It seems fairly
2105 // expensive (and rare).
2106 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2108 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2109
2111 }
2112
2113 // Check whether this module is available.
2115 *Module, getDiagnostics())) {
2116 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2117 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2118 LastModuleImportLoc = ImportLoc;
2119 LastModuleImportResult = ModuleLoadResult();
2120 return ModuleLoadResult();
2121 }
2122
2123 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2124 }
2125
2126 // Resolve any remaining module using export_as for this one.
2129 .getModuleMap()
2131
2132 LastModuleImportLoc = ImportLoc;
2133 LastModuleImportResult = ModuleLoadResult(Module);
2134 return LastModuleImportResult;
2135}
2136
2138 StringRef ModuleName,
2139 StringRef Source) {
2140 // Avoid creating filenames with special characters.
2141 SmallString<128> CleanModuleName(ModuleName);
2142 for (auto &C : CleanModuleName)
2143 if (!isAlphanumeric(C))
2144 C = '_';
2145
2146 // FIXME: Using a randomized filename here means that our intermediate .pcm
2147 // output is nondeterministic (as .pcm files refer to each other by name).
2148 // Can this affect the output in any way?
2149 SmallString<128> ModuleFileName;
2150 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2151 CleanModuleName, "pcm", ModuleFileName)) {
2152 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2153 << ModuleFileName << EC.message();
2154 return;
2155 }
2156 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2157
2158 FrontendInputFile Input(
2159 ModuleMapFileName,
2160 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2161 InputKind::ModuleMap, /*Preprocessed*/true));
2162
2163 std::string NullTerminatedSource(Source.str());
2164
2165 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2166 StringRef(), ModuleFileName);
2167
2168 // Create a virtual file containing our desired source.
2169 // FIXME: We shouldn't need to do this.
2170 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2171 ModuleMapFileName, NullTerminatedSource.size(), 0);
2172 Other->getSourceManager().overrideFileContents(
2173 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2174
2175 Other->BuiltModules = std::move(BuiltModules);
2176 Other->DeleteBuiltModules = false;
2177
2178 // Build the module, inheriting any modules that we've built locally.
2179 bool Success = compileModule(ImportLoc, ModuleName, ModuleFileName, *Other);
2180
2181 BuiltModules = std::move(Other->BuiltModules);
2182
2183 if (Success) {
2184 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2185 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2186 }
2187}
2188
2191 SourceLocation ImportLoc) {
2192 if (!TheASTReader)
2194 if (!TheASTReader)
2195 return;
2196
2197 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2198}
2199
2201 SourceLocation TriggerLoc) {
2202 if (getPreprocessor()
2203 .getHeaderSearchInfo()
2205 .empty())
2206 return nullptr;
2207 if (!TheASTReader)
2209 // Can't do anything if we don't have the module manager.
2210 if (!TheASTReader)
2211 return nullptr;
2212 // Get an existing global index. This loads it if not already
2213 // loaded.
2214 TheASTReader->loadGlobalIndex();
2215 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2216 // If the global index doesn't exist, create it.
2217 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2218 hasPreprocessor()) {
2219 llvm::sys::fs::create_directories(
2220 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2221 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2224 .getHeaderSearchInfo()
2226 // FIXME this drops the error on the floor. This code is only used for
2227 // typo correction and drops more than just this one source of errors
2228 // (such as the directory creation failure above). It should handle the
2229 // error.
2230 consumeError(std::move(Err));
2231 return nullptr;
2232 }
2233 TheASTReader->resetForReload();
2234 TheASTReader->loadGlobalIndex();
2235 GlobalIndex = TheASTReader->getGlobalIndex();
2236 }
2237 // For finding modules needing to be imported for fixit messages,
2238 // we need to make the global index cover all modules, so we do that here.
2239 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2241 bool RecreateIndex = false;
2243 E = MMap.module_end(); I != E; ++I) {
2244 Module *TheModule = I->second;
2245 OptionalFileEntryRef Entry = TheModule->getASTFile();
2246 if (!Entry) {
2248 Path.emplace_back(TriggerLoc,
2249 getPreprocessor().getIdentifierInfo(TheModule->Name));
2250 std::reverse(Path.begin(), Path.end());
2251 // Load a module as hidden. This also adds it to the global index.
2252 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2253 RecreateIndex = true;
2254 }
2255 }
2256 if (RecreateIndex) {
2257 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2260 .getHeaderSearchInfo()
2262 // FIXME As above, this drops the error on the floor.
2263 consumeError(std::move(Err));
2264 return nullptr;
2265 }
2266 TheASTReader->resetForReload();
2267 TheASTReader->loadGlobalIndex();
2268 GlobalIndex = TheASTReader->getGlobalIndex();
2269 }
2270 HaveFullGlobalModuleIndex = true;
2271 }
2272 return GlobalIndex;
2273}
2274
2275// Check global module index for missing imports.
2276bool
2278 SourceLocation TriggerLoc) {
2279 // Look for the symbol in non-imported modules, but only if an error
2280 // actually occurred.
2281 if (!buildingModule()) {
2282 // Load global module index, or retrieve a previously loaded one.
2284 TriggerLoc);
2285
2286 // Only if we have a global index.
2287 if (GlobalIndex) {
2288 GlobalModuleIndex::HitSet FoundModules;
2289
2290 // Find the modules that reference the identifier.
2291 // Note that this only finds top-level modules.
2292 // We'll let diagnoseTypo find the actual declaration module.
2293 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2294 return true;
2295 }
2296 }
2297
2298 return false;
2299}
2300void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2301
2304 ExternalSemaSrc = std::move(ESS);
2305}
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...
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
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 computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
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:25
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:749
module_iterator module_begin() const
Definition ModuleMap.h:751
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:763
module_iterator module_end() const
Definition ModuleMap.h:752
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:758
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:856
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.
SourceLocation getBegin() const
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:806
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.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ PluginAction
Run a plugin action,.
@ RewriteObjC
ObjC->C Rewriter.
bool Inv(InterpState &S, CodePtr OpPC)
Definition Interp.h:671
@ 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
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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
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.