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