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