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