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 "llvm/Support/VirtualOutputBackend.h"
30#include <cassert>
31#include <list>
32#include <memory>
33#include <optional>
34#include <string>
35#include <utility>
36
37namespace llvm {
38class raw_fd_ostream;
39class Timer;
40class TimerGroup;
41}
42
43namespace clang {
44class ASTContext;
45class ASTReader;
46
47namespace serialization {
48class ModuleFile;
49}
50
54class FileManager;
55class FrontendAction;
56class Module;
57class ModuleCache;
58class Preprocessor;
59class Sema;
60class SourceManager;
61class TargetInfo;
63
64/// CompilerInstance - Helper class for managing a single instance of the Clang
65/// compiler.
66///
67/// The CompilerInstance serves two purposes:
68/// (1) It manages the various objects which are necessary to run the compiler,
69/// for example the preprocessor, the target information, and the AST
70/// context.
71/// (2) It provides utility routines for constructing and manipulating the
72/// common Clang objects.
73///
74/// The compiler instance generally owns the instance of all the objects that it
75/// manages. However, clients can still share objects by manually setting the
76/// object and retaking ownership prior to destroying the CompilerInstance.
77///
78/// The compiler instance is intended to simplify clients, but not to lock them
79/// in to the compiler instance for everything. When possible, utility functions
80/// come in two forms; a short form that reuses the CompilerInstance objects,
81/// and a long form that takes explicit instances of any required objects.
82class CompilerInstance : public ModuleLoader {
83 /// The options used in this compiler instance.
84 std::shared_ptr<CompilerInvocation> Invocation;
85
86 /// The virtual file system instance.
88
89 /// The diagnostics engine instance.
91
92 /// The target being compiled for.
94
95 /// Options for the auxiliary target.
96 std::unique_ptr<TargetOptions> AuxTargetOpts;
97
98 /// Auxiliary Target info.
100
101 /// The file manager.
103
104 /// The output manager.
106
107 /// The source manager.
109
110 /// The cache of PCM files.
112
113 /// Functor for getting the dependency preprocessor directives of a file.
114 std::unique_ptr<DependencyDirectivesGetter> GetDependencyDirectives;
115
116 /// The preprocessor.
117 std::shared_ptr<Preprocessor> PP;
118
119 /// The AST context.
121
122 /// An optional sema source that will be attached to sema.
124
125 /// The AST consumer.
126 std::unique_ptr<ASTConsumer> Consumer;
127
128 /// The code completion consumer.
129 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
130
131 /// The semantic analysis object.
132 std::unique_ptr<Sema> TheSema;
133
134 /// The frontend timer group.
135 std::unique_ptr<llvm::TimerGroup> timerGroup;
136
137 /// The frontend timer.
138 std::unique_ptr<llvm::Timer> FrontendTimer;
139
140 /// The ASTReader, if one exists.
142
143 /// The module dependency collector for crashdumps
144 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
145
146 /// The module provider.
147 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
148
149 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
150
151 /// The set of modules that failed to build.
152 ///
153 /// This value will be passed among all of the compiler instances created
154 /// to (re)build modules, so that once a module fails to build anywhere,
155 /// other instances will see that the module has failed and won't try to
156 /// build it again.
157 llvm::StringSet<> FailedModules;
158
159 /// The set of top-level modules that has already been built on the
160 /// fly as part of this overall compilation action.
161 std::map<std::string, std::string, std::less<>> BuiltModules;
162
163 /// Should we delete the BuiltModules when we're done?
164 bool DeleteBuiltModules = true;
165
166 /// The location of the module-import keyword for the last module
167 /// import.
168 SourceLocation LastModuleImportLoc;
169
170 /// The result of the last module import.
171 ///
172 ModuleLoadResult LastModuleImportResult;
173
174 /// Whether we should (re)build the global module index once we
175 /// have finished with this translation unit.
176 bool BuildGlobalModuleIndex = false;
177
178 /// We have a full global module index, with all modules.
179 bool HaveFullGlobalModuleIndex = false;
180
181 /// One or more modules failed to build.
182 bool DisableGeneratingGlobalModuleIndex = false;
183
184 /// The stream for verbose output if owned, otherwise nullptr.
185 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
186
187 /// The stream for verbose output.
188 raw_ostream *VerboseOutputStream = &llvm::errs();
189
190 /// The list of active output files.
191 std::list<llvm::vfs::OutputFile> OutputFiles;
192
193 /// Force an output buffer.
194 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
195
196 CompilerInstance(const CompilerInstance &) = delete;
197 void operator=(const CompilerInstance &) = delete;
198public:
199 explicit CompilerInstance(
200 std::shared_ptr<CompilerInvocation> Invocation =
201 std::make_shared<CompilerInvocation>(),
202 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
203 std::make_shared<PCHContainerOperations>(),
204 ModuleCache *ModCache = nullptr);
205 ~CompilerInstance() override;
206
207 /// @name High-Level Operations
208 /// @{
209
210 /// ExecuteAction - Execute the provided action against the compiler's
211 /// CompilerInvocation object.
212 ///
213 /// This function makes the following assumptions:
214 ///
215 /// - The invocation options should be initialized. This function does not
216 /// handle the '-help' or '-version' options, clients should handle those
217 /// directly.
218 ///
219 /// - The diagnostics engine should have already been created by the client.
220 ///
221 /// - No other CompilerInstance state should have been initialized (this is
222 /// an unchecked error).
223 ///
224 /// - Clients should have initialized any LLVM target features that may be
225 /// required.
226 ///
227 /// - Clients should eventually call llvm_shutdown() upon the completion of
228 /// this routine to ensure that any managed objects are properly destroyed.
229 ///
230 /// Note that this routine may write output to 'stderr'.
231 ///
232 /// \param Act - The action to execute.
233 /// \return - True on success.
234 //
235 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
236 // of the context or else not CompilerInstance specific.
237 bool ExecuteAction(FrontendAction &Act);
238
239 /// At the end of a compilation, print the number of warnings/errors.
241
242 /// Load the list of plugins requested in the \c FrontendOptions.
244
245 /// @}
246 /// @name Compiler Invocation and Options
247 /// @{
248
249 CompilerInvocation &getInvocation() { return *Invocation; }
250
251 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
252
253 /// Indicates whether we should (re)build the global module index.
254 bool shouldBuildGlobalModuleIndex() const;
255
256 /// Set the flag indicating whether we should (re)build the global
257 /// module index.
258 void setBuildGlobalModuleIndex(bool Build) {
259 BuildGlobalModuleIndex = Build;
260 }
261
262 /// @}
263 /// @name Forwarding Methods
264 /// @{
265
266 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
267
269 return Invocation->getCodeGenOpts();
270 }
272 return Invocation->getCodeGenOpts();
273 }
274
276 return Invocation->getDependencyOutputOpts();
277 }
279 return Invocation->getDependencyOutputOpts();
280 }
281
283 return Invocation->getDiagnosticOpts();
284 }
286 return Invocation->getDiagnosticOpts();
287 }
288
290 return Invocation->getFileSystemOpts();
291 }
293 return Invocation->getFileSystemOpts();
294 }
295
297 return Invocation->getFrontendOpts();
298 }
300 return Invocation->getFrontendOpts();
301 }
302
304 return Invocation->getHeaderSearchOpts();
305 }
307 return Invocation->getHeaderSearchOpts();
308 }
309
310 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
312 return Invocation->getAPINotesOpts();
313 }
314
315 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
316 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
317
319 return Invocation->getPreprocessorOpts();
320 }
322 return Invocation->getPreprocessorOpts();
323 }
324
326 return Invocation->getPreprocessorOutputOpts();
327 }
329 return Invocation->getPreprocessorOutputOpts();
330 }
331
333 return Invocation->getTargetOpts();
334 }
336 return Invocation->getTargetOpts();
337 }
338
339 /// @}
340 /// @name Diagnostics Engine
341 /// @{
342
343 bool hasDiagnostics() const { return Diagnostics != nullptr; }
344
345 /// Get the current diagnostics engine.
347 assert(Diagnostics && "Compiler instance has no diagnostics!");
348 return *Diagnostics;
349 }
350
352 assert(Diagnostics && "Compiler instance has no diagnostics!");
353 return Diagnostics;
354 }
355
356 /// setDiagnostics - Replace the current diagnostics engine.
358
360 assert(Diagnostics && Diagnostics->getClient() &&
361 "Compiler instance has no diagnostic client!");
362 return *Diagnostics->getClient();
363 }
364
365 /// @}
366 /// @name VerboseOutputStream
367 /// @{
368
369 /// Replace the current stream for verbose output.
370 void setVerboseOutputStream(raw_ostream &Value);
371
372 /// Replace the current stream for verbose output.
373 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
374
375 /// Get the current stream for verbose output.
376 raw_ostream &getVerboseOutputStream() {
377 return *VerboseOutputStream;
378 }
379
380 /// @}
381 /// @name Target Info
382 /// @{
383
384 bool hasTarget() const { return Target != nullptr; }
385
387 assert(Target && "Compiler instance has no target!");
388 return *Target;
389 }
390
392 assert(Target && "Compiler instance has no target!");
393 return Target;
394 }
395
396 /// Replace the current Target.
398
399 /// @}
400 /// @name AuxTarget Info
401 /// @{
402
403 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
404
405 /// Replace the current AuxTarget.
407
408 // Create Target and AuxTarget based on current options
409 bool createTarget();
410
411 /// @}
412 /// @name Virtual File System
413 /// @{
414
415 bool hasVirtualFileSystem() const { return VFS != nullptr; }
416
417 /// Create a virtual file system instance based on the invocation.
418 ///
419 /// @param BaseFS The file system that may be used when configuring the final
420 /// file system, and act as the underlying file system. Must not
421 /// be NULL.
422 /// @param DC If non-NULL, the diagnostic consumer to be used in case
423 /// configuring the file system emits diagnostics. Note that the
424 /// DiagnosticsEngine using the consumer won't obey the
425 /// --warning-suppression-mappings= flag.
427 BaseFS = llvm::vfs::getRealFileSystem(),
428 DiagnosticConsumer *DC = nullptr);
429
430 /// Use the given file system.
432 VFS = std::move(FS);
433 }
434
435 llvm::vfs::FileSystem &getVirtualFileSystem() const { return *VFS; }
436
440
441 /// @}
442 /// @name File Manager
443 /// @{
444
445 bool hasFileManager() const { return FileMgr != nullptr; }
446
447 /// Return the current file manager to the caller.
449 assert(FileMgr && "Compiler instance has no file manager!");
450 return *FileMgr;
451 }
452
454 assert(FileMgr && "Compiler instance has no file manager!");
455 return FileMgr;
456 }
457
459 llvm::BuryPointer(FileMgr.get());
460 FileMgr.resetWithoutRelease();
461 }
462
463 /// Replace the current file manager and virtual file system.
465
466 /// @}
467 /// @name Output Manager
468 /// @{
469
470 /// Set the output manager.
471 void
473
474 /// Create an output manager.
475 void createOutputManager();
476
477 bool hasOutputManager() const { return bool(OutputMgr); }
478
479 llvm::vfs::OutputBackend &getOutputManager();
480 llvm::vfs::OutputBackend &getOrCreateOutputManager();
481
482 /// @}
483 /// @name Source Manager
484 /// @{
485
486 bool hasSourceManager() const { return SourceMgr != nullptr; }
487
488 /// Return the current source manager.
490 assert(SourceMgr && "Compiler instance has no source manager!");
491 return *SourceMgr;
492 }
493
495 assert(SourceMgr && "Compiler instance has no source manager!");
496 return SourceMgr;
497 }
498
500 llvm::BuryPointer(SourceMgr.get());
501 SourceMgr.resetWithoutRelease();
502 }
503
504 /// setSourceManager - Replace the current source manager.
506
507 /// @}
508 /// @name Preprocessor
509 /// @{
510
511 bool hasPreprocessor() const { return PP != nullptr; }
512
513 /// Return the current preprocessor.
515 assert(PP && "Compiler instance has no preprocessor!");
516 return *PP;
517 }
518
519 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
520
522 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
523 }
524
525 /// Replace the current preprocessor.
526 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
527
528 /// @}
529 /// @name ASTContext
530 /// @{
531
532 bool hasASTContext() const { return Context != nullptr; }
533
535 assert(Context && "Compiler instance has no AST context!");
536 return *Context;
537 }
538
540 assert(Context && "Compiler instance has no AST context!");
541 return Context;
542 }
543
545 llvm::BuryPointer(Context.get());
546 Context.resetWithoutRelease();
547 }
548
549 /// setASTContext - Replace the current AST context.
551
552 /// Replace the current Sema; the compiler instance takes ownership
553 /// of S.
554 void setSema(Sema *S);
555
556 /// @}
557 /// @name ASTConsumer
558 /// @{
559
560 bool hasASTConsumer() const { return (bool)Consumer; }
561
563 assert(Consumer && "Compiler instance has no AST consumer!");
564 return *Consumer;
565 }
566
567 /// takeASTConsumer - Remove the current AST consumer and give ownership to
568 /// the caller.
569 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
570
571 /// setASTConsumer - Replace the current AST consumer; the compiler instance
572 /// takes ownership of \p Value.
573 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
574
575 /// @}
576 /// @name Semantic analysis
577 /// @{
578 bool hasSema() const { return (bool)TheSema; }
579
580 Sema &getSema() const {
581 assert(TheSema && "Compiler instance has no Sema object!");
582 return *TheSema;
583 }
584
585 std::unique_ptr<Sema> takeSema();
586 void resetAndLeakSema();
587
588 /// @}
589 /// @name Module Management
590 /// @{
591
594
595 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
597 std::shared_ptr<ModuleDependencyCollector> Collector);
598
599 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
600 return ThePCHContainerOperations;
601 }
602
603 /// Return the appropriate PCHContainerWriter depending on the
604 /// current CodeGenOptions.
606 assert(Invocation && "cannot determine module format without invocation");
607 StringRef Format = getHeaderSearchOpts().ModuleFormat;
608 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
609 if (!Writer) {
610 if (Diagnostics)
611 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
612 llvm::report_fatal_error("unknown module format");
613 }
614 return *Writer;
615 }
616
617 /// Return the appropriate PCHContainerReader depending on the
618 /// current CodeGenOptions.
620 assert(Invocation && "cannot determine module format without invocation");
621 StringRef Format = getHeaderSearchOpts().ModuleFormat;
622 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
623 if (!Reader) {
624 if (Diagnostics)
625 Diagnostics->Report(diag::err_module_format_unhandled) << Format;
626 llvm::report_fatal_error("unknown module format");
627 }
628 return *Reader;
629 }
630
631 /// @}
632 /// @name Code Completion
633 /// @{
634
635 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
636
638 assert(CompletionConsumer &&
639 "Compiler instance has no code completion consumer!");
640 return *CompletionConsumer;
641 }
642
643 /// setCodeCompletionConsumer - Replace the current code completion consumer;
644 /// the compiler instance takes ownership of \p Value.
646
647 /// @}
648 /// @name Frontend timer
649 /// @{
650
651 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
652
653 llvm::Timer &getFrontendTimer() const {
654 assert(FrontendTimer && "Compiler instance has no frontend timer!");
655 return *FrontendTimer;
656 }
657
658 /// }
659 /// @name Output Files
660 /// @{
661
662 /// clearOutputFiles - Clear the output file list. The underlying output
663 /// streams must have been closed beforehand.
664 ///
665 /// \param EraseFiles - If true, attempt to erase the files from disk.
666 void clearOutputFiles(bool EraseFiles);
667
668 /// @}
669 /// @name Construction Utility Methods
670 /// @{
671
672 /// Create the diagnostics engine using the invocation's diagnostic options
673 /// and replace any existing one with it.
674 ///
675 /// Note that this routine also replaces the diagnostic client,
676 /// allocating one if one is not provided.
677 ///
678 /// \param Client If non-NULL, a diagnostic client that will be
679 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
680 /// unit.
681 ///
682 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
683 /// the diagnostic object should take ownership of the client.
684 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
685 bool ShouldOwnClient = true);
686
687 /// Create a DiagnosticsEngine object.
688 ///
689 /// If no diagnostic client is provided, this creates a
690 /// DiagnosticConsumer that is owned by the returned diagnostic
691 /// object, if using directly the caller is responsible for
692 /// releasing the returned DiagnosticsEngine's client eventually.
693 ///
694 /// \param VFS The file system used to load the suppression mappings file.
695 ///
696 /// \param Opts - The diagnostic options; note that the created text
697 /// diagnostic object contains a reference to these options.
698 ///
699 /// \param Client If non-NULL, a diagnostic client that will be
700 /// attached to (and, then, owned by) the returned DiagnosticsEngine
701 /// object. If NULL, the returned DiagnosticsEngine will own a newly-created
702 /// client.
703 ///
704 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
705 /// used by some diagnostics printers (for logging purposes only).
706 ///
707 /// \return The new object on success, or null on failure.
709 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
710 DiagnosticConsumer *Client = nullptr,
711 bool ShouldOwnClient = true,
712 const CodeGenOptions *CodeGenOpts = nullptr);
713
714 /// Create the file manager and replace any existing one with it.
715 ///
716 /// \return The new file manager on success, or null on failure.
718
719 /// Create the source manager and replace any existing one with it.
721
722 /// Create the preprocessor, using the invocation, file, and source managers,
723 /// and replace any existing one with it.
725
727 std::unique_ptr<DependencyDirectivesGetter> Getter) {
728 GetDependencyDirectives = std::move(Getter);
729 }
730
731 std::string getSpecificModuleCachePath(StringRef ModuleHash);
733 return getSpecificModuleCachePath(getInvocation().getModuleHash());
734 }
735
736 /// Create the AST context.
737 void createASTContext();
738
739 /// Create an external AST source to read a PCH file and attach it to the AST
740 /// context.
742 StringRef Path, DisableValidationForModuleKind DisableValidation,
743 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
744 bool OwnDeserializationListener);
745
746 /// Create an external AST source to read a PCH file.
747 ///
748 /// \return - The new object on success, or null on failure.
750 StringRef Path, StringRef Sysroot,
751 DisableValidationForModuleKind DisableValidation,
752 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
753 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
754 const CodeGenOptions &CodeGenOpts,
755 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
756 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
757 void *DeserializationListener, bool OwnDeserializationListener,
758 bool Preamble, bool UseGlobalModuleIndex);
759
760 /// Create a code completion consumer using the invocation; note that this
761 /// will cause the source manager to truncate the input source file at the
762 /// completion point.
764
765 /// Create a code completion consumer to print code completion results, at
766 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
768 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
769 const CodeCompleteOptions &Opts, raw_ostream &OS);
770
771 /// Create the Sema object to be used for parsing.
773 CodeCompleteConsumer *CompletionConsumer);
774
775 /// Create the frontend timer and replace any existing one with it.
776 void createFrontendTimer();
777
778 /// Create the default output file (from the invocation's options) and add it
779 /// to the list of tracked output files.
780 ///
781 /// The files created by this are usually removed on signal, and, depending
782 /// on FrontendOptions, may also use a temporary file (that is, the data is
783 /// written to a temporary file which will atomically replace the target
784 /// output on success).
785 ///
786 /// \return - Null on error.
787 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
788 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
789 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
790 bool ForceUseTemporary = false);
791
792 /// Create a new output file, optionally deriving the output path name, and
793 /// add it to the list of tracked output files.
794 ///
795 /// \return - Null on error.
796 std::unique_ptr<raw_pwrite_stream>
797 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
798 bool UseTemporary, bool CreateMissingDirectories = false);
799
800private:
801 /// Create a new output file and add it to the list of tracked output files.
802 ///
803 /// If \p OutputPath is empty, then createOutputFile will derive an output
804 /// path location as \p BaseInput, with any suffix removed, and \p Extension
805 /// appended. If \p OutputPath is not stdout and \p UseTemporary
806 /// is true, createOutputFile will create a new temporary file that must be
807 /// renamed to \p OutputPath in the end.
808 ///
809 /// \param OutputPath - If given, the path to the output file.
810 /// \param Binary - The mode to open the file in.
811 /// \param RemoveFileOnSignal - Whether the file should be registered with
812 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
813 /// multithreaded use, as the underlying signal mechanism is not reentrant
814 /// \param UseTemporary - Create a new temporary file that must be renamed to
815 /// OutputPath in the end.
816 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
817 /// missing directories in the output path.
819 createOutputFileImpl(StringRef OutputPath, bool Binary,
820 bool RemoveFileOnSignal, bool UseTemporary,
821 bool CreateMissingDirectories);
822
823public:
824 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
825
826 /// @}
827 /// @name Initialization Utility Methods
828 /// @{
829
830 /// InitializeSourceManager - Initialize the source manager to set InputFile
831 /// as the main file.
832 ///
833 /// \return True on success.
835
836 /// InitializeSourceManager - Initialize the source manager to set InputFile
837 /// as the main file.
838 ///
839 /// \return True on success.
840 static bool InitializeSourceManager(const FrontendInputFile &Input,
841 DiagnosticsEngine &Diags,
843 SourceManager &SourceMgr);
844
845 /// @}
846
847 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
848 OutputStream = std::move(OutStream);
849 }
850
851 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
852 return std::move(OutputStream);
853 }
854
855 void createASTReader();
856
857 bool loadModuleFile(StringRef FileName,
858 serialization::ModuleFile *&LoadedModuleFile);
859
860 /// Configuration object for making the result of \c cloneForModuleCompile()
861 /// thread-safe.
864 DiagnosticConsumer &DiagConsumer;
865 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
866
867 public:
870 DiagnosticConsumer &DiagConsumer,
871 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector = nullptr)
872 : VFS(std::move(VFS)), DiagConsumer(DiagConsumer),
873 ModuleDepCollector(std::move(ModuleDepCollector)) {
874 assert(this->VFS && "Clone config requires non-null VFS");
875 }
876
878 DiagnosticConsumer &getDiagConsumer() const { return DiagConsumer; }
879 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const {
880 return ModuleDepCollector;
881 }
882 };
883
884private:
885 /// Find a module, potentially compiling it, before reading its AST. This is
886 /// the guts of loadModule.
887 ///
888 /// For prebuilt modules, the Module is not expected to exist in
889 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
890 /// ModuleManager, then it will be loaded and looked up.
891 ///
892 /// For implicit modules, the Module is expected to already be in the
893 /// ModuleMap. First attempt to load it from the given path on disk. If that
894 /// fails, defer to compileModuleAndReadAST, which will first build and then
895 /// load it.
896 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
897 SourceLocation ImportLoc,
898 SourceLocation ModuleNameLoc,
899 bool IsInclusionDirective);
900
901 /// Creates a \c CompilerInstance for compiling a module.
902 ///
903 /// This expects a properly initialized \c FrontendInputFile.
904 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
905 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
906 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
907 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
908
909public:
910 /// Creates a new \c CompilerInstance for compiling a module.
911 ///
912 /// This takes care of creating appropriate \c FrontendInputFile for
913 /// public/private frameworks, inferred modules and such.
914 ///
915 /// The \c ThreadSafeConfig takes precedence over the \c DiagnosticConsumer
916 /// and \c FileSystem of this instance (and disables \c FileManager sharing).
917 std::unique_ptr<CompilerInstance> cloneForModuleCompile(
918 SourceLocation ImportLoc, Module *Module, StringRef ModuleFileName,
919 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
920
921 /// Compile a module file for the given module, using the options
922 /// provided by the importing compiler instance. Returns true if the module
923 /// was built without errors.
924 // FIXME: This should be private, but it's called from static non-member
925 // functions in the implementation file.
926 bool compileModule(SourceLocation ImportLoc, StringRef ModuleName,
927 StringRef ModuleFileName, CompilerInstance &Instance);
928
931 bool IsInclusionDirective) override;
932
933 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
934 StringRef Source) override;
935
937 SourceLocation ImportLoc) override;
938
942
944
945 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
946
947 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
948 DependencyCollectors.push_back(std::move(Listener));
949 }
950
952
953 ModuleCache &getModuleCache() const { return *ModCache; }
954};
955
956} // end namespace clang
957
958#endif
Defines the Diagnostic-related interfaces.
This is the interface for scanning header and source files to get the minimum necessary preprocessor ...
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
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:430
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...
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.
void setOutputManager(IntrusiveRefCntPtr< llvm::vfs::OutputBackend > NewOutputs)
Set the output manager.
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
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...
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 setVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
Use the given file system.
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
void createOutputManager()
Create an output manager.
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
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
TargetOptions & getTargetOpts()
IntrusiveRefCntPtr< TargetInfo > getTargetPtr() const
void createVirtualFileSystem(IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS=llvm::vfs::getRealFileSystem(), DiagnosticConsumer *DC=nullptr)
Create a virtual file system instance based on the invocation.
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
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.
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()
FileManager * createFileManager()
Create the file manager and replace any existing one with it.
ASTConsumer & getASTConsumer() const
void setFileManager(IntrusiveRefCntPtr< FileManager > Value)
Replace the current file manager and virtual file system.
TargetInfo & getTarget() const
llvm::vfs::OutputBackend & getOutputManager()
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()
llvm::vfs::OutputBackend & getOrCreateOutputManager()
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...
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...
The module cache used for compiling modules implicitly.
Definition ModuleCache.h:26
Describes the result of attempting to load a module.
ModuleLoader(bool BuildingModule=false)
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.
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
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.
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:130
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
ArrayRef< IdentifierLoc > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule,...
TranslationUnitKind
Describes the kind of translation unit being processed.
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