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