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