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