clang 24.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"
22#include "clang/Basic/Stack.h"
24#include "clang/Basic/Version.h"
25#include "clang/Config/config.h"
42#include "clang/Sema/Sema.h"
49#include "llvm/ADT/IntrusiveRefCntPtr.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/Statistic.h"
52#include "llvm/Config/llvm-config.h"
53#include "llvm/Plugins/PassPlugin.h"
54#include "llvm/Support/AdvisoryLock.h"
55#include "llvm/Support/BuryPointer.h"
56#include "llvm/Support/CrashRecoveryContext.h"
57#include "llvm/Support/FileSystem.h"
58#include "llvm/Support/MemoryBuffer.h"
59#include "llvm/Support/Path.h"
60#include "llvm/Support/Signals.h"
61#include "llvm/Support/SmallVectorMemoryBuffer.h"
62#include "llvm/Support/Threading.h"
63#include "llvm/Support/TimeProfiler.h"
64#include "llvm/Support/Timer.h"
65#include "llvm/Support/VirtualFileSystem.h"
66#include "llvm/Support/VirtualOutputBackends.h"
67#include "llvm/Support/VirtualOutputError.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/TargetParser/Host.h"
70#include <optional>
71#include <time.h>
72#include <utility>
73
74using namespace clang;
75
76CompilerInstance::CompilerInstance(
77 std::shared_ptr<CompilerInvocation> Invocation,
78 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
79 std::shared_ptr<ModuleCache> ModCache)
80 : ModuleLoader(/*BuildingModule=*/ModCache != nullptr),
81 Invocation(std::move(Invocation)),
82 ModCache(ModCache ? std::move(ModCache)
84 ThePCHContainerOperations(std::move(PCHContainerOps)) {
85 assert(this->Invocation && "Invocation must not be null");
86}
87
89 assert(OutputFiles.empty() && "Still output files in flight?");
90}
91
93 return (BuildGlobalModuleIndex ||
94 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
95 getFrontendOpts().GenerateGlobalModuleIndex)) &&
96 !DisableGeneratingGlobalModuleIndex;
97}
98
103
105 OwnedVerboseOutputStream.reset();
106 VerboseOutputStream = &Value;
107}
108
109void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
110 OwnedVerboseOutputStream.swap(Value);
111 VerboseOutputStream = OwnedVerboseOutputStream.get();
112}
113
116
118 // Create the target instance.
121 if (!hasTarget())
122 return false;
123
124 if (getLangOpts().SYCLIsDevice && !getTarget().getTriple().isGPU()) {
125 getDiagnostics().Report(diag::err_sycl_device_invalid_target)
126 << getTarget().getTriple().str();
127 return false;
128 }
129
130 // Check whether AuxTarget exists, if not, then create TargetInfo for the
131 // other side of CUDA/OpenMP/SYCL compilation.
132 if (!getAuxTarget() &&
133 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
134 !getFrontendOpts().AuxTriple.empty()) {
135 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
136 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
137 if (getFrontendOpts().AuxTargetCPU)
138 TO->CPU = *getFrontendOpts().AuxTargetCPU;
139 if (getFrontendOpts().AuxTargetFeatures)
140 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
141 TO->HostTriple = getTarget().getTriple().str();
143 }
144
145 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
146 if (getLangOpts().RoundingMath) {
147 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
148 getLangOpts().RoundingMath = false;
149 }
150 auto FPExc = getLangOpts().getFPExceptionMode();
151 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
152 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
153 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
154 }
155 // FIXME: can we disable FEnvAccess?
156 }
157
158 // We should do it here because target knows nothing about
159 // language options when it's being created.
160 if (getLangOpts().OpenCL &&
161 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
162 return false;
163
164 // Inform the target of the language options.
165 // FIXME: We shouldn't need to do this, the target should be immutable once
166 // created. This complexity should be lifted elsewhere.
168
169 if (auto *Aux = getAuxTarget()) {
170 if (getLangOpts().CUDAIsDevice) {
171 // The host's alignment rules depend on its language options, such as
172 // -fclang-abi-compat. Adjust the host before the device copies them.
173 LangOptions HostLangOpts = getLangOpts();
174 HostLangOpts.CUDAIsDevice = false;
175 Aux->adjust(getDiagnostics(), HostLangOpts, &getTarget());
176 }
177 getTarget().setAuxTarget(Aux);
178 }
179
180 return true;
181}
182
184 assert(Value == nullptr ||
185 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
186 FileMgr = std::move(Value);
187}
188
193
194void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
195 PP = std::move(Value);
196}
197
199 assert(Context && "Compiler instance has no AST context!");
200 return Context;
201}
202
205 Context = std::move(Value);
206
207 if (Context && Consumer)
209}
210
212 TheSema.reset(S);
213}
214
215void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
216 Consumer = std::move(Value);
217
218 if (Context && Consumer)
220}
221
225
226std::unique_ptr<Sema> CompilerInstance::takeSema() {
227 return std::move(TheSema);
228}
229
231 return TheASTReader;
232}
234 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
235 "Expected ASTReader to use the same PCM cache");
236 TheASTReader = std::move(Reader);
237}
238
239std::shared_ptr<ModuleDependencyCollector>
241 return ModuleDepCollector;
242}
243
245 std::shared_ptr<ModuleDependencyCollector> Collector) {
246 ModuleDepCollector = std::move(Collector);
247}
248
249static void collectHeaderMaps(const HeaderSearch &HS,
250 std::shared_ptr<ModuleDependencyCollector> MDC) {
251 SmallVector<std::string, 4> HeaderMapFileNames;
252 HS.getHeaderMapFileNames(HeaderMapFileNames);
253 for (auto &Name : HeaderMapFileNames)
254 MDC->addFile(Name);
255}
256
258 std::shared_ptr<ModuleDependencyCollector> MDC) {
259 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
260 if (PPOpts.ImplicitPCHInclude.empty())
261 return;
262
263 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
265 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
266 if (!PCHDir) {
267 MDC->addFile(PCHInclude);
268 return;
269 }
270
271 std::error_code EC;
272 SmallString<128> DirNative;
273 llvm::sys::path::native(PCHDir->getName(), DirNative);
274 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
276 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
277 Dir != DirEnd && !EC; Dir.increment(EC)) {
278 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
279 // used here since we're not interested in validating the PCH at this time,
280 // but only to check whether this is a file containing an AST.
282 Dir->path(), FileMgr, CI.getModuleCache(),
284 /*FindModuleFileExtensions=*/false, Validator,
285 /*ValidateDiagnosticOptions=*/false))
286 MDC->addFile(Dir->path());
287 }
288}
289
291 std::shared_ptr<ModuleDependencyCollector> MDC) {
292 // Collect all VFS found.
294 CI.getVirtualFileSystem().visit([&](llvm::vfs::FileSystem &VFS) {
295 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(&VFS))
296 llvm::vfs::collectVFSEntries(*RedirectingVFS, VFSEntries);
297 });
298
299 for (auto &E : VFSEntries)
300 MDC->addFile(E.VPath, E.RPath);
301}
302
305 bool ShouldOwnClient = false;
306 if (!DC) {
307 DC = new DiagnosticConsumer;
308 ShouldOwnClient = true;
309 }
310
311 DiagnosticOptions DiagOpts;
312 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
313 ShouldOwnClient);
314
316 std::move(BaseFS));
317 // FIXME: Should this go into createVFSFromCompilerInvocation?
318 if (getFrontendOpts().ShowStats)
319 VFS =
320 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(std::move(VFS));
321}
322
323// Diagnostics
325 const CodeGenOptions *CodeGenOpts,
326 DiagnosticsEngine &Diags) {
327 std::error_code EC;
328 std::unique_ptr<raw_ostream> StreamOwner;
329 raw_ostream *OS = &llvm::errs();
330 if (DiagOpts.DiagnosticLogFile != "-") {
331 // Create the output stream.
332 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
333 DiagOpts.DiagnosticLogFile, EC,
334 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
335 if (EC) {
336 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
337 << DiagOpts.DiagnosticLogFile << EC.message();
338 } else {
339 FileOS->SetUnbuffered();
340 OS = FileOS.get();
341 StreamOwner = std::move(FileOS);
342 }
343 }
344
345 // Chain in the diagnostic client which will log the diagnostics.
346 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
347 std::move(StreamOwner));
348 if (CodeGenOpts)
349 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
350 if (Diags.ownsClient()) {
351 Diags.setClient(
352 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
353 } else {
354 Diags.setClient(
355 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
356 }
357}
358
360 DiagnosticsEngine &Diags,
361 StringRef OutputFile) {
362 auto SerializedConsumer =
363 clang::serialized_diags::create(OutputFile, DiagOpts);
364
365 if (Diags.ownsClient()) {
367 Diags.takeClient(), std::move(SerializedConsumer)));
368 } else {
370 Diags.getClient(), std::move(SerializedConsumer)));
371 }
372}
373
375 bool ShouldOwnClient) {
377 Client, ShouldOwnClient, &getCodeGenOpts());
378}
379
381 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
382 DiagnosticConsumer *Client, bool ShouldOwnClient,
383 const CodeGenOptions *CodeGenOpts) {
384 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
385 DiagnosticIDs::create(), Opts);
386
387 // Create the diagnostic client for reporting errors or for
388 // implementing -verify.
389 if (Client) {
390 Diags->setClient(Client, ShouldOwnClient);
391 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
392 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
393 } else
394 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
395
396 // Chain in -verify checker, if requested.
397 if (Opts.VerifyDiagnostics)
398 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
399
400 // Chain in -diagnostic-log-file dumper, if requested.
401 if (!Opts.DiagnosticLogFile.empty())
402 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
403
404 if (!Opts.DiagnosticSerializationFile.empty())
406
407 // Configure our handling of diagnostics.
408 ProcessWarningOptions(*Diags, Opts, VFS);
409
410 return Diags;
411}
412
413// File Manager
414
416 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
417 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(getFileSystemOpts(), VFS);
418}
419
420// Source Manager
421
423 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
424 assert(FileMgr && "FileManager needed for creating SourceManager");
425 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(getDiagnostics(),
427}
428
429// Initialize the remapping of files to alternative contents, e.g.,
430// those specified through other files.
432 SourceManager &SourceMgr,
434 const PreprocessorOptions &InitOpts) {
435 // Remap files in the source manager (with buffers).
436 for (const auto &RB : InitOpts.RemappedFileBuffers) {
437 // Create the file entry for the file that we're mapping from.
438 FileEntryRef FromFile =
439 FileMgr.getVirtualFileRef(RB.first, RB.second->getBufferSize(), 0);
440
441 // Override the contents of the "from" file with the contents of the
442 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
443 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
444 // to the SourceManager.
445 if (InitOpts.RetainRemappedFileBuffers)
446 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
447 else
448 SourceMgr.overrideFileContents(
449 FromFile, std::unique_ptr<llvm::MemoryBuffer>(RB.second));
450 }
451
452 // Remap files in the source manager (with other files).
453 for (const auto &RF : InitOpts.RemappedFiles) {
454 // Find the file that we're mapping to.
455 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
456 if (!ToFile) {
457 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
458 continue;
459 }
460
461 // Create the file entry for the file that we're mapping from.
462 FileEntryRef FromFile =
463 FileMgr.getVirtualFileRef(RF.first, ToFile->getSize(), 0);
464
465 // Override the contents of the "from" file with the contents of
466 // the "to" file.
467 SourceMgr.overrideFileContents(FromFile, *ToFile);
468 }
469
470 SourceMgr.setOverridenFilesKeepOriginalName(
472}
473
474// Preprocessor
475
478
479 // The AST reader holds a reference to the old preprocessor (if any).
480 TheASTReader.reset();
481
482 // Create the Preprocessor.
483 HeaderSearch *HeaderInfo =
486 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOpts(),
488 getSourceManager(), *HeaderInfo, *this,
489 /*IdentifierInfoLookup=*/nullptr,
490 /*OwnsHeaderSearch=*/true, TUKind);
492 if (!SharedBuiltins)
493 SharedBuiltins = std::make_shared<const Builtin::TargetBuiltins>(
495 PP->Initialize(getTarget(), getAuxTarget(), SharedBuiltins);
496
497 if (PPOpts.DetailedRecord)
498 PP->createPreprocessingRecord();
499
500 // Apply remappings to the source manager.
501 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
502 PP->getFileManager(), PPOpts);
503
504 // Predefine macros and configure the preprocessor.
507
508 // Initialize the header search object. In CUDA compilations, we use the aux
509 // triple (the host triple) to initialize our header search, since we need to
510 // find the host headers in order to compile the CUDA code.
511 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
512 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
513 PP->getAuxTargetInfo())
514 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
515
516 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
517 PP->getLangOpts(), *HeaderSearchTriple);
518
519 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
520
521 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
522 // FIXME: We already might've computed the context hash and the specific
523 // module cache path in `FrontendAction::BeginSourceFile()` when turning
524 // "-include-pch <DIR>" into "-include-pch <DIR>/<FILE>". Reuse those here.
525 PP->getHeaderSearchInfo().initializeModuleCachePath(
526 getInvocation().computeContextHash());
527 }
528
529 // Handle generating dependencies, if requested.
531 if (!DepOpts.OutputFile.empty())
532 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
533 if (!DepOpts.DOTOutputFile.empty())
535 getHeaderSearchOpts().Sysroot);
536
537 // If we don't have a collector, but we are collecting module dependencies,
538 // then we're the top level compiler instance and need to create one.
539 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
540 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
542 }
543
544 // If there is a module dep collector, register with other dep collectors
545 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
546 if (ModuleDepCollector) {
547 addDependencyCollector(ModuleDepCollector);
548 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
549 collectIncludePCH(*this, ModuleDepCollector);
550 collectVFSEntries(*this, ModuleDepCollector);
551 }
552
553 // Modules need an output manager.
554 if (!hasOutputManager())
556
557 for (auto &Listener : DependencyCollectors)
558 Listener->attachToPreprocessor(*PP);
559
560 // Handle generating header include information, if requested.
561 if (DepOpts.ShowHeaderIncludes)
562 AttachHeaderIncludeGen(*PP, DepOpts);
563 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
564 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
565 if (OutputPath == "-")
566 OutputPath = "";
567 AttachHeaderIncludeGen(*PP, DepOpts,
568 /*ShowAllHeaders=*/true, OutputPath,
569 /*ShowDepth=*/false);
570 }
571
573 AttachHeaderIncludeGen(*PP, DepOpts,
574 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
575 /*ShowDepth=*/true, /*MSStyle=*/true);
576 }
577
578 if (GetDependencyDirectives)
579 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
580
582 PP->getTextEncoding(), getLangOpts(), getTarget()))
583 PP->getDiagnostics().Report(clang::diag::err_fe_text_encoding_config)
584 << PP->getTextEncoding().getLiteralEncoding();
585}
586
587// ASTContext
588
591 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
592 getLangOpts(), PP.getSourceManager(), PP.getIdentifierTable(),
593 PP.getSelectorTable(), PP.getBuiltinInfo(), PP.TUKind);
594 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
595 setASTContext(std::move(Context));
596}
597
598// ExternalASTSource
599
600namespace {
601// Helper to recursively read the module names for all modules we're adding.
602// We mark these as known and redirect any attempt to load that module to
603// the files we were handed.
604struct ReadModuleNames : ASTReaderListener {
605 Preprocessor &PP;
607
608 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
609
610 void ReadModuleName(StringRef ModuleName) override {
611 // Keep the module name as a string for now. It's not safe to create a new
612 // IdentifierInfo from an ASTReader callback.
613 LoadedModules.push_back(ModuleName.str());
614 }
615
616 void registerAll() {
617 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
618 for (const std::string &LoadedModule : LoadedModules)
619 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
620 MM.findOrLoadModule(LoadedModule));
621 LoadedModules.clear();
622 }
623
624 void markAllUnavailable() {
625 for (const std::string &LoadedModule : LoadedModules) {
627 LoadedModule)) {
628 M->HasIncompatibleModuleFile = true;
629
630 // Mark module as available if the only reason it was unavailable
631 // was missing headers.
632 SmallVector<Module *, 2> Stack;
633 Stack.push_back(M);
634 while (!Stack.empty()) {
635 Module *Current = Stack.pop_back_val();
636 if (Current->IsUnimportable) continue;
637 Current->IsAvailable = true;
638 auto SubmodulesRange = Current->submodules();
639 llvm::append_range(Stack, SubmodulesRange);
640 }
641 }
642 }
643 LoadedModules.clear();
644 }
645};
646} // namespace
647
649 StringRef Path, DisableValidationForModuleKind DisableValidation,
650 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
651 bool OwnDeserializationListener) {
653 TheASTReader = createPCHExternalASTSource(
654 Path, getHeaderSearchOpts().Sysroot, DisableValidation,
655 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
657 getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
658 DeserializationListener, OwnDeserializationListener, Preamble,
659 getFrontendOpts().UseGlobalModuleIndex);
660}
661
663 StringRef Path, StringRef Sysroot,
664 DisableValidationForModuleKind DisableValidation,
665 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
666 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
667 const CodeGenOptions &CodeGenOpts,
668 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
669 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
670 void *DeserializationListener, bool OwnDeserializationListener,
671 bool Preamble, bool UseGlobalModuleIndex) {
672 const HeaderSearchOptions &HSOpts =
673 PP.getHeaderSearchInfo().getHeaderSearchOpts();
674
675 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
676 PP, ModCache, &Context, PCHContainerRdr, CodeGenOpts, Extensions,
677 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
678 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
681 HSOpts.ValidateASTInputFilesContent, UseGlobalModuleIndex);
682
683 // We need the external source to be set up before we read the AST, because
684 // eagerly-deserialized declarations may use it.
685 Context.setExternalSource(Reader);
686
687 Reader->setDeserializationListener(
688 static_cast<ASTDeserializationListener *>(DeserializationListener),
689 /*TakeOwnership=*/OwnDeserializationListener);
690
691 for (auto &Listener : DependencyCollectors)
692 Listener->attachToASTReader(*Reader);
693
694 auto Listener = std::make_unique<ReadModuleNames>(PP);
695 auto &ListenerRef = *Listener;
696 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
697 std::move(Listener));
698
699 switch (Reader->ReadAST(ModuleFileName::makeExplicit(Path),
704 // Set the predefines buffer as suggested by the PCH reader. Typically, the
705 // predefines buffer will be empty.
706 PP.setPredefines(Reader->getSuggestedPredefines());
707 ListenerRef.registerAll();
708 return Reader;
709
711 // Unrecoverable failure: don't even try to process the input file.
712 break;
713
719 // No suitable PCH file could be found. Return an error.
720 break;
721 }
722
723 ListenerRef.markAllUnavailable();
724 Context.setExternalSource(nullptr);
725 return nullptr;
726}
727
728// Code Completion
729
731 StringRef Filename,
732 unsigned Line,
733 unsigned Column) {
734 // Tell the source manager to chop off the given file at a specific
735 // line and column.
736 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
737 if (!Entry) {
738 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
739 << Filename;
740 return true;
741 }
742
743 // Truncate the named file at the given line/column.
745 return false;
746}
747
750 if (!CompletionConsumer) {
752 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
753 getFrontendOpts().CodeCompleteOpts, llvm::outs()));
754 return;
756 Loc.Line, Loc.Column)) {
758 return;
759 }
760}
761
763 timerGroup.reset(new llvm::TimerGroup("clang", "Clang time report"));
764 FrontendTimer.reset(new llvm::Timer("frontend", "Front end", *timerGroup));
765}
766
769 StringRef Filename,
770 unsigned Line,
771 unsigned Column,
772 const CodeCompleteOptions &Opts,
773 raw_ostream &OS) {
774 if (EnableCodeCompletion(PP, Filename, Line, Column))
775 return nullptr;
776
777 // Set up the creation routine for code-completion.
778 return new PrintingCodeCompleteConsumer(Opts, OS);
779}
780
782 CodeCompleteConsumer *CompletionConsumer) {
783 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
784 TUKind, CompletionConsumer));
785
786 // Set up API notes.
787 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
788
789 // Attach the external sema source if there is any.
790 if (ExternalSemaSrc) {
791 TheSema->addExternalSource(ExternalSemaSrc);
792 ExternalSemaSrc->InitializeSema(*TheSema);
793 }
794
795 // If we're building a module and are supposed to load API notes,
796 // notify the API notes manager.
797 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
798 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
799 currentModule, getLangOpts().APINotesModules,
800 getAPINotesOpts().ModuleSearchPaths);
801 }
802}
803
804// Output Files
805
807 // The ASTConsumer can own streams that write to the output files.
808 assert(!hasASTConsumer() && "ASTConsumer should be reset");
809 if (!EraseFiles) {
810 for (auto &O : OutputFiles)
811 llvm::handleAllErrors(
812 O.keep(),
813 [&](const llvm::vfs::TempFileOutputError &E) {
814 getDiagnostics().Report(diag::err_unable_to_rename_temp)
815 << E.getTempPath() << E.getOutputPath()
816 << E.convertToErrorCode().message();
817 },
818 [&](const llvm::vfs::OutputError &E) {
819 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
820 << E.getOutputPath() << E.convertToErrorCode().message();
821 },
822 [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
823 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
824 << O.getPath() << EIB.message();
825 });
826 }
827 OutputFiles.clear();
828 if (DeleteBuiltModules) {
829 for (auto &Module : BuiltModules)
830 llvm::sys::fs::remove(Module.second);
831 BuiltModules.clear();
832 }
833}
834
835std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
836 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
837 bool CreateMissingDirectories, bool ForceUseTemporary,
838 bool SetOnlyIfDifferent) {
839 StringRef OutputPath = getFrontendOpts().OutputFile;
840 std::optional<SmallString<128>> PathStorage;
841 if (OutputPath.empty()) {
842 if (InFile == "-" || Extension.empty()) {
843 OutputPath = "-";
844 } else {
845 PathStorage.emplace(InFile);
846 llvm::sys::path::replace_extension(*PathStorage, Extension);
847 OutputPath = *PathStorage;
848 }
849 }
850
851 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
852 getFrontendOpts().UseTemporary || ForceUseTemporary,
853 CreateMissingDirectories, SetOnlyIfDifferent);
854}
855
856std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
857 return std::make_unique<llvm::raw_null_ostream>();
858}
859
860// Output Manager
861
864 assert(!OutputMgr && "Already has an output manager");
865 OutputMgr = std::move(NewOutputs);
866}
867
869 assert(!OutputMgr && "Already has an output manager");
870 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
871}
872
873llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
874 assert(OutputMgr);
875 return *OutputMgr;
876}
877
879 if (!hasOutputManager())
881 return getOutputManager();
882}
883
884std::unique_ptr<raw_pwrite_stream> CompilerInstance::createOutputFile(
885 StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
886 bool UseTemporary, bool CreateMissingDirectories, bool SetOnlyIfDifferent) {
888 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
889 CreateMissingDirectories, SetOnlyIfDifferent);
890 if (OS)
891 return std::move(*OS);
892 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
893 << OutputPath << errorToErrorCode(OS.takeError()).message();
894 return nullptr;
895}
896
898CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
899 bool RemoveFileOnSignal,
900 bool UseTemporary,
901 bool CreateMissingDirectories,
902 bool SetOnlyIfDifferent) {
903 assert((!CreateMissingDirectories || UseTemporary) &&
904 "CreateMissingDirectories is only allowed when using temporary files");
905
906 // If '-working-directory' was passed, the output filename should be
907 // relative to that.
908 std::optional<SmallString<128>> AbsPath;
909 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
910 assert(hasFileManager() &&
911 "File Manager is required to fix up relative path.\n");
912
913 AbsPath.emplace(OutputPath);
915 OutputPath = *AbsPath;
916 }
917
918 using namespace llvm::vfs;
920 OutputPath,
921 OutputConfig()
922 .setTextWithCRLF(!Binary)
923 .setDiscardOnSignal(RemoveFileOnSignal)
924 .setAtomicWrite(UseTemporary)
925 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories)
926 .setOnlyIfDifferent(SetOnlyIfDifferent));
927 if (!O)
928 return O.takeError();
929
930 O->discardOnDestroy([](llvm::Error E) { consumeError(std::move(E)); });
931 OutputFiles.push_back(std::move(*O));
932 return OutputFiles.back().createProxy();
933}
934
935// Initialization Utilities
936
941
942// static
944 DiagnosticsEngine &Diags,
945 FileManager &FileMgr,
946 SourceManager &SourceMgr) {
948 Input.getKind().getFormat() == InputKind::ModuleMap
949 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
951 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
952
953 if (Input.isBuffer()) {
954 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
955 assert(SourceMgr.getMainFileID().isValid() &&
956 "Couldn't establish MainFileID!");
957 return true;
958 }
959
960 StringRef InputFile = Input.getFile();
961
962 // Figure out where to get and map in the main file.
963 auto FileOrErr = InputFile == "-"
964 ? FileMgr.getSTDIN()
965 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
966 if (!FileOrErr) {
967 auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
968 if (InputFile != "-")
969 Diags.Report(diag::err_fe_error_reading) << InputFile << EC.message();
970 else
971 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
972 return false;
973 }
974
975 SourceMgr.setMainFileID(
976 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
977
978 assert(SourceMgr.getMainFileID().isValid() &&
979 "Couldn't establish MainFileID!");
980 return true;
981}
982
983// High-Level Operations
984
985void CompilerInstance::PrepareForExecution() {
986 // Set up the frontend timer for -ftime-report. BackendConsumer uses
987 // getTimerGroup() and getFrontendTimer() when TimePasses is set. In the
988 // cc1 driver path this was done in cc1_main before calling
989 // ExecuteCompilerInvocation; we consolidate it here so that all tools
990 // (cc1, clang-repl, libclang, etc.) get consistent behavior.
991 if (getCodeGenOpts().TimePasses && !FrontendTimer) {
993 getFrontendTimer().startTimer();
994 }
995
996 // FIXME: Consider consolidating additional per-instance setup here:
997 // - llvm::timeTraceProfilerInitialize) when TimeTracePath is set.
998 // - Plugin loading (LoadRequestedPlugins) and -mllvm argument processing.
999}
1000
1002 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
1003 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
1004 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
1005
1006 llvm::TimeTraceScope TimeScope("ExecuteCompiler");
1007
1008 PrepareForExecution();
1009
1010 // Mark this point as the bottom of the stack if we don't have somewhere
1011 // better. We generally expect frontend actions to be invoked with (nearly)
1012 // DesiredStackSpace available.
1014
1015 raw_ostream &OS = getVerboseOutputStream();
1016
1017 if (!Act.PrepareToExecute(*this))
1018 return false;
1019
1020 if (!createTarget())
1021 return false;
1022
1023 // rewriter project will change target built-in bool type from its default.
1024 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1026
1027 // Validate/process some options.
1028 if (getHeaderSearchOpts().Verbose)
1029 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
1030 << LLVM_VERSION_STRING << " default target "
1031 << llvm::sys::getDefaultTargetTriple() << "\n";
1032
1033 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
1034 llvm::EnableStatistics(false);
1035
1036 // Sort vectors containing toc data and no toc data variables to facilitate
1037 // binary search later.
1038 llvm::sort(getCodeGenOpts().TocDataVarsUserSpecified);
1039 llvm::sort(getCodeGenOpts().NoTocDataVars);
1040
1041 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
1042 // Reset the ID tables if we are reusing the SourceManager and parsing
1043 // regular files.
1044 if (hasSourceManager() && !Act.isModelParsingAction())
1046
1047 ModuleImportResults.clear();
1048
1049 if (Act.BeginSourceFile(*this, FIF)) {
1050 if (llvm::Error Err = Act.Execute()) {
1051 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1052 }
1053 Act.EndSourceFile();
1054 }
1055 }
1056
1058
1059 if (getFrontendOpts().ShowStats) {
1060 if (hasFileManager()) {
1062 OS << '\n';
1063 }
1064 llvm::PrintStatistics(OS);
1065 }
1066 StringRef StatsFile = getFrontendOpts().StatsFile;
1067 if (!StatsFile.empty()) {
1068 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1069 if (getFrontendOpts().AppendStats)
1070 FileFlags |= llvm::sys::fs::OF_Append;
1071 std::error_code EC;
1072 auto StatS =
1073 std::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, FileFlags);
1074 if (EC) {
1075 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
1076 << StatsFile << EC.message();
1077 } else {
1078 llvm::PrintStatisticsJSON(*StatS);
1079 }
1080 }
1081
1082 return !getDiagnostics().getClient()->getNumErrors();
1083}
1084
1086 if (!getDiagnosticOpts().ShowCarets)
1087 return;
1088
1089 raw_ostream &OS = getVerboseOutputStream();
1090
1091 // We can have multiple diagnostics sharing one diagnostic client.
1092 // Get the total number of warnings/errors from the client.
1093 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1094 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1095
1096 if (NumWarnings)
1097 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1098 if (NumWarnings && NumErrors)
1099 OS << " and ";
1100 if (NumErrors)
1101 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1102 if (NumWarnings || NumErrors) {
1103 OS << " generated";
1104 if (getLangOpts().CUDA) {
1105 if (!getLangOpts().CUDAIsDevice) {
1106 OS << " when compiling for host";
1107 } else {
1108 OS << " when compiling for "
1109 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1110 : getTarget().getTriple().str());
1111 }
1112 }
1113 OS << ".\n";
1114 }
1115}
1116
1118 // Load any requested plugins.
1119 for (const std::string &Path : getFrontendOpts().Plugins) {
1120 std::string Error;
1121 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
1122 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1123 << Path << Error;
1124 }
1125
1126 // Load and store pass plugins for the back-end.
1127 for (const std::string &Path : getCodeGenOpts().PassPlugins) {
1128 if (auto PassPlugin = llvm::PassPlugin::load(Path)) {
1129 PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
1130 } else {
1131 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
1132 << Path << toString(PassPlugin.takeError());
1133 }
1134 }
1135
1136 // Check if any of the loaded plugins replaces the main AST action
1137 for (const FrontendPluginRegistry::entry &Plugin :
1138 FrontendPluginRegistry::entries()) {
1139 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1140 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1142 getFrontendOpts().ActionName = Plugin.getName().str();
1143 break;
1144 }
1145 }
1146}
1147
1148bool CompilerInstance::parseLLVMArgs(raw_ostream *Errs) {
1149 const std::vector<std::string> &LLVMArgs = getFrontendOpts().LLVMArgs;
1150 if (LLVMArgs.empty())
1151 return true;
1152 SmallVector<const char *> Args = {"clang (LLVM option parsing)"};
1153 for (const std::string &Arg : LLVMArgs)
1154 Args.push_back(Arg.c_str());
1155 return llvm::cl::parseCommandLineOptions(LibraryOptions, Args,
1156 /*Overview=*/"", Errs,
1158}
1159
1160/// Determine the appropriate source input kind based on language
1161/// options.
1163 if (LangOpts.OpenCL)
1164 return Language::OpenCL;
1165 if (LangOpts.CUDA)
1166 return Language::CUDA;
1167 if (LangOpts.ObjC)
1168 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1169 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1170}
1171
1172std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1173 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1174 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1175 ArrayRef<std::string> DirectoryDependencies,
1176 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1177 // Construct a compiler invocation for creating this module.
1178 auto Invocation = std::make_shared<CompilerInvocation>(getInvocation());
1179
1180 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1181
1182 // For any options that aren't intended to affect how a module is built,
1183 // reset them to their default values.
1184 Invocation->resetNonModularOptions();
1185
1186 // Remove any macro definitions that are explicitly ignored by the module.
1187 // They aren't supposed to affect how the module is built anyway.
1188 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1189 llvm::erase_if(PPOpts.Macros,
1190 [&HSOpts](const std::pair<std::string, bool> &def) {
1191 StringRef MacroDef = def.first;
1192 return HSOpts.ModulesIgnoreMacros.contains(
1193 llvm::CachedHashString(MacroDef.split('=').first));
1194 });
1195 HSOpts.ModulesIgnoreMacros.clear();
1196
1197 // Remove any search paths that are explicitly ignored by the module.
1198 // They aren't supposed to affect how the module is built anyway.
1199 if (!HSOpts.ModulesIgnoreSearchPaths.empty())
1200 llvm::erase_if(HSOpts.UserEntries,
1201 [&HSOpts](const HeaderSearchOptions::Entry &E) {
1202 return HSOpts.ModulesIgnoreSearchPaths.contains(
1203 llvm::CachedHashString(E.Path));
1204 });
1205 HSOpts.ModulesIgnoreSearchPaths.clear();
1206
1207 // If the original compiler invocation had -fmodule-name, pass it through.
1208 Invocation->getLangOpts().ModuleName =
1210
1211 // Note the name of the module we're building.
1212 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1213
1214 // If there is a module map file, build the module using the module map.
1215 // Set up the inputs/outputs so that we build the module from its umbrella
1216 // header.
1217 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1218 FrontendOpts.OutputFile = ModuleFileName.str();
1219 FrontendOpts.DisableFree = false;
1220 FrontendOpts.GenerateGlobalModuleIndex = false;
1221 FrontendOpts.BuildingImplicitModule = true;
1222 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1223 // Force implicitly-built modules to hash the content of the module file.
1224 HSOpts.ModulesHashContent = true;
1225 FrontendOpts.Inputs = {std::move(Input)};
1226
1227 // Don't free the remapped file buffers; they are owned by our caller.
1228 PPOpts.RetainRemappedFileBuffers = true;
1229
1230 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1231
1232 DiagOpts.VerifyDiagnostics = 0;
1233 assert(getInvocation().computeContextHash() ==
1234 Invocation->computeContextHash() &&
1235 "Module hash mismatch!");
1236
1237 std::shared_ptr<ModuleCache> ModCache;
1238 if (ThreadSafeConfig) {
1239 ModCache = ThreadSafeConfig->getModuleCache();
1240 } else {
1241 ModCache = this->ModCache;
1242 }
1243
1244 // Construct a compiler instance that will be used to create the module.
1245 auto InstancePtr = std::make_unique<CompilerInstance>(
1246 std::move(Invocation), getPCHContainerOperations(), std::move(ModCache));
1247 auto &Instance = *InstancePtr;
1248
1249 // The module build has the same targets as this instance, so it can use
1250 // the same builtins.
1251 Instance.SharedBuiltins = SharedBuiltins;
1252
1253 auto &Inv = Instance.getInvocation();
1254
1255 if (ThreadSafeConfig) {
1256 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1257 Instance.createFileManager();
1258 } else if (FrontendOpts.ModulesShareFileManager) {
1259 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1260 Instance.setFileManager(getFileManagerPtr());
1261 } else {
1262 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1263 Instance.createFileManager();
1264 }
1265
1266 if (ThreadSafeConfig) {
1267 Instance.createDiagnostics(&ThreadSafeConfig->getDiagConsumer(),
1268 /*ShouldOwnClient=*/false);
1269 } else {
1270 Instance.createDiagnostics(
1271 new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1272 /*ShouldOwnClient=*/true);
1273 }
1274 if (llvm::is_contained(DiagOpts.SystemHeaderWarningsModules, ModuleName))
1275 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1276
1277 Instance.createSourceManager();
1278 SourceManager &SourceMgr = Instance.getSourceManager();
1279
1280 if (ThreadSafeConfig) {
1281 // Detecting cycles in the module graph is responsibility of the client.
1282 } else {
1283 // Note that this module is part of the module build stack, so that we
1284 // can detect cycles in the module graph.
1285 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1286 SourceMgr.pushModuleBuildStack(
1287 ModuleName, FullSourceLoc(ImportLoc, getSourceManager()));
1288 }
1289
1290 // Make a copy for the new instance.
1291 Instance.FailedModules = FailedModules;
1292
1293 // An inferred framework is built from module map text printed by this
1294 // instance rather than by repeating the inference, so directories the
1295 // inference enumerated (its Frameworks subdirectory) are only known here.
1296 Instance.setInheritedDirectoryDependencies(DirectoryDependencies);
1297
1298 // Pass along the GenModuleActionWrapper callback.
1299 Instance.setGenModuleActionWrapper(getGenModuleActionWrapper());
1300
1301 if (GetDependencyDirectives)
1302 Instance.GetDependencyDirectives =
1303 GetDependencyDirectives->cloneFor(Instance.getFileManager());
1304
1305 if (ThreadSafeConfig) {
1306 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1307 } else {
1308 // If we're collecting module dependencies, we need to share a collector
1309 // between all of the module CompilerInstances. Other than that, we don't
1310 // want to produce any dependency output from the module build.
1311 Instance.setModuleDepCollector(getModuleDepCollector());
1312 }
1313 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1314
1315 return InstancePtr;
1316}
1317
1318namespace {
1319class PrettyStackTraceBuildModule : public llvm::PrettyStackTraceEntry {
1320 StringRef ModuleName;
1321 StringRef ModuleFileName;
1322
1323public:
1324 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1325 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1326 void print(raw_ostream &OS) const override {
1327 OS << "Building module '" << ModuleName << "' as '" << ModuleFileName
1328 << "'\n";
1329 }
1330};
1331} // namespace
1332
1333std::unique_ptr<llvm::MemoryBuffer>
1334CompilerInstance::compileModule(SourceLocation ImportLoc, StringRef ModuleName,
1335 StringRef ModuleFileName,
1336 CompilerInstance &Instance) {
1337 PrettyStackTraceBuildModule CrashInfo(ModuleName, ModuleFileName);
1338 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1339
1340 // Never compile a module that's already finalized - this would cause the
1341 // existing module to be freed, causing crashes if it is later referenced
1342 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(ModuleFileName)) {
1343 getDiagnostics().Report(ImportLoc, diag::err_module_rebuild_finalized)
1344 << ModuleName;
1345 return nullptr;
1346 }
1347
1348 getDiagnostics().Report(ImportLoc, diag::remark_module_build)
1349 << ModuleName << ModuleFileName;
1350
1351 SmallString<0> Buffer;
1352
1353 // Execute the action to actually build the module in-place. Use a separate
1354 // thread so that we get a stack large enough.
1355 uint64_t ParentTID = llvm::get_threadid();
1356 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1357 [&]() {
1359 << "module_compile_thread: parent=" << ParentTID
1360 << " pcm_compile: " << ModuleFileName;
1361
1362 auto OS = std::make_unique<llvm::raw_svector_ostream>(Buffer);
1363
1364 std::unique_ptr<FrontendAction> Action =
1365 std::make_unique<GenerateModuleFromModuleMapAction>(std::move(OS));
1366
1367 if (auto WrapGenModuleAction = Instance.getGenModuleActionWrapper())
1368 Action = WrapGenModuleAction(Instance.getFrontendOpts(),
1369 std::move(Action));
1370
1371 Instance.ExecuteAction(*Action);
1372 },
1374
1375 getDiagnostics().Report(ImportLoc, diag::remark_module_build_done)
1376 << ModuleName;
1377
1378 // Propagate the statistics to the parent FileManager.
1379 if (!getFrontendOpts().ModulesShareFileManager)
1380 getFileManager().AddStats(Instance.getFileManager());
1381
1382 // Propagate the failed modules to the parent instance.
1383 FailedModules = std::move(Instance.FailedModules);
1384
1385 if (Crashed) {
1386 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1387 // that must be closed before clearing output files.
1388 Instance.setSema(nullptr);
1389 Instance.setASTConsumer(nullptr);
1390
1391 // Delete any remaining temporary files related to Instance.
1392 Instance.clearOutputFiles(/*EraseFiles=*/true);
1393 }
1394
1395 // We've rebuilt a module. If we're allowed to generate or update the global
1396 // module index, record that fact in the importing compiler instance.
1397 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1399 }
1400
1401 if (Crashed)
1402 return nullptr;
1403
1404 // Unless \p AllowPCMWithCompilerErrors is set, return 'failure' if errors
1405 // occurred.
1406 if (Instance.getDiagnostics().hasErrorOccurred() &&
1407 !Instance.getFrontendOpts().AllowPCMWithCompilerErrors)
1408 return nullptr;
1409
1410 // PCMs don't need to be null-terminated. Since the buffer typically has no
1411 // spare capacity, adding the terminator would reallocate and copy it.
1412 return std::make_unique<llvm::SmallVectorMemoryBuffer>(
1413 std::move(Buffer), Instance.getFrontendOpts().OutputFile,
1414 /*RequiresNullTerminator=*/false);
1415}
1416
1419 StringRef Filename = llvm::sys::path::filename(File.getName());
1420 SmallString<128> PublicFilename(File.getDir().getName());
1421 if (Filename == "module_private.map")
1422 llvm::sys::path::append(PublicFilename, "module.map");
1423 else if (Filename == "module.private.modulemap")
1424 llvm::sys::path::append(PublicFilename, "module.modulemap");
1425 else
1426 return std::nullopt;
1427 return FileMgr.getOptionalFileRef(PublicFilename);
1428}
1429
1430std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1431 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
1432 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1433 StringRef ModuleName = Module->getTopLevelModuleName();
1434
1436
1437 // Get or create the module map that we'll use to build this module.
1439 SourceManager &SourceMgr = getSourceManager();
1440
1441 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1442 ModuleMapFID.isValid()) {
1443 // We want to use the top-level module map. If we don't, the compiling
1444 // instance may think the containing module map is a top-level one, while
1445 // the importing instance knows it's included from a parent module map via
1446 // the extern directive. This mismatch could bite us later.
1447 SourceLocation Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1448 while (Loc.isValid() && isModuleMap(SourceMgr.getFileCharacteristic(Loc))) {
1449 ModuleMapFID = SourceMgr.getFileID(Loc);
1450 Loc = SourceMgr.getIncludeLoc(ModuleMapFID);
1451 }
1452
1453 OptionalFileEntryRef ModuleMapFile =
1454 SourceMgr.getFileEntryRefForID(ModuleMapFID);
1455 assert(ModuleMapFile && "Top-level module map with no FileID");
1456
1457 // Canonicalize compilation to start with the public module map. This is
1458 // vital for submodules declarations in the private module maps to be
1459 // correctly parsed when depending on a top level module in the public one.
1460 if (OptionalFileEntryRef PublicMMFile =
1461 getPublicModuleMap(*ModuleMapFile, getFileManager()))
1462 ModuleMapFile = PublicMMFile;
1463
1464 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1465
1466 // Use the systemness of the module map as parsed instead of using the
1467 // IsSystem attribute of the module. If the module has [system] but the
1468 // module map is not in a system path, then this would incorrectly parse
1469 // any other modules in that module map as system too.
1470 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(ModuleMapFID);
1471 bool IsSystem = isSystem(SLoc.getFile().getFileCharacteristic());
1472
1473 // Use the module map where this module resides.
1474 return cloneForModuleCompileImpl(
1475 ImportLoc, ModuleName,
1476 FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1478 Module->getDirectoryDependencies(), std::move(ThreadSafeConfig));
1479 }
1480
1481 // FIXME: We only need to fake up an input file here as a way of
1482 // transporting the module's directory to the module map parser. We should
1483 // be able to do that more directly, and parse from a memory buffer without
1484 // inventing this file.
1485 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1486 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1487
1488 std::string InferredModuleMapContent;
1489 llvm::raw_string_ostream OS(InferredModuleMapContent);
1490 Module->print(OS);
1491
1492 auto Instance = cloneForModuleCompileImpl(
1493 ImportLoc, ModuleName,
1494 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1496 Module->getDirectoryDependencies(), std::move(ThreadSafeConfig));
1497
1498 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1499 llvm::MemoryBuffer::getMemBufferCopy(InferredModuleMapContent);
1500 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1501 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1502 Instance->getSourceManager().overrideFileContents(ModuleMapFile,
1503 std::move(ModuleMapBuffer));
1504
1505 return Instance;
1506}
1507
1508/// Read the AST right after compiling the module.
1509/// Returns true on success, false on failure.
1510static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1511 SourceLocation ImportLoc,
1513 Module *Module,
1515 bool *OutOfDate, bool *Missing) {
1516 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1517
1518 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1519 if (OutOfDate)
1520 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1521
1522 // Try to read the module file, now that we've compiled it.
1523 ASTReader::ASTReadResult ReadResult =
1524 ImportingInstance.getASTReader()->ReadAST(
1526 ModuleLoadCapabilities);
1527 if (ReadResult == ASTReader::Success)
1528 return true;
1529
1530 // The caller wants to handle out-of-date failures.
1531 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1532 *OutOfDate = true;
1533 return false;
1534 }
1535
1536 // The caller wants to handle missing module files.
1537 if (Missing && ReadResult == ASTReader::Missing) {
1538 *Missing = true;
1539 return false;
1540 }
1541
1542 // The ASTReader didn't diagnose the error, so conservatively report it.
1543 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1544 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1545 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1546
1547 return false;
1548}
1549
1550/// Compile a module in a separate compiler instance.
1551/// Returns true on success, false on failure.
1552static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1553 SourceLocation ImportLoc,
1556 std::unique_ptr<llvm::MemoryBuffer> Buffer;
1557
1558 {
1559 auto Instance = ImportingInstance.cloneForModuleCompile(
1561
1562 Buffer = ImportingInstance.compileModule(ModuleNameLoc,
1564 ModuleFileName, *Instance);
1565
1566 if (!Buffer) {
1567 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1568 diag::err_module_not_built)
1569 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1570 return false;
1571 }
1572 }
1573
1574 off_t Size;
1575 time_t ModTime;
1576 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Written =
1577 ImportingInstance.getModuleCache().write(
1578 ModuleFileName, std::move(Buffer), Size, ModTime);
1579 if (!Written) {
1580 ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
1581 diag::err_module_not_written)
1582 << Module->Name << ModuleFileName << Written.getError().message()
1583 << SourceRange(ImportLoc, ModuleNameLoc);
1584 return false;
1585 }
1586 Buffer = std::move(*Written);
1587
1588 // The module is built successfully, we can update its timestamp now.
1589 if (ImportingInstance.getPreprocessor()
1594 }
1595
1596 // Readers use the module cache's view of the written PCM. Extracting the AST
1597 // file (which may be wrapped in an object file) isn't strictly necessary, but
1598 // it's more efficient to do so now rather than repeatedly in the readers.
1599 Buffer =
1600 ImportingInstance.getPCHContainerReader().ExtractPCH(std::move(Buffer));
1602 ModuleFileName, std::move(Buffer), Size, ModTime);
1603
1604 return true;
1605}
1606
1607/// The result of `compileModuleBehindLockOrRead()`.
1609 /// We failed to compile the module.
1611 /// We successfully compiled the module and we still need to read it.
1613 /// We failed to read the module file compiled by another instance.
1615 /// We read a module file compiled by another instance.
1617};
1618
1619/// Attempt to compile the module in a separate compiler instance behind a lock
1620/// (to avoid building the same module in multiple compiler instances), or read
1621/// the AST produced by another compiler instance.
1624 SourceLocation ImportLoc,
1627 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1628
1629 Diags.Report(ModuleNameLoc, diag::remark_module_lock)
1630 << ModuleFileName << Module->Name;
1631
1632 auto &ModuleCache = ImportingInstance.getModuleCache();
1633
1634 while (true) {
1635 auto Lock = ModuleCache.getLock(ModuleFileName);
1636 bool Owned;
1637 if (llvm::Error Err = Lock->tryLock().moveInto(Owned)) {
1638 // ModuleCache takes care of correctness and locks are only necessary for
1639 // performance. Fallback to building the module in case of any lock
1640 // related errors.
1641 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
1642 << Module->Name << toString(std::move(Err));
1643 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1647 }
1648 if (Owned) {
1649 // We're responsible for building the module ourselves.
1650 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1654 }
1655
1656 // Someone else is responsible for building the module. Wait for them to
1657 // finish.
1658 unsigned Timeout =
1660 switch (Lock->waitForUnlockFor(std::chrono::seconds(Timeout))) {
1661 case llvm::WaitForUnlockResult::Success:
1662 break; // The interesting case.
1663 case llvm::WaitForUnlockResult::OwnerDied:
1664 continue; // try again to get the lock.
1665 case llvm::WaitForUnlockResult::Timeout:
1666 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1667 // for someone else to complete the build so that it does not happen
1668 // twice. In case of timeout, try to build it ourselves again.
1669 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1670 << Module->Name;
1671 // Clear the lock file so that future invocations can make progress.
1672 Lock->unsafeUnlock();
1673 continue;
1674 }
1675
1676 // Read the module that was just written by someone else.
1677 bool OutOfDate = false;
1678 bool Missing = false;
1679 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1680 Module, ModuleFileName, &OutOfDate, &Missing))
1682 if (!OutOfDate && !Missing)
1684
1685 // The module may be missing or out of date in the presence of file system
1686 // races. It may also be out of date if one of its imports depends on header
1687 // search paths that are not consistent with this ImportingInstance.
1688 // Try again...
1689 }
1690}
1691
1692/// Compile a module in a separate compiler instance and read the AST,
1693/// returning true if the module compiles without errors, potentially using a
1694/// lock manager to avoid building the same module in multiple compiler
1695/// instances.
1696static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1697 SourceLocation ImportLoc,
1699 Module *Module,
1701 if (ImportingInstance.getInvocation()
1705 ImportingInstance, ImportLoc, ModuleNameLoc, Module, ModuleFileName)) {
1708 return false;
1710 return true;
1712 // We successfully compiled the module under a lock. Let's read it from
1713 // the in-memory module cache now.
1714 break;
1715 }
1716 } else {
1717 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc, Module,
1719 return false;
1720 }
1721
1722 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1724 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1725}
1726
1727/// Diagnose differences between the current definition of the given
1728/// configuration macro and the definition provided on the command line.
1729static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1730 Module *Mod, SourceLocation ImportLoc) {
1731 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1732 SourceManager &SourceMgr = PP.getSourceManager();
1733
1734 // If this identifier has never had a macro definition, then it could
1735 // not have changed.
1736 if (!Id->hadMacroDefinition())
1737 return;
1738 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1739
1740 // Find the macro definition from the command line.
1741 MacroInfo *CmdLineDefinition = nullptr;
1742 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1743 SourceLocation MDLoc = MD->getLocation();
1744 FileID FID = SourceMgr.getFileID(MDLoc);
1745 if (FID.isInvalid())
1746 continue;
1747 // We only care about the predefines buffer, or if the macro is defined
1748 // over the command line transitively through a PCH.
1749 if (FID != PP.getPredefinesFileID() &&
1750 !SourceMgr.isWrittenInCommandLineFile(MDLoc))
1751 continue;
1752 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1753 CmdLineDefinition = DMD->getMacroInfo();
1754 break;
1755 }
1756
1757 auto *CurrentDefinition = PP.getMacroInfo(Id);
1758 if (CurrentDefinition == CmdLineDefinition) {
1759 // Macro matches. Nothing to do.
1760 } else if (!CurrentDefinition) {
1761 // This macro was defined on the command line, then #undef'd later.
1762 // Complain.
1763 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1764 << true << ConfigMacro << Mod->getFullModuleName();
1765 auto LatestDef = LatestLocalMD->getDefinition();
1766 assert(LatestDef.isUndefined() &&
1767 "predefined macro went away with no #undef?");
1768 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1769 << true;
1770 return;
1771 } else if (!CmdLineDefinition) {
1772 // There was no definition for this macro in the command line,
1773 // but there was a local definition. Complain.
1774 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1775 << false << ConfigMacro << Mod->getFullModuleName();
1776 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1777 diag::note_module_def_undef_here)
1778 << false;
1779 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1780 /*Syntactically=*/true)) {
1781 // The macro definitions differ.
1782 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1783 << false << ConfigMacro << Mod->getFullModuleName();
1784 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1785 diag::note_module_def_undef_here)
1786 << false;
1787 }
1788}
1789
1791 SourceLocation ImportLoc) {
1792 clang::Module *TopModule = M->getTopLevelModule();
1793 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1794 checkConfigMacro(PP, ConMacro, M, ImportLoc);
1795 }
1796}
1797
1799 if (TheASTReader)
1800 return;
1801
1802 if (!hasASTContext())
1804
1805 // If we're implicitly building modules but not currently recursively
1806 // building a module, check whether we need to prune the module cache.
1807 if (getSourceManager().getModuleBuildStack().empty() &&
1809 .getHeaderSearchInfo()
1810 .getSpecificModuleCachePath()
1811 .empty())
1812 ModCache->maybePrune(getHeaderSearchOpts().ModuleCachePath,
1813 getHeaderSearchOpts().ModuleCachePruneInterval,
1814 getHeaderSearchOpts().ModuleCachePruneAfter);
1815
1817 std::string Sysroot = HSOpts.Sysroot;
1818 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1819 const FrontendOptions &FEOpts = getFrontendOpts();
1820 std::unique_ptr<llvm::Timer> ReadTimer;
1821
1822 if (timerGroup)
1823 ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
1824 "Reading modules", *timerGroup);
1825 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1828 getFrontendOpts().ModuleFileExtensions,
1829 Sysroot.empty() ? "" : Sysroot.c_str(),
1831 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
1832 /*AllowConfigurationMismatch=*/false,
1836 +getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
1837 if (hasASTConsumer()) {
1838 TheASTReader->setDeserializationListener(
1839 getASTConsumer().GetASTDeserializationListener());
1841 getASTConsumer().GetASTMutationListener());
1842 }
1843 getASTContext().setExternalSource(TheASTReader);
1844 if (hasSema())
1845 TheASTReader->InitializeSema(getSema());
1846 if (hasASTConsumer())
1847 TheASTReader->StartTranslationUnit(&getASTConsumer());
1848
1849 for (auto &Listener : DependencyCollectors)
1850 Listener->attachToASTReader(*TheASTReader);
1851}
1852
1855 llvm::Timer Timer;
1856 if (timerGroup)
1857 Timer.init("preloading." + std::string(FileName.str()),
1858 "Preloading " + std::string(FileName.str()), *timerGroup);
1859 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1860
1861 // If we don't already have an ASTReader, create one now.
1862 if (!TheASTReader)
1864
1865 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1866 // ASTReader to diagnose it, since it can produce better errors that we can.
1867 bool ConfigMismatchIsRecoverable =
1868 getDiagnostics().getDiagnosticLevel(diag::warn_ast_file_config_mismatch,
1869 SourceLocation()) <=
1871
1872 auto Listener = std::make_unique<ReadModuleNames>(*PP);
1873 auto &ListenerRef = *Listener;
1874 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1875 std::move(Listener));
1876
1877 // Try to load the module file.
1878 switch (TheASTReader->ReadAST(
1880 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1881 &LoadedModuleFile)) {
1882 case ASTReader::Success:
1883 // We successfully loaded the module file; remember the set of provided
1884 // modules so that we don't try to load implicit modules for them.
1885 ListenerRef.registerAll();
1886 return true;
1887
1889 // Ignore unusable module files.
1891 diag::warn_ast_file_config_mismatch)
1892 << FileName;
1893 // All modules provided by any files we tried and failed to load are now
1894 // unavailable; includes of those modules should now be handled textually.
1895 ListenerRef.markAllUnavailable();
1896 return true;
1897
1898 default:
1899 return false;
1900 }
1901}
1902
1903namespace {
1904enum ModuleSource {
1905 MS_ModuleNotFound,
1906 MS_ModuleCache,
1907 MS_PrebuiltModulePath,
1908 MS_ModuleBuildPragma
1909};
1910} // end namespace
1911
1912/// Select a source for loading the named module and compute the filename to
1913/// load it from.
1914static ModuleSource selectModuleSource(
1915 Module *M, StringRef ModuleName, ModuleFileName &ModuleFilename,
1916 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1917 HeaderSearch &HS) {
1918 assert(ModuleFilename.empty() && "Already has a module source?");
1919
1920 // Check to see if the module has been built as part of this compilation
1921 // via a module build pragma.
1922 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1923 if (BuiltModuleIt != BuiltModules.end()) {
1924 ModuleFilename = ModuleFileName::makeExplicit(BuiltModuleIt->second);
1925 return MS_ModuleBuildPragma;
1926 }
1927
1928 // Try to load the module from the prebuilt module path.
1929 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1930 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1931 !HSOpts.PrebuiltModulePaths.empty()) {
1932 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1933 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1934 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
1935 if (!ModuleFilename.empty())
1936 return MS_PrebuiltModulePath;
1937 }
1938
1939 // Try to load the module from the module cache.
1940 if (M) {
1941 ModuleFilename = HS.getCachedModuleFileName(M);
1942 return MS_ModuleCache;
1943 }
1944
1945 return MS_ModuleNotFound;
1946}
1947
1948ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1949 StringRef ModuleName, SourceLocation ImportLoc, SourceRange ModuleNameRange,
1950 bool IsInclusionDirective) {
1951 // Search for a module with the given name.
1952 HeaderSearch &HS = PP->getHeaderSearchInfo();
1953 Module *M =
1954 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
1955
1956 // Check for any configuration macros that have changed. This is done
1957 // immediately before potentially building a module in case this module
1958 // depends on having one of its configuration macros defined to successfully
1959 // build. If this is not done the user will never see the warning.
1960 if (M)
1961 checkConfigMacros(getPreprocessor(), M, ImportLoc);
1962
1963 // Select the source and filename for loading the named module.
1964 ModuleFileName ModuleFilename;
1965 ModuleSource Source =
1966 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1967 SourceLocation ModuleNameLoc = ModuleNameRange.getBegin();
1968 if (Source == MS_ModuleNotFound) {
1969 // We can't find a module, error out here.
1970 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1971 << ModuleName << ModuleNameRange;
1972 return nullptr;
1973 }
1974 if (ModuleFilename.empty()) {
1975 if (M && M->HasIncompatibleModuleFile) {
1976 // We tried and failed to load a module file for this module. Fall
1977 // back to textual inclusion for its headers.
1979 }
1980
1981 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1982 << ModuleName;
1983 return nullptr;
1984 }
1985
1986 // Create an ASTReader on demand.
1987 if (!getASTReader())
1989
1990 // Time how long it takes to load the module.
1991 llvm::Timer Timer;
1992 if (timerGroup)
1993 Timer.init("loading." + std::string(ModuleFilename.str()),
1994 "Loading " + std::string(ModuleFilename.str()), *timerGroup);
1995 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1996 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1997
1998 // Try to load the module file. If we are not trying to load from the
1999 // module cache, we don't know how to rebuild modules.
2000 unsigned ARRFlags = Source == MS_ModuleCache
2003 : Source == MS_PrebuiltModulePath
2004 ? 0
2006 switch (getASTReader()->ReadAST(ModuleFilename,
2007 Source == MS_PrebuiltModulePath
2009 : Source == MS_ModuleBuildPragma
2012 ImportLoc, ARRFlags)) {
2013 case ASTReader::Success: {
2014 if (M)
2015 return M;
2016 assert(Source != MS_ModuleCache &&
2017 "missing module, but file loaded from cache");
2018
2019 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
2020 // until the first call to ReadAST. Look it up now.
2021 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
2022
2023 // Check whether M refers to the file in the prebuilt module path.
2024 if (M && M->getASTFileKey() &&
2025 *M->getASTFileKey() ==
2026 getASTReader()->getModuleManager().makeKey(ModuleFilename))
2027 return M;
2028
2029 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
2030 << ModuleName;
2031 return ModuleLoadResult();
2032 }
2033
2035 case ASTReader::Missing:
2036 // The most interesting case.
2037 break;
2038
2040 if (Source == MS_PrebuiltModulePath)
2041 // FIXME: We shouldn't be setting HadFatalFailure below if we only
2042 // produce a warning here!
2043 getDiagnostics().Report(SourceLocation(),
2044 diag::warn_ast_file_config_mismatch)
2045 << ModuleFilename;
2046 // Fall through to error out.
2047 [[fallthrough]];
2051 // FIXME: The ASTReader will already have complained, but can we shoehorn
2052 // that diagnostic information into a more useful form?
2053 return ModuleLoadResult();
2054
2055 case ASTReader::Failure:
2057 return ModuleLoadResult();
2058 }
2059
2060 // ReadAST returned Missing or OutOfDate.
2061 if (Source != MS_ModuleCache) {
2062 // We don't know the desired configuration for this module and don't
2063 // necessarily even have a module map. Since ReadAST already produces
2064 // diagnostics for these two cases, we simply error out here.
2065 return ModuleLoadResult();
2066 }
2067
2068 // The module file is missing or out-of-date. Build it.
2069 assert(M && "missing module, but trying to compile for cache");
2070
2071 // Check whether there is a cycle in the module graph.
2073 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
2074 for (; Pos != PosEnd; ++Pos) {
2075 if (Pos->first == ModuleName)
2076 break;
2077 }
2078
2079 if (Pos != PosEnd) {
2080 SmallString<256> CyclePath;
2081 for (; Pos != PosEnd; ++Pos) {
2082 CyclePath += Pos->first;
2083 CyclePath += " -> ";
2084 }
2085 CyclePath += ModuleName;
2086
2087 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
2088 << ModuleName << CyclePath;
2089 return nullptr;
2090 }
2091
2092 // Check whether we have already attempted to build this module (but failed).
2093 if (FailedModules.contains(ModuleName)) {
2094 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
2095 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
2096 return nullptr;
2097 }
2098
2099 // Try to compile and then read the AST.
2100 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
2101 ModuleFilename)) {
2102 assert(getDiagnostics().hasErrorOccurred() &&
2103 "undiagnosed error in compileModuleAndReadAST");
2104 FailedModules.insert(ModuleName);
2105 return nullptr;
2106 }
2107
2108 // Okay, we've rebuilt and now loaded the module.
2109 return M;
2110}
2111
2114 ModuleIdPath Path,
2116 bool IsInclusionDirective) {
2117 // Determine what file we're searching from.
2118 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
2119 SourceLocation ModuleNameLoc = Path[0].getLoc();
2120
2121 // If we've already handled this import, just return the cached result.
2122 // This cache eliminates redundant diagnostics when both the preprocessor
2123 // and parser see the same import declaration.
2124 if (ImportLoc.isValid()) {
2125 auto CacheIt = ModuleImportResults.find(ImportLoc);
2126 if (CacheIt != ModuleImportResults.end()) {
2127 if (CacheIt->second && ModuleName != getLangOpts().CurrentModule)
2128 TheASTReader->makeModuleVisible(CacheIt->second, Visibility, ImportLoc);
2129 return CacheIt->second;
2130 }
2131 }
2132
2133 // If we don't already have information on this module, load the module now.
2134 Module *Module = nullptr;
2136 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].getIdentifierInfo())) {
2137 // Use the cached result, which may be nullptr.
2138 Module = *MaybeModule;
2139 // Config macros are already checked before building a module, but they need
2140 // to be checked at each import location in case any of the config macros
2141 // have a new value at the current `ImportLoc`.
2142 if (Module)
2144 } else if (ModuleName == getLangOpts().CurrentModule) {
2145 // This is the module we're building.
2146 Module = PP->getHeaderSearchInfo().lookupModule(
2147 ModuleName, ImportLoc, /*AllowSearch*/ true,
2148 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2149
2150 // Config macros do not need to be checked here for two reasons.
2151 // * This will always be textual inclusion, and thus the config macros
2152 // actually do impact the content of the header.
2153 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2154 // function as the `#include` or `#import` is textual.
2155
2156 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2157 } else if (getPreprocessorOpts().SingleModuleParseMode) {
2158 // This mimics how findOrCompileModuleAndReadAST() finds the module.
2160 ModuleName, ImportLoc, true, !IsInclusionDirective);
2161 if (Module) {
2162 if (PPCallbacks *PPCb = getPreprocessor().getPPCallbacks())
2163 PPCb->moduleLoadSkipped(Module);
2164 // Mark the module and its submodules as if they were loaded from a PCM.
2165 // This prevents emission of the "missing submodule" diagnostic below.
2166 std::vector<clang::Module *> Worklist{Module};
2167 while (!Worklist.empty()) {
2168 clang::Module *M = Worklist.back();
2169 Worklist.pop_back();
2170 M->IsFromModuleFile = true;
2171 for (clang::Module *SubM : M->submodules())
2172 Worklist.push_back(SubM);
2173 }
2174 }
2175 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2176 } else {
2177 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
2178 Path.back().getIdentifierInfo()->getLength());
2179 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2180 ModuleName, ImportLoc, SourceRange{ModuleNameLoc, ModuleNameEndLoc},
2181 IsInclusionDirective);
2182 if (!Result.isNormal())
2183 return Result;
2184 if (!Result)
2185 DisableGeneratingGlobalModuleIndex = true;
2186 Module = Result;
2187 MM.cacheModuleLoad(*Path[0].getIdentifierInfo(), Module);
2188 }
2189
2190 // If we never found the module, fail. Otherwise, verify the module and link
2191 // it up.
2192 if (!Module)
2193 return ModuleLoadResult();
2194
2195 // Verify that the rest of the module path actually corresponds to
2196 // a submodule.
2197 bool MapPrivateSubModToTopLevel = false;
2198 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2199 StringRef Name = Path[I].getIdentifierInfo()->getName();
2200 clang::Module *Sub = Module->findSubmodule(Name);
2201
2202 // If the user is requesting Foo.Private and it doesn't exist, try to
2203 // match Foo_Private and emit a warning asking for the user to write
2204 // @import Foo_Private instead. FIXME: remove this when existing clients
2205 // migrate off of Foo.Private syntax.
2206 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2207 SmallString<128> PrivateModule(Module->Name);
2208 PrivateModule.append("_Private");
2209
2211 auto &II = PP->getIdentifierTable().get(
2212 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
2213 PrivPath.emplace_back(Path[0].getLoc(), &II);
2214
2216 // If there is a modulemap module or prebuilt module, load it.
2217 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
2218 !IsInclusionDirective) ||
2219 selectModuleSource(nullptr, PrivateModule, FileName, BuiltModules,
2220 PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2221 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
2222 if (Sub) {
2223 MapPrivateSubModToTopLevel = true;
2224 PP->markClangModuleAsAffecting(Module);
2225 if (!getDiagnostics().isIgnored(
2226 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
2227 getDiagnostics().Report(Path[I].getLoc(),
2228 diag::warn_no_priv_submodule_use_toplevel)
2229 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2230 << PrivateModule
2231 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2232 << FixItHint::CreateReplacement(SourceRange(Path[0].getLoc()),
2233 PrivateModule);
2234 getDiagnostics().Report(Sub->DefinitionLoc,
2235 diag::note_private_top_level_defined);
2236 }
2237 }
2238 }
2239
2240 if (!Sub) {
2241 // Attempt to perform typo correction to find a module name that works.
2243 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2244
2245 for (class Module *SubModule : Module->submodules()) {
2246 unsigned ED =
2247 Name.edit_distance(SubModule->Name,
2248 /*AllowReplacements=*/true, BestEditDistance);
2249 if (ED <= BestEditDistance) {
2250 if (ED < BestEditDistance) {
2251 Best.clear();
2252 BestEditDistance = ED;
2253 }
2254
2255 Best.push_back(SubModule->Name);
2256 }
2257 }
2258
2259 // If there was a clear winner, user it.
2260 if (Best.size() == 1) {
2261 getDiagnostics().Report(Path[I].getLoc(),
2262 diag::err_no_submodule_suggest)
2263 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2264 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2265 << FixItHint::CreateReplacement(SourceRange(Path[I].getLoc()),
2266 Best[0]);
2267
2268 Sub = Module->findSubmodule(Best[0]);
2269 }
2270 }
2271
2272 if (!Sub) {
2273 // No submodule by this name. Complain, and don't look for further
2274 // submodules.
2275 getDiagnostics().Report(Path[I].getLoc(), diag::err_no_submodule)
2276 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2277 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2278 break;
2279 }
2280
2281 Module = Sub;
2282 }
2283
2284 // Make the named module visible, if it's not already part of the module
2285 // we are parsing.
2286 if (ModuleName != getLangOpts().CurrentModule) {
2287 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2288 // We have an umbrella header or directory that doesn't actually include
2289 // all of the headers within the directory it covers. Complain about
2290 // this missing submodule and recover by forgetting that we ever saw
2291 // this submodule.
2292 // FIXME: Should we detect this at module load time? It seems fairly
2293 // expensive (and rare).
2294 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
2296 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2297
2299 }
2300
2301 // Check whether this module is available.
2303 *Module, getDiagnostics())) {
2304 getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
2305 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2306 ModuleImportResults[ImportLoc] = ModuleLoadResult();
2307 return ModuleLoadResult();
2308 }
2309
2310 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
2311 }
2312
2313 // Resolve any remaining module using export_as for this one.
2316 .getModuleMap()
2318
2319 ModuleImportResults[ImportLoc] = ModuleLoadResult(Module);
2320 return ModuleLoadResult(Module);
2321}
2322
2324 StringRef ModuleName,
2325 StringRef Source) {
2326 // Avoid creating filenames with special characters.
2327 SmallString<128> CleanModuleName(ModuleName);
2328 for (auto &C : CleanModuleName)
2329 if (!isAlphanumeric(C))
2330 C = '_';
2331
2332 // FIXME: Using a randomized filename here means that our intermediate .pcm
2333 // output is nondeterministic (as .pcm files refer to each other by name).
2334 // Can this affect the output in any way?
2336 int FD;
2337 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2338 CleanModuleName, "pcm", FD, ModuleFileName)) {
2339 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
2340 << ModuleFileName << EC.message();
2341 return;
2342 }
2343 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2344
2345 FrontendInputFile Input(
2346 ModuleMapFileName,
2347 InputKind(getLanguageFromOptions(Invocation->getLangOpts()),
2348 InputKind::ModuleMap, /*Preprocessed*/true));
2349
2350 std::string NullTerminatedSource(Source.str());
2351
2352 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2353 StringRef(), ModuleFileName);
2354
2355 // Create a virtual file containing our desired source.
2356 // FIXME: We shouldn't need to do this.
2357 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2358 ModuleMapFileName, NullTerminatedSource.size(), 0);
2359 Other->getSourceManager().overrideFileContents(
2360 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
2361
2362 Other->BuiltModules = std::move(BuiltModules);
2363 Other->DeleteBuiltModules = false;
2364
2365 // Build the module, inheriting any modules that we've built locally.
2366 std::unique_ptr<llvm::MemoryBuffer> Buffer =
2367 compileModule(ImportLoc, ModuleName, ModuleFileName, *Other);
2368 BuiltModules = std::move(Other->BuiltModules);
2369
2370 if (Buffer) {
2371 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
2372 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2373 OS << Buffer->getBuffer();
2374 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2375 }
2376}
2377
2380 SourceLocation ImportLoc) {
2381 if (!TheASTReader)
2383 if (!TheASTReader)
2384 return;
2385
2386 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
2387}
2388
2390 SourceLocation TriggerLoc) {
2391 if (getPreprocessor()
2392 .getHeaderSearchInfo()
2393 .getSpecificModuleCachePath()
2394 .empty())
2395 return nullptr;
2396 if (!TheASTReader)
2398 // Can't do anything if we don't have the module manager.
2399 if (!TheASTReader)
2400 return nullptr;
2401 // Get an existing global index. This loads it if not already
2402 // loaded.
2403 TheASTReader->loadGlobalIndex();
2404 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2405 // If the global index doesn't exist, create it.
2406 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2407 hasPreprocessor()) {
2408 llvm::sys::fs::create_directories(
2409 getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2410 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2413 .getHeaderSearchInfo()
2414 .getSpecificModuleCachePath())) {
2415 // FIXME this drops the error on the floor. This code is only used for
2416 // typo correction and drops more than just this one source of errors
2417 // (such as the directory creation failure above). It should handle the
2418 // error.
2419 consumeError(std::move(Err));
2420 return nullptr;
2421 }
2422 TheASTReader->resetForReload();
2423 TheASTReader->loadGlobalIndex();
2424 GlobalIndex = TheASTReader->getGlobalIndex();
2425 }
2426 // For finding modules needing to be imported for fixit messages,
2427 // we need to make the global index cover all modules, so we do that here.
2428 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2430
2431 // Load modules that were parsed from module maps but not loaded yet.
2432 MMap.loadAllParsedModules();
2433
2434 bool RecreateIndex = false;
2436 E = MMap.module_end(); I != E; ++I) {
2437 Module *TheModule = I->second;
2438 if (!TheModule->getASTFileKey()) {
2440 Path.emplace_back(TriggerLoc,
2441 getPreprocessor().getIdentifierInfo(TheModule->Name));
2442 std::reverse(Path.begin(), Path.end());
2443 // Load a module as hidden. This also adds it to the global index.
2444 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
2445 RecreateIndex = true;
2446 }
2447 }
2448 if (RecreateIndex) {
2449 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2452 .getHeaderSearchInfo()
2453 .getSpecificModuleCachePath())) {
2454 // FIXME As above, this drops the error on the floor.
2455 consumeError(std::move(Err));
2456 return nullptr;
2457 }
2458 TheASTReader->resetForReload();
2459 TheASTReader->loadGlobalIndex();
2460 GlobalIndex = TheASTReader->getGlobalIndex();
2461 }
2462 HaveFullGlobalModuleIndex = true;
2463 }
2464 return GlobalIndex;
2465}
2466
2467// Check global module index for missing imports.
2468bool
2470 SourceLocation TriggerLoc) {
2471 // Look for the symbol in non-imported modules, but only if an error
2472 // actually occurred.
2473 if (!buildingModule()) {
2474 // Load global module index, or retrieve a previously loaded one.
2476 TriggerLoc);
2477
2478 // Only if we have a global index.
2479 if (GlobalIndex) {
2480 GlobalModuleIndex::HitSet FoundModules;
2481
2482 // Find the modules that reference the identifier.
2483 // Note that this only finds top-level modules.
2484 // We'll let diagnoseTypo find the actual declaration module.
2485 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
2486 return true;
2487 }
2488 }
2489
2490 return false;
2491}
2492void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
2493
2496 ExternalSemaSrc = std::move(ESS);
2497}
Defines the clang::ASTContext interface.
Defines a logger where each line is written atomically to the file.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName 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 readASTAfterCompileModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName, bool *OutOfDate, bool *Missing)
Read the AST right after compiling the module.
static CompileOrReadResult compileModuleBehindLockOrRead(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Attempt to compile the module in a separate compiler instance behind a lock (to avoid building the sa...
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)
CompileOrReadResult
The result of compileModuleBehindLockOrRead().
@ Compiled
We successfully compiled the module and we still need to read it.
@ Read
We read a module file compiled by another instance.
@ FailedToRead
We failed to read the module file compiled by another instance.
@ FailedToCompile
We failed to compile 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 ModuleSource selectModuleSource(Module *M, StringRef ModuleName, ModuleFileName &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 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, ModuleFileName ModuleFileName)
Compile a module in a separate compiler instance.
static void checkConfigMacros(Preprocessor &PP, Module *M, SourceLocation ImportLoc)
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, const Context &Ctx, QualType Ty)
static StringRef getTriple(const Command &Job)
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:246
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.
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
RAII object to temporarily add an AST callback listener.
Definition ASTReader.h:1914
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition ASTReader.h:1827
@ ARR_None
The client can't handle any AST loading failures.
Definition ASTReader.h:1823
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition ASTReader.h:1840
@ 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:1831
@ 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:1844
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:447
@ Success
The control block was read successfully.
Definition ASTReader.h:450
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition ASTReader.h:467
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition ASTReader.h:460
@ Failure
The AST file itself appears corrupted.
Definition ASTReader.h:453
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition ASTReader.h:463
@ HadErrors
The AST file has errors.
Definition ASTReader.h:470
@ Missing
The AST file was missing.
Definition ASTReader.h:456
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.
bool loadModuleFile(ModuleFileName FileName, serialization::ModuleFile *&LoadedModuleFile)
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 ...
bool parseLLVMArgs(llvm::raw_ostream *Errs=nullptr)
Parse the -mllvm options in FrontendOptions::LLVMArgs, setting library options in getLibraryOptions()...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
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.
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
GenModuleActionWrapperFunc getGenModuleActionWrapper() const
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
FileSystemOptions & getFileSystemOpts()
llvm::Timer & getFrontendTimer() const
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()
std::unique_ptr< llvm::MemoryBuffer > compileModule(SourceLocation ImportLoc, StringRef ModuleName, StringRef ModuleFileName, CompilerInstance &Instance)
Compile a module file for the given module, using the options provided by the importing compiler inst...
void 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.
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.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false, bool SetOnlyIfDifferent=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
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()
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
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.
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
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:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool hasErrorOccurred() const
Definition Diagnostic.h:923
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:663
DiagnosticConsumer * getClient()
Definition Diagnostic.h:655
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
Definition Diagnostic.h:659
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:317
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:57
void AddStats(const FileManager &Other)
Import statistics from a child FileManager and add them to this current FileManager.
void PrintStats() const
static bool fixupRelativePath(const FileSystemOptions &FileSystemOpts, SmallVectorImpl< char > &Path)
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
Abstract base class for actions which can be performed by the frontend.
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
llvm::Error Execute()
Set the source manager's main input file, and run the action.
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
An input file for the front end.
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::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM's option processing; this should only be used for debugging an...
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.
unsigned ImplicitModulesLockTimeoutSeconds
The time in seconds to wait on an implicit module lock before timing out.
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.
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreMacros
The set of macro names that should be ignored by implicitly-built modules.
std::vector< Entry > UserEntries
User specified include entries.
llvm::SmallSetVector< llvm::CachedHashString, 16 > ModulesIgnoreSearchPaths
The set of header search paths that should be ignored by implicitly-built modules.
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.
ModuleFileName 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...
ModuleFileName getPrebuiltImplicitModuleFileName(Module *Module)
Retrieve the name of the prebuilt module file that should be used to load the given module.
ModuleFileName getCachedModuleFileName(Module *Module)
Retrieve the name of the cached 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.
ModuleMap & getModuleMap()
Retrieve the module map.
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.
llvm::MemoryBuffer & addBuiltPCM(llvm::StringRef Filename, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t Size, time_t ModTime)
Store a just-built PCM under the Filename.
The kind of a file that we've been handed as an input.
@ 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:40
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:41
AtomicLineLogger & getLogger()
virtual llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > write(StringRef Path, std::unique_ptr< llvm::MemoryBuffer > Buffer, off_t &Size, time_t &ModTime)=0
Write the PCM contents to the given path in the module cache.
virtual InMemoryModuleCache & getInMemoryModuleCache()=0
Returns this process's view of the module cache.
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.
Identifies a module file to be loaded.
Definition Module.h:109
bool empty() const
Checks whether the module file name is empty.
Definition Module.h:194
static ModuleFileName makeExplicit(std::string Name)
Creates a file name for an explicit module.
Definition Module.h:142
StringRef str() const
Returns the plain module file name.
Definition Module.h:188
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:812
module_iterator module_begin() const
Definition ModuleMap.h:814
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition ModuleMap.h:826
module_iterator module_end() const
Definition ModuleMap.h:815
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:52
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition ModuleMap.h:821
void loadAllParsedModules()
Module * findOrLoadModule(StringRef Name)
Describes a module or submodule.
Definition Module.h:340
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition Module.h:953
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition Module.h:731
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition Module.h:564
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition Module.h:646
@ Hidden
All of the names in this module are hidden.
Definition Module.h:648
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:479
const ModuleFileKey * getASTFileKey() const
The serialized AST file key for this module, if one was created.
Definition Module.h:964
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition Module.h:592
std::string Name
The name of this module.
Definition Module.h:343
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:1079
ArrayRef< std::string > getDirectoryDependencies() const
Definition Module.h:1005
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition Module.h:394
ModuleRef findSubmodule(StringRef Name) const
Find the submodule with the given name.
Definition Module.cpp:374
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition Module.h:579
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
Definition Module.h:568
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:242
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition Module.h:575
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual std::unique_ptr< llvm::MemoryBuffer > ExtractPCH(std::unique_ptr< llvm::MemoryBuffer > Buffer) const =0
Returns a buffer with the serialized AST inside the PCH container Buffer.
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
@ 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:863
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition ASTReader.h:360
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:228
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:845
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual void setAuxTarget(const TargetInfo *Aux)
void noSignedCharForObjCBool()
Definition TargetInfo.h:940
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.
static std::error_code setConvertersFromOptions(TextEncoding &TE, const clang::LangOptions &Opts, TargetInfo &TInfo)
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:158
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)
Definition Interp.h:817
@ MK_PCH
File is a PCH file treated as such.
Definition ModuleFile.h:52
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition ModuleFile.h:55
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition ModuleFile.h:49
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition ModuleFile.h:46
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition ModuleFile.h:61
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions &DiagOpts, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
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.
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:906
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
Definition Stack.h:26
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:48
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 ...
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...
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
A source location that has been parsed on the command line.