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