clang 22.0.0git
CompilerInstance.h
Go to the documentation of this file.
1//===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
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
9#ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
10#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/BuryPointer.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/VirtualFileSystem.h"
29#include <cassert>
30#include <list>
31#include <memory>
32#include <optional>
33#include <string>
34#include <utility>
35
36namespace llvm {
37class raw_fd_ostream;
38class Timer;
39class TimerGroup;
40}
41
42namespace clang {
43class ASTContext;
44class ASTReader;
45
46namespace serialization {
47class ModuleFile;
48}
49
50class CodeCompleteConsumer;
51class DiagnosticsEngine;
52class DiagnosticConsumer;
53class FileManager;
54class FrontendAction;
55class Module;
56class ModuleCache;
57class Preprocessor;
58class Sema;
59class SourceManager;
60class TargetInfo;
62
63/// CompilerInstance - Helper class for managing a single instance of the Clang
64/// compiler.
65///
66/// The CompilerInstance serves two purposes:
67/// (1) It manages the various objects which are necessary to run the compiler,
68/// for example the preprocessor, the target information, and the AST
69/// context.
70/// (2) It provides utility routines for constructing and manipulating the
71/// common Clang objects.
72///
73/// The compiler instance generally owns the instance of all the objects that it
74/// manages. However, clients can still share objects by manually setting the
75/// object and retaking ownership prior to destroying the CompilerInstance.
76///
77/// The compiler instance is intended to simplify clients, but not to lock them
78/// in to the compiler instance for everything. When possible, utility functions
79/// come in two forms; a short form that reuses the CompilerInstance objects,
80/// and a long form that takes explicit instances of any required objects.
82 /// The options used in this compiler instance.
83 std::shared_ptr<CompilerInvocation> Invocation;
84
85 /// The diagnostics engine instance.
87
88 /// The target being compiled for.
90
91 /// Options for the auxiliary target.
92 std::unique_ptr<TargetOptions> AuxTargetOpts;
93
94 /// Auxiliary Target info.
96
97 /// The file manager.
99
100 /// The source manager.
102
103 /// The cache of PCM files.
105
106 /// Functor for getting the dependency preprocessor directives of a file.
107 std::unique_ptr<DependencyDirectivesGetter> GetDependencyDirectives;
108
109 /// The preprocessor.
110 std::shared_ptr<Preprocessor> PP;
111
112 /// The AST context.
114
115 /// An optional sema source that will be attached to sema.
117
118 /// The AST consumer.
119 std::unique_ptr<ASTConsumer> Consumer;
120
121 /// The code completion consumer.
122 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
123
124 /// The semantic analysis object.
125 std::unique_ptr<Sema> TheSema;
126
127 /// The frontend timer group.
128 std::unique_ptr<llvm::TimerGroup> timerGroup;
129
130 /// The frontend timer.
131 std::unique_ptr<llvm::Timer> FrontendTimer;
132
133 /// The ASTReader, if one exists.
135
136 /// The module dependency collector for crashdumps
137 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
138
139 /// The module provider.
140 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
141
142 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
143
144 /// The set of modules that failed to build.
145 ///
146 /// This value will be passed among all of the compiler instances created
147 /// to (re)build modules, so that once a module fails to build anywhere,
148 /// other instances will see that the module has failed and won't try to
149 /// build it again.
150 llvm::StringSet<> FailedModules;
151
152 /// The set of top-level modules that has already been built on the
153 /// fly as part of this overall compilation action.
154 std::map<std::string, std::string, std::less<>> BuiltModules;
155
156 /// Should we delete the BuiltModules when we're done?
157 bool DeleteBuiltModules = true;
158
159 /// The location of the module-import keyword for the last module
160 /// import.
161 SourceLocation LastModuleImportLoc;
162
163 /// The result of the last module import.
164 ///
165 ModuleLoadResult LastModuleImportResult;
166
167 /// Whether we should (re)build the global module index once we
168 /// have finished with this translation unit.
169 bool BuildGlobalModuleIndex = false;
170
171 /// We have a full global module index, with all modules.
172 bool HaveFullGlobalModuleIndex = false;
173
174 /// One or more modules failed to build.
175 bool DisableGeneratingGlobalModuleIndex = false;
176
177 /// The stream for verbose output if owned, otherwise nullptr.
178 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
179
180 /// The stream for verbose output.
181 raw_ostream *VerboseOutputStream = &llvm::errs();
182
183 /// Holds information about the output file.
184 ///
185 /// If TempFilename is not empty we must rename it to Filename at the end.
186 /// TempFilename may be empty and Filename non-empty if creating the temporary
187 /// failed.
188 struct OutputFile {
189 std::string Filename;
190 std::optional<llvm::sys::fs::TempFile> File;
191
192 OutputFile(std::string filename,
193 std::optional<llvm::sys::fs::TempFile> file)
194 : Filename(std::move(filename)), File(std::move(file)) {}
195 };
196
197 /// The list of active output files.
198 std::list<OutputFile> OutputFiles;
199
200 /// Force an output buffer.
201 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
202
203 CompilerInstance(const CompilerInstance &) = delete;
204 void operator=(const CompilerInstance &) = delete;
205public:
206 explicit CompilerInstance(
207 std::shared_ptr<CompilerInvocation> Invocation =
208 std::make_shared<CompilerInvocation>(),
209 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
210 std::make_shared<PCHContainerOperations>(),
211 ModuleCache *ModCache = nullptr);
212 ~CompilerInstance() override;
213
214 /// @name High-Level Operations
215 /// @{
216
217 /// ExecuteAction - Execute the provided action against the compiler's
218 /// CompilerInvocation object.
219 ///
220 /// This function makes the following assumptions:
221 ///
222 /// - The invocation options should be initialized. This function does not
223 /// handle the '-help' or '-version' options, clients should handle those
224 /// directly.
225 ///
226 /// - The diagnostics engine should have already been created by the client.
227 ///
228 /// - No other CompilerInstance state should have been initialized (this is
229 /// an unchecked error).
230 ///
231 /// - Clients should have initialized any LLVM target features that may be
232 /// required.
233 ///
234 /// - Clients should eventually call llvm_shutdown() upon the completion of
235 /// this routine to ensure that any managed objects are properly destroyed.
236 ///
237 /// Note that this routine may write output to 'stderr'.
238 ///
239 /// \param Act - The action to execute.
240 /// \return - True on success.
241 //
242 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
243 // of the context or else not CompilerInstance specific.
244 bool ExecuteAction(FrontendAction &Act);
245
246 /// At the end of a compilation, print the number of warnings/errors.
248
249 /// Load the list of plugins requested in the \c FrontendOptions.
251
252 /// @}
253 /// @name Compiler Invocation and Options
254 /// @{
255
256 CompilerInvocation &getInvocation() { return *Invocation; }
257
258 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
259
260 /// Indicates whether we should (re)build the global module index.
261 bool shouldBuildGlobalModuleIndex() const;
262
263 /// Set the flag indicating whether we should (re)build the global
264 /// module index.
265 void setBuildGlobalModuleIndex(bool Build) {
266 BuildGlobalModuleIndex = Build;
267 }
268
269 /// @}
270 /// @name Forwarding Methods
271 /// @{
272
273 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
274
276 return Invocation->getCodeGenOpts();
277 }
279 return Invocation->getCodeGenOpts();
280 }
281
283 return Invocation->getDependencyOutputOpts();
284 }
286 return Invocation->getDependencyOutputOpts();
287 }
288
290 return Invocation->getDiagnosticOpts();
291 }
293 return Invocation->getDiagnosticOpts();
294 }
295
297 return Invocation->getFileSystemOpts();
298 }
300 return Invocation->getFileSystemOpts();
301 }
302
304 return Invocation->getFrontendOpts();
305 }
307 return Invocation->getFrontendOpts();
308 }
309
311 return Invocation->getHeaderSearchOpts();
312 }
314 return Invocation->getHeaderSearchOpts();
315 }
316
317 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
319 return Invocation->getAPINotesOpts();
320 }
321
322 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
323 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
324
326 return Invocation->getPreprocessorOpts();
327 }
329 return Invocation->getPreprocessorOpts();
330 }
331
333 return Invocation->getPreprocessorOutputOpts();
334 }
336 return Invocation->getPreprocessorOutputOpts();
337 }
338
340 return Invocation->getTargetOpts();
341 }
343 return Invocation->getTargetOpts();
344 }
345
346 /// @}
347 /// @name Diagnostics Engine
348 /// @{
349
350 bool hasDiagnostics() const { return Diagnostics != nullptr; }
351
352 /// Get the current diagnostics engine.
354 assert(Diagnostics && "Compiler instance has no diagnostics!");
355 return *Diagnostics;
356 }
357
359 assert(Diagnostics && "Compiler instance has no diagnostics!");
360 return Diagnostics;
361 }
362
363 /// setDiagnostics - Replace the current diagnostics engine.
365
367 assert(Diagnostics && Diagnostics->getClient() &&
368 "Compiler instance has no diagnostic client!");
369 return *Diagnostics->getClient();
370 }
371
372 /// @}
373 /// @name VerboseOutputStream
374 /// @{
375
376 /// Replace the current stream for verbose output.
377 void setVerboseOutputStream(raw_ostream &Value);
378
379 /// Replace the current stream for verbose output.
380 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
381
382 /// Get the current stream for verbose output.
383 raw_ostream &getVerboseOutputStream() {
384 return *VerboseOutputStream;
385 }
386
387 /// @}
388 /// @name Target Info
389 /// @{
390
391 bool hasTarget() const { return Target != nullptr; }
392
394 assert(Target && "Compiler instance has no target!");
395 return *Target;
396 }
397
399 assert(Target && "Compiler instance has no target!");
400 return Target;
401 }
402
403 /// Replace the current Target.
405
406 /// @}
407 /// @name AuxTarget Info
408 /// @{
409
410 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
411
412 /// Replace the current AuxTarget.
414
415 // Create Target and AuxTarget based on current options
416 bool createTarget();
417
418 /// @}
419 /// @name Virtual File System
420 /// @{
421
422 llvm::vfs::FileSystem &getVirtualFileSystem() const;
425
426 /// @}
427 /// @name File Manager
428 /// @{
429
430 bool hasFileManager() const { return FileMgr != nullptr; }
431
432 /// Return the current file manager to the caller.
434 assert(FileMgr && "Compiler instance has no file manager!");
435 return *FileMgr;
436 }
437
439 assert(FileMgr && "Compiler instance has no file manager!");
440 return FileMgr;
441 }
442
444 llvm::BuryPointer(FileMgr.get());
445 FileMgr.resetWithoutRelease();
446 }
447
448 /// Replace the current file manager and virtual file system.
450
451 /// @}
452 /// @name Source Manager
453 /// @{
454
455 bool hasSourceManager() const { return SourceMgr != nullptr; }
456
457 /// Return the current source manager.
459 assert(SourceMgr && "Compiler instance has no source manager!");
460 return *SourceMgr;
461 }
462
464 assert(SourceMgr && "Compiler instance has no source manager!");
465 return SourceMgr;
466 }
467
469 llvm::BuryPointer(SourceMgr.get());
470 SourceMgr.resetWithoutRelease();
471 }
472
473 /// setSourceManager - Replace the current source manager.
475
476 /// @}
477 /// @name Preprocessor
478 /// @{
479
480 bool hasPreprocessor() const { return PP != nullptr; }
481
482 /// Return the current preprocessor.
484 assert(PP && "Compiler instance has no preprocessor!");
485 return *PP;
486 }
487
488 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
489
491 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
492 }
493
494 /// Replace the current preprocessor.
495 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
496
497 /// @}
498 /// @name ASTContext
499 /// @{
500
501 bool hasASTContext() const { return Context != nullptr; }
502
504 assert(Context && "Compiler instance has no AST context!");
505 return *Context;
506 }
507
509 assert(Context && "Compiler instance has no AST context!");
510 return Context;
511 }
512
514 llvm::BuryPointer(Context.get());
515 Context.resetWithoutRelease();
516 }
517
518 /// setASTContext - Replace the current AST context.
520
521 /// Replace the current Sema; the compiler instance takes ownership
522 /// of S.
523 void setSema(Sema *S);
524
525 /// @}
526 /// @name ASTConsumer
527 /// @{
528
529 bool hasASTConsumer() const { return (bool)Consumer; }
530
532 assert(Consumer && "Compiler instance has no AST consumer!");
533 return *Consumer;
534 }
535
536 /// takeASTConsumer - Remove the current AST consumer and give ownership to
537 /// the caller.
538 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
539
540 /// setASTConsumer - Replace the current AST consumer; the compiler instance
541 /// takes ownership of \p Value.
542 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
543
544 /// @}
545 /// @name Semantic analysis
546 /// @{
547 bool hasSema() const { return (bool)TheSema; }
548
549 Sema &getSema() const {
550 assert(TheSema && "Compiler instance has no Sema object!");
551 return *TheSema;
552 }
553
554 std::unique_ptr<Sema> takeSema();
555 void resetAndLeakSema();
556
557 /// @}
558 /// @name Module Management
559 /// @{
560
563
564 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
566 std::shared_ptr<ModuleDependencyCollector> Collector);
567
568 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
569 return ThePCHContainerOperations;
570 }
571
572 /// Return the appropriate PCHContainerWriter depending on the
573 /// current CodeGenOptions.
575 assert(Invocation && "cannot determine module format without invocation");
576 StringRef Format = getHeaderSearchOpts().ModuleFormat;
577 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
578 if (!Writer) {
579 if (Diagnostics)
580 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
581 llvm::report_fatal_error("unknown module format");
582 }
583 return *Writer;
584 }
585
586 /// Return the appropriate PCHContainerReader depending on the
587 /// current CodeGenOptions.
589 assert(Invocation && "cannot determine module format without invocation");
590 StringRef Format = getHeaderSearchOpts().ModuleFormat;
591 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
592 if (!Reader) {
593 if (Diagnostics)
594 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
595 llvm::report_fatal_error("unknown module format");
596 }
597 return *Reader;
598 }
599
600 /// @}
601 /// @name Code Completion
602 /// @{
603
604 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
605
607 assert(CompletionConsumer &&
608 "Compiler instance has no code completion consumer!");
609 return *CompletionConsumer;
610 }
611
612 /// setCodeCompletionConsumer - Replace the current code completion consumer;
613 /// the compiler instance takes ownership of \p Value.
615
616 /// @}
617 /// @name Frontend timer
618 /// @{
619
620 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
621
622 llvm::Timer &getFrontendTimer() const {
623 assert(FrontendTimer && "Compiler instance has no frontend timer!");
624 return *FrontendTimer;
625 }
626
627 /// }
628 /// @name Output Files
629 /// @{
630
631 /// clearOutputFiles - Clear the output file list. The underlying output
632 /// streams must have been closed beforehand.
633 ///
634 /// \param EraseFiles - If true, attempt to erase the files from disk.
635 void clearOutputFiles(bool EraseFiles);
636
637 /// @}
638 /// @name Construction Utility Methods
639 /// @{
640
641 /// Create the diagnostics engine using the invocation's diagnostic options
642 /// and replace any existing one with it.
643 ///
644 /// Note that this routine also replaces the diagnostic client,
645 /// allocating one if one is not provided.
646 ///
647 /// \param VFS is used for any IO needed when creating DiagnosticsEngine. It
648 /// doesn't replace VFS in the CompilerInstance (if any).
649 ///
650 /// \param Client If non-NULL, a diagnostic client that will be
651 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
652 /// unit.
653 ///
654 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
655 /// the diagnostic object should take ownership of the client.
656 void createDiagnostics(llvm::vfs::FileSystem &VFS,
657 DiagnosticConsumer *Client = nullptr,
658 bool ShouldOwnClient = true);
659
660 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
661 ///
662 /// If no diagnostic client is provided, this creates a
663 /// DiagnosticConsumer that is owned by the returned diagnostic
664 /// object, if using directly the caller is responsible for
665 /// releasing the returned DiagnosticsEngine's client eventually.
666 ///
667 /// \param Opts - The diagnostic options; note that the created text
668 /// diagnostic object contains a reference to these options.
669 ///
670 /// \param Client If non-NULL, a diagnostic client that will be
671 /// attached to (and, then, owned by) the returned DiagnosticsEngine
672 /// object.
673 ///
674 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
675 /// used by some diagnostics printers (for logging purposes only).
676 ///
677 /// \return The new object on success, or null on failure.
679 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
680 DiagnosticConsumer *Client = nullptr,
681 bool ShouldOwnClient = true,
682 const CodeGenOptions *CodeGenOpts = nullptr);
683
684 /// Create the file manager and replace any existing one with it.
685 ///
686 /// \return The new file manager on success, or null on failure.
689
690 /// Create the source manager and replace any existing one with it.
691 void createSourceManager(FileManager &FileMgr);
692
693 /// Create the preprocessor, using the invocation, file, and source managers,
694 /// and replace any existing one with it.
696
698 std::unique_ptr<DependencyDirectivesGetter> Getter) {
699 GetDependencyDirectives = std::move(Getter);
700 }
701
702 std::string getSpecificModuleCachePath(StringRef ModuleHash);
704 return getSpecificModuleCachePath(getInvocation().getModuleHash());
705 }
706
707 /// Create the AST context.
708 void createASTContext();
709
710 /// Create an external AST source to read a PCH file and attach it to the AST
711 /// context.
713 StringRef Path, DisableValidationForModuleKind DisableValidation,
714 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
715 bool OwnDeserializationListener);
716
717 /// Create an external AST source to read a PCH file.
718 ///
719 /// \return - The new object on success, or null on failure.
721 StringRef Path, StringRef Sysroot,
722 DisableValidationForModuleKind DisableValidation,
723 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
724 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
725 const CodeGenOptions &CodeGenOpts,
726 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
727 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
728 void *DeserializationListener, bool OwnDeserializationListener,
729 bool Preamble, bool UseGlobalModuleIndex);
730
731 /// Create a code completion consumer using the invocation; note that this
732 /// will cause the source manager to truncate the input source file at the
733 /// completion point.
735
736 /// Create a code completion consumer to print code completion results, at
737 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
739 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
740 const CodeCompleteOptions &Opts, raw_ostream &OS);
741
742 /// Create the Sema object to be used for parsing.
744 CodeCompleteConsumer *CompletionConsumer);
745
746 /// Create the frontend timer and replace any existing one with it.
747 void createFrontendTimer();
748
749 /// Create the default output file (from the invocation's options) and add it
750 /// to the list of tracked output files.
751 ///
752 /// The files created by this are usually removed on signal, and, depending
753 /// on FrontendOptions, may also use a temporary file (that is, the data is
754 /// written to a temporary file which will atomically replace the target
755 /// output on success).
756 ///
757 /// \return - Null on error.
758 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
759 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
760 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
761 bool ForceUseTemporary = false);
762
763 /// Create a new output file, optionally deriving the output path name, and
764 /// add it to the list of tracked output files.
765 ///
766 /// \return - Null on error.
767 std::unique_ptr<raw_pwrite_stream>
768 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
769 bool UseTemporary, bool CreateMissingDirectories = false);
770
771private:
772 /// Create a new output file and add it to the list of tracked output files.
773 ///
774 /// If \p OutputPath is empty, then createOutputFile will derive an output
775 /// path location as \p BaseInput, with any suffix removed, and \p Extension
776 /// appended. If \p OutputPath is not stdout and \p UseTemporary
777 /// is true, createOutputFile will create a new temporary file that must be
778 /// renamed to \p OutputPath in the end.
779 ///
780 /// \param OutputPath - If given, the path to the output file.
781 /// \param Binary - The mode to open the file in.
782 /// \param RemoveFileOnSignal - Whether the file should be registered with
783 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
784 /// multithreaded use, as the underlying signal mechanism is not reentrant
785 /// \param UseTemporary - Create a new temporary file that must be renamed to
786 /// OutputPath in the end.
787 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
788 /// missing directories in the output path.
790 createOutputFileImpl(StringRef OutputPath, bool Binary,
791 bool RemoveFileOnSignal, bool UseTemporary,
792 bool CreateMissingDirectories);
793
794public:
795 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
796
797 /// @}
798 /// @name Initialization Utility Methods
799 /// @{
800
801 /// InitializeSourceManager - Initialize the source manager to set InputFile
802 /// as the main file.
803 ///
804 /// \return True on success.
806
807 /// InitializeSourceManager - Initialize the source manager to set InputFile
808 /// as the main file.
809 ///
810 /// \return True on success.
811 static bool InitializeSourceManager(const FrontendInputFile &Input,
812 DiagnosticsEngine &Diags,
813 FileManager &FileMgr,
814 SourceManager &SourceMgr);
815
816 /// @}
817
818 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
819 OutputStream = std::move(OutStream);
820 }
821
822 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
823 return std::move(OutputStream);
824 }
825
826 void createASTReader();
827
828 bool loadModuleFile(StringRef FileName,
829 serialization::ModuleFile *&LoadedModuleFile);
830
831 /// Configuration object for making the result of \c cloneForModuleCompile()
832 /// thread-safe.
835 DiagnosticConsumer &DiagConsumer;
836 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
837
838 public:
841 DiagnosticConsumer &DiagConsumer,
842 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector = nullptr)
843 : VFS(std::move(VFS)), DiagConsumer(DiagConsumer),
844 ModuleDepCollector(std::move(ModuleDepCollector)) {
845 assert(this->VFS && "Clone config requires non-null VFS");
846 }
847
849 DiagnosticConsumer &getDiagConsumer() const { return DiagConsumer; }
850 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const {
851 return ModuleDepCollector;
852 }
853 };
854
855private:
856 /// Find a module, potentially compiling it, before reading its AST. This is
857 /// the guts of loadModule.
858 ///
859 /// For prebuilt modules, the Module is not expected to exist in
860 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
861 /// ModuleManager, then it will be loaded and looked up.
862 ///
863 /// For implicit modules, the Module is expected to already be in the
864 /// ModuleMap. First attempt to load it from the given path on disk. If that
865 /// fails, defer to compileModuleAndReadAST, which will first build and then
866 /// load it.
867 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
868 SourceLocation ImportLoc,
869 SourceLocation ModuleNameLoc,
870 bool IsInclusionDirective);
871
872 /// Creates a \c CompilerInstance for compiling a module.
873 ///
874 /// This expects a properly initialized \c FrontendInputFile.
875 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
876 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
877 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
878 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
879
880public:
881 /// Creates a new \c CompilerInstance for compiling a module.
882 ///
883 /// This takes care of creating appropriate \c FrontendInputFile for
884 /// public/private frameworks, inferred modules and such.
885 ///
886 /// The \c ThreadSafeConfig takes precedence over the \c DiagnosticConsumer
887 /// and \c FileSystem of this instance (and disables \c FileManager sharing).
888 std::unique_ptr<CompilerInstance> cloneForModuleCompile(
889 SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName,
890 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
891
892 /// Compile a module file for the given module, using the options
893 /// provided by the importing compiler instance. Returns true if the module
894 /// was built without errors.
895 // FIXME: This should be private, but it's called from static non-member
896 // functions in the implementation file.
897 bool compileModule(SourceLocation ImportLoc, StringRef ModuleName,
898 StringRef ModuleFileName, CompilerInstance &Instance);
899
902 bool IsInclusionDirective) override;
903
904 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
905 StringRef Source) override;
906
908 SourceLocation ImportLoc) override;
909
912 }
913
915
916 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
917
918 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
919 DependencyCollectors.push_back(std::move(Listener));
920 }
921
923
924 ModuleCache &getModuleCache() const { return *ModCache; }
925};
926
927} // end namespace clang
928
929#endif
Defines the Diagnostic-related interfaces.
IndirectLocalPath & Path
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
StringRef Filename
Definition: Format.cpp:3177
llvm::MachO::Target Target
Definition: MachO.h:51
Defines the SourceManager interface.
Tracks various options which control how API notes are found and handled.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
Stores options for the analyzer from the command line.
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...
Configuration object for making the result of cloneForModuleCompile() thread-safe.
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
ThreadSafeCloneConfig(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagConsumer, std::shared_ptr< ModuleDependencyCollector > ModuleDepCollector=nullptr)
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVFS() const
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
void createPCHExternalASTSource(StringRef Path, DisableValidationForModuleKind DisableValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
DiagnosticConsumer & getDiagnosticClient() const
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
AnalyzerOptions & getAnalyzerOpts()
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.
const HeaderSearchOptions & getHeaderSearchOpts() const
DependencyOutputOptions & getDependencyOutputOpts()
const DependencyOutputOptions & getDependencyOutputOpts() const
std::shared_ptr< Preprocessor > getPreprocessorPtr()
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.
llvm::TimerGroup & getTimerGroup() const
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
bool compileModule(SourceLocation ImportLoc, StringRef ModuleName, StringRef ModuleFileName, CompilerInstance &Instance)
Compile a module file for the given module, using the options provided by the importing compiler inst...
void createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
const DiagnosticOptions & getDiagnosticOpts() const
std::string getSpecificModuleCachePath()
std::unique_ptr< CompilerInstance > cloneForModuleCompile(SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName, std::optional< ThreadSafeCloneConfig > ThreadSafeConfig=std::nullopt)
Creates a new CompilerInstance for compiling a module.
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
const CodeGenOptions & getCodeGenOpts() const
FileSystemOptions & getFileSystemOpts()
llvm::Timer & getFrontendTimer() const
const TargetOptions & getTargetOpts() const
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
void setOutputStream(std::unique_ptr< llvm::raw_pwrite_stream > OutStream)
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.
IntrusiveRefCntPtr< DiagnosticsEngine > getDiagnosticsPtr() const
std::unique_ptr< Sema > takeSema()
const PreprocessorOptions & getPreprocessorOpts() const
void printDiagnosticStats()
At the end of a compilation, print the number of warnings/errors.
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
IntrusiveRefCntPtr< FileManager > getFileManagerPtr() const
IntrusiveRefCntPtr< ASTContext > getASTContextPtr() const
ModuleCache & getModuleCache() const
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
IntrusiveRefCntPtr< ASTReader > getASTReader() const
void setTarget(TargetInfo *Value)
Replace the current Target.
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
void createASTContext()
Create the AST context.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file, optionally deriving the output path name, and add it to the list of tracked...
void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to create the given module from the specified source buffer.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
std::shared_ptr< CompilerInvocation > getInvocationPtr()
bool hadModuleLoaderFatalFailure() const
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
void setSourceManager(llvm::IntrusiveRefCntPtr< SourceManager > Value)
setSourceManager - Replace the current source manager.
void setASTContext(llvm::IntrusiveRefCntPtr< ASTContext > Value)
setASTContext - Replace the current AST context.
HeaderSearchOptions & getHeaderSearchOpts()
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
bool hasCodeCompletionConsumer() const
const LangOptions & getLangOpts() const
CompilerInvocation & getInvocation()
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
void setVerboseOutputStream(raw_ostream &Value)
Replace the current stream for verbose output.
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
PreprocessorOptions & getPreprocessorOpts()
ASTConsumer & getASTConsumer() const
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager and virtual file system.
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
const FileSystemOptions & getFileSystemOpts() 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()
const APINotesOptions & getAPINotesOpts() const
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
IntrusiveRefCntPtr< SourceManager > getSourceManagerPtr() const
CodeCompleteConsumer & getCodeCompletionConsumer() const
void setDiagnostics(llvm::IntrusiveRefCntPtr< DiagnosticsEngine > Value)
setDiagnostics - Replace the current diagnostics engine.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
APINotesOptions & getAPINotesOpts()
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool loadModuleFile(StringRef FileName, serialization::ModuleFile *&LoadedModuleFile)
void setDependencyDirectivesGetter(std::unique_ptr< DependencyDirectivesGetter > Getter)
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.
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
Definition: Diagnostic.h:1722
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
Keeps track of options that affect how file operations are performed.
Abstract base class for actions which can be performed by the frontend.
An input file for the front end.
FrontendOptions - Options for controlling the behavior of the frontend.
A global index for a set of module files, providing information about the identifiers within those mo...
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
std::string ModuleFormat
The module/pch container format.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
The module cache used for compiling modules implicitly.
Definition: ModuleCache.h:26
Describes the result of attempting to load a module.
Definition: ModuleLoader.h:36
Abstract interface for a module loader.
Definition: ModuleLoader.h:83
Describes a module or submodule.
Definition: Module.h:144
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:443
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
This abstract interface provides operations for creating containers for serialized ASTs (precompiled ...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition: TargetInfo.h:226
Options for controlling the target.
Definition: TargetOptions.h:26
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:130
Defines the clang::TargetInfo interface.
@ ModuleFile
The module file (.pcm). Required.
The JSON file list parser is used to communicate input to InstallAPI.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1097
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30