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
12#include "clang/AST/ASTConsumer.h"
13#include "clang/Basic/Diagnostic.h"
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/Frontend/CompilerInvocation.h"
17#include "clang/Frontend/PCHContainerOperations.h"
18#include "clang/Frontend/Utils.h"
19#include "clang/Lex/DependencyDirectivesScanner.h"
20#include "clang/Lex/HeaderSearch.h"
21#include "clang/Lex/HeaderSearchOptions.h"
22#include "clang/Lex/ModuleLoader.h"
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
53class CodeCompleteConsumer;
54class DiagnosticsEngine;
55class DiagnosticConsumer;
56class FileManager;
57class FrontendAction;
58class Module;
59class ModuleCache;
60class Preprocessor;
61class Sema;
62class SourceManager;
63class TargetInfo;
64enum class DisableValidationForModuleKind;
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.
89 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
90
91 /// The diagnostics engine instance.
92 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
93
94 /// The target being compiled for.
95 IntrusiveRefCntPtr<TargetInfo> Target;
96
97 /// Options for the auxiliary target.
98 std::unique_ptr<TargetOptions> AuxTargetOpts;
99
100 /// Auxiliary Target info.
101 IntrusiveRefCntPtr<TargetInfo> AuxTarget;
102
103 /// The file manager.
104 IntrusiveRefCntPtr<FileManager> FileMgr;
105
106 /// The output manager.
107 IntrusiveRefCntPtr<llvm::vfs::OutputBackend> OutputMgr;
108
109 /// The source manager.
110 IntrusiveRefCntPtr<SourceManager> SourceMgr;
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.
122 IntrusiveRefCntPtr<ASTContext> Context;
123
124 /// An optional sema source that will be attached to sema.
125 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSemaSrc;
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.
146 IntrusiveRefCntPtr<ASTReader> TheASTReader;
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 /// The location of the module-import keyword for the last module
172 /// import.
173 SourceLocation LastModuleImportLoc;
174
175 /// The result of the last module import.
176 ///
177 ModuleLoadResult LastModuleImportResult;
178
179 /// Whether we should (re)build the global module index once we
180 /// have finished with this translation unit.
181 bool BuildGlobalModuleIndex = false;
182
183 /// We have a full global module index, with all modules.
184 bool HaveFullGlobalModuleIndex = false;
185
186 /// One or more modules failed to build.
187 bool DisableGeneratingGlobalModuleIndex = false;
188
189 /// The stream for verbose output if owned, otherwise nullptr.
190 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream;
191
192 /// The stream for verbose output.
193 raw_ostream *VerboseOutputStream = &llvm::errs();
194
195 /// The list of active output files.
196 std::list<llvm::vfs::OutputFile> OutputFiles;
197
198 /// Force an output buffer.
199 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream;
200
201 using GenModuleActionWrapperFunc =
202 std::function<std::unique_ptr<FrontendAction>(
203 const FrontendOptions &, std::unique_ptr<FrontendAction>)>;
204
205 /// An optional callback function used to wrap all FrontendActions
206 /// produced to generate imported modules before they are executed.
207 GenModuleActionWrapperFunc GenModuleActionWrapper;
208
209 CompilerInstance(const CompilerInstance &) = delete;
210 void operator=(const CompilerInstance &) = delete;
211public:
212 explicit CompilerInstance(
213 std::shared_ptr<CompilerInvocation> Invocation =
214 std::make_shared<CompilerInvocation>(),
215 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
216 std::make_shared<PCHContainerOperations>(),
217 std::shared_ptr<ModuleCache> ModCache = nullptr);
218 ~CompilerInstance() override;
219
220 /// @name High-Level Operations
221 /// @{
222
223 /// ExecuteAction - Execute the provided action against the compiler's
224 /// CompilerInvocation object.
225 ///
226 /// This function makes the following assumptions:
227 ///
228 /// - The invocation options should be initialized. This function does not
229 /// handle the '-help' or '-version' options, clients should handle those
230 /// directly.
231 ///
232 /// - The diagnostics engine should have already been created by the client.
233 ///
234 /// - No other CompilerInstance state should have been initialized (this is
235 /// an unchecked error).
236 ///
237 /// - Clients should have initialized any LLVM target features that may be
238 /// required.
239 ///
240 /// - Clients should eventually call llvm_shutdown() upon the completion of
241 /// this routine to ensure that any managed objects are properly destroyed.
242 ///
243 /// Note that this routine may write output to 'stderr'.
244 ///
245 /// \param Act - The action to execute.
246 /// \return - True on success.
247 //
248 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
249 // of the context or else not CompilerInstance specific.
250 bool ExecuteAction(FrontendAction &Act);
251
252 /// At the end of a compilation, print the number of warnings/errors.
253 void printDiagnosticStats();
254
255 /// Load the list of plugins requested in the \c FrontendOptions.
256 void LoadRequestedPlugins();
257
258 /// @}
259 /// @name Compiler Invocation and Options
260 /// @{
261
262 CompilerInvocation &getInvocation() { return *Invocation; }
263
264 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; }
265
266 /// Indicates whether we should (re)build the global module index.
267 bool shouldBuildGlobalModuleIndex() const;
268
269 /// Set the flag indicating whether we should (re)build the global
270 /// module index.
271 void setBuildGlobalModuleIndex(bool Build) {
272 BuildGlobalModuleIndex = Build;
273 }
274
275 /// @}
276 /// @name Forwarding Methods
277 /// @{
278
279 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); }
280
281 CodeGenOptions &getCodeGenOpts() {
282 return Invocation->getCodeGenOpts();
283 }
284 const CodeGenOptions &getCodeGenOpts() const {
285 return Invocation->getCodeGenOpts();
286 }
287
288 DependencyOutputOptions &getDependencyOutputOpts() {
289 return Invocation->getDependencyOutputOpts();
290 }
291 const DependencyOutputOptions &getDependencyOutputOpts() const {
292 return Invocation->getDependencyOutputOpts();
293 }
294
295 DiagnosticOptions &getDiagnosticOpts() {
296 return Invocation->getDiagnosticOpts();
297 }
298 const DiagnosticOptions &getDiagnosticOpts() const {
299 return Invocation->getDiagnosticOpts();
300 }
301
302 FileSystemOptions &getFileSystemOpts() {
303 return Invocation->getFileSystemOpts();
304 }
305 const FileSystemOptions &getFileSystemOpts() const {
306 return Invocation->getFileSystemOpts();
307 }
308
309 FrontendOptions &getFrontendOpts() {
310 return Invocation->getFrontendOpts();
311 }
312 const FrontendOptions &getFrontendOpts() const {
313 return Invocation->getFrontendOpts();
314 }
315
316 HeaderSearchOptions &getHeaderSearchOpts() {
317 return Invocation->getHeaderSearchOpts();
318 }
319 const HeaderSearchOptions &getHeaderSearchOpts() const {
320 return Invocation->getHeaderSearchOpts();
321 }
322
323 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); }
324 const APINotesOptions &getAPINotesOpts() const {
325 return Invocation->getAPINotesOpts();
326 }
327
328 LangOptions &getLangOpts() { return Invocation->getLangOpts(); }
329 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); }
330
331 PreprocessorOptions &getPreprocessorOpts() {
332 return Invocation->getPreprocessorOpts();
333 }
334 const PreprocessorOptions &getPreprocessorOpts() const {
335 return Invocation->getPreprocessorOpts();
336 }
337
338 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
339 return Invocation->getPreprocessorOutputOpts();
340 }
341 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
342 return Invocation->getPreprocessorOutputOpts();
343 }
344
345 TargetOptions &getTargetOpts() {
346 return Invocation->getTargetOpts();
347 }
348 const TargetOptions &getTargetOpts() const {
349 return Invocation->getTargetOpts();
350 }
351
352 /// @}
353 /// @name Diagnostics Engine
354 /// @{
355
356 bool hasDiagnostics() const { return Diagnostics != nullptr; }
357
358 /// Get the current diagnostics engine.
359 DiagnosticsEngine &getDiagnostics() const {
360 assert(Diagnostics && "Compiler instance has no diagnostics!");
361 return *Diagnostics;
362 }
363
364 IntrusiveRefCntPtr<DiagnosticsEngine> getDiagnosticsPtr() const {
365 assert(Diagnostics && "Compiler instance has no diagnostics!");
366 return Diagnostics;
367 }
368
369 /// setDiagnostics - Replace the current diagnostics engine.
370 void setDiagnostics(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Value);
371
372 DiagnosticConsumer &getDiagnosticClient() const {
373 assert(Diagnostics && Diagnostics->getClient() &&
374 "Compiler instance has no diagnostic client!");
375 return *Diagnostics->getClient();
376 }
377
378 /// @}
379 /// @name VerboseOutputStream
380 /// @{
381
382 /// Replace the current stream for verbose output.
383 void setVerboseOutputStream(raw_ostream &Value);
384
385 /// Replace the current stream for verbose output.
386 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value);
387
388 /// Get the current stream for verbose output.
389 raw_ostream &getVerboseOutputStream() {
390 return *VerboseOutputStream;
391 }
392
393 /// @}
394 /// @name Target Info
395 /// @{
396
397 bool hasTarget() const { return Target != nullptr; }
398
399 TargetInfo &getTarget() const {
400 assert(Target && "Compiler instance has no target!");
401 return *Target;
402 }
403
404 IntrusiveRefCntPtr<TargetInfo> getTargetPtr() const {
405 assert(Target && "Compiler instance has no target!");
406 return Target;
407 }
408
409 /// Replace the current Target.
410 void setTarget(TargetInfo *Value);
411
412 /// @}
413 /// @name AuxTarget Info
414 /// @{
415
416 TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
417
418 /// Replace the current AuxTarget.
419 void setAuxTarget(TargetInfo *Value);
420
421 // Create Target and AuxTarget based on current options
422 bool createTarget();
423
424 /// @}
425 /// @name Virtual File System
426 /// @{
427
428 bool hasVirtualFileSystem() const { return VFS != nullptr; }
429
430 /// Create a virtual file system instance based on the invocation.
431 ///
432 /// @param BaseFS The file system that may be used when configuring the final
433 /// file system, and act as the underlying file system. Must not
434 /// be NULL.
435 /// @param DC If non-NULL, the diagnostic consumer to be used in case
436 /// configuring the file system emits diagnostics. Note that the
437 /// DiagnosticsEngine using the consumer won't obey the
438 /// --warning-suppression-mappings= flag.
439 void createVirtualFileSystem(IntrusiveRefCntPtr<llvm::vfs::FileSystem>
440 BaseFS = llvm::vfs::getRealFileSystem(),
441 DiagnosticConsumer *DC = nullptr);
442
443 /// Use the given file system.
444 void setVirtualFileSystem(IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) {
445 VFS = std::move(FS);
446 }
447
448 llvm::vfs::FileSystem &getVirtualFileSystem() const { return *VFS; }
449
450 IntrusiveRefCntPtr<llvm::vfs::FileSystem> getVirtualFileSystemPtr() const {
451 return VFS;
452 }
453
454 /// @}
455 /// @name File Manager
456 /// @{
457
458 bool hasFileManager() const { return FileMgr != nullptr; }
459
460 /// Return the current file manager to the caller.
461 FileManager &getFileManager() const {
462 assert(FileMgr && "Compiler instance has no file manager!");
463 return *FileMgr;
464 }
465
466 IntrusiveRefCntPtr<FileManager> getFileManagerPtr() const {
467 assert(FileMgr && "Compiler instance has no file manager!");
468 return FileMgr;
469 }
470
471 void resetAndLeakFileManager() {
472 llvm::BuryPointer(Ptr: FileMgr.get());
473 FileMgr.resetWithoutRelease();
474 }
475
476 /// Replace the current file manager.
477 void setFileManager(IntrusiveRefCntPtr<FileManager> Value);
478
479 /// @}
480 /// @name Output Manager
481 /// @{
482
483 /// Set the output manager.
484 void
485 setOutputManager(IntrusiveRefCntPtr<llvm::vfs::OutputBackend> NewOutputs);
486
487 /// Create an output manager.
488 void createOutputManager();
489
490 bool hasOutputManager() const { return bool(OutputMgr); }
491
492 llvm::vfs::OutputBackend &getOutputManager();
493 llvm::vfs::OutputBackend &getOrCreateOutputManager();
494
495 /// @}
496 /// @name Source Manager
497 /// @{
498
499 bool hasSourceManager() const { return SourceMgr != nullptr; }
500
501 /// Return the current source manager.
502 SourceManager &getSourceManager() const {
503 assert(SourceMgr && "Compiler instance has no source manager!");
504 return *SourceMgr;
505 }
506
507 IntrusiveRefCntPtr<SourceManager> getSourceManagerPtr() const {
508 assert(SourceMgr && "Compiler instance has no source manager!");
509 return SourceMgr;
510 }
511
512 void resetAndLeakSourceManager() {
513 llvm::BuryPointer(Ptr: SourceMgr.get());
514 SourceMgr.resetWithoutRelease();
515 }
516
517 /// setSourceManager - Replace the current source manager.
518 void setSourceManager(llvm::IntrusiveRefCntPtr<SourceManager> Value);
519
520 /// @}
521 /// @name Preprocessor
522 /// @{
523
524 bool hasPreprocessor() const { return PP != nullptr; }
525
526 /// Return the current preprocessor.
527 Preprocessor &getPreprocessor() const {
528 assert(PP && "Compiler instance has no preprocessor!");
529 return *PP;
530 }
531
532 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; }
533
534 void resetAndLeakPreprocessor() {
535 llvm::BuryPointer(Ptr: new std::shared_ptr<Preprocessor>(PP));
536 }
537
538 /// Replace the current preprocessor.
539 void setPreprocessor(std::shared_ptr<Preprocessor> Value);
540
541 /// @}
542 /// @name ASTContext
543 /// @{
544
545 bool hasASTContext() const { return Context != nullptr; }
546
547 ASTContext &getASTContext() const {
548 assert(Context && "Compiler instance has no AST context!");
549 return *Context;
550 }
551
552 IntrusiveRefCntPtr<ASTContext> getASTContextPtr() const {
553 assert(Context && "Compiler instance has no AST context!");
554 return Context;
555 }
556
557 void resetAndLeakASTContext() {
558 llvm::BuryPointer(Ptr: Context.get());
559 Context.resetWithoutRelease();
560 }
561
562 /// setASTContext - Replace the current AST context.
563 void setASTContext(llvm::IntrusiveRefCntPtr<ASTContext> Value);
564
565 /// Replace the current Sema; the compiler instance takes ownership
566 /// of S.
567 void setSema(Sema *S);
568
569 /// @}
570 /// @name ASTConsumer
571 /// @{
572
573 bool hasASTConsumer() const { return (bool)Consumer; }
574
575 ASTConsumer &getASTConsumer() const {
576 assert(Consumer && "Compiler instance has no AST consumer!");
577 return *Consumer;
578 }
579
580 /// takeASTConsumer - Remove the current AST consumer and give ownership to
581 /// the caller.
582 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
583
584 /// setASTConsumer - Replace the current AST consumer; the compiler instance
585 /// takes ownership of \p Value.
586 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
587
588 /// @}
589 /// @name Semantic analysis
590 /// @{
591 bool hasSema() const { return (bool)TheSema; }
592
593 Sema &getSema() const {
594 assert(TheSema && "Compiler instance has no Sema object!");
595 return *TheSema;
596 }
597
598 std::unique_ptr<Sema> takeSema();
599 void resetAndLeakSema();
600
601 /// @}
602 /// @name Module Management
603 /// @{
604
605 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
606 void setASTReader(IntrusiveRefCntPtr<ASTReader> Reader);
607
608 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
609 void setModuleDepCollector(
610 std::shared_ptr<ModuleDependencyCollector> Collector);
611
612 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
613 return ThePCHContainerOperations;
614 }
615
616 /// Return the appropriate PCHContainerWriter depending on the
617 /// current CodeGenOptions.
618 const PCHContainerWriter &getPCHContainerWriter() const {
619 assert(Invocation && "cannot determine module format without invocation");
620 StringRef Format = getHeaderSearchOpts().ModuleFormat;
621 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
622 if (!Writer) {
623 if (Diagnostics)
624 Diagnostics->Report(DiagID: diag::err_module_format_unhandled) << Format;
625 llvm::report_fatal_error(reason: "unknown module format");
626 }
627 return *Writer;
628 }
629
630 /// Return the appropriate PCHContainerReader depending on the
631 /// current CodeGenOptions.
632 const PCHContainerReader &getPCHContainerReader() const {
633 assert(Invocation && "cannot determine module format without invocation");
634 StringRef Format = getHeaderSearchOpts().ModuleFormat;
635 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
636 if (!Reader) {
637 if (Diagnostics)
638 Diagnostics->Report(DiagID: diag::err_module_format_unhandled) << Format;
639 llvm::report_fatal_error(reason: "unknown module format");
640 }
641 return *Reader;
642 }
643
644 /// @}
645 /// @name Code Completion
646 /// @{
647
648 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
649
650 CodeCompleteConsumer &getCodeCompletionConsumer() const {
651 assert(CompletionConsumer &&
652 "Compiler instance has no code completion consumer!");
653 return *CompletionConsumer;
654 }
655
656 /// setCodeCompletionConsumer - Replace the current code completion consumer;
657 /// the compiler instance takes ownership of \p Value.
658 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
659
660 /// }
661 /// @name Back-end Pass Plugins
662 /// @{
663
664 llvm::ArrayRef<std::unique_ptr<llvm::PassPlugin>> getPassPlugins() const {
665 return PassPlugins;
666 }
667
668 /// @}
669 /// @name Frontend timer
670 /// @{
671
672 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; }
673
674 llvm::Timer &getFrontendTimer() const {
675 assert(FrontendTimer && "Compiler instance has no frontend timer!");
676 return *FrontendTimer;
677 }
678
679 /// }
680 /// @name Output Files
681 /// @{
682
683 /// clearOutputFiles - Clear the output file list. The underlying output
684 /// streams must have been closed beforehand.
685 ///
686 /// \param EraseFiles - If true, attempt to erase the files from disk.
687 void clearOutputFiles(bool EraseFiles);
688
689 /// @}
690 /// @name Construction Utility Methods
691 /// @{
692
693 /// Create the diagnostics engine using the invocation's diagnostic options
694 /// and replace any existing one with it.
695 ///
696 /// Note that this routine also replaces the diagnostic client,
697 /// allocating one if one is not provided.
698 ///
699 /// \param Client If non-NULL, a diagnostic client that will be
700 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
701 /// unit.
702 ///
703 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
704 /// the diagnostic object should take ownership of the client.
705 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
706 bool ShouldOwnClient = true);
707
708 /// Create a DiagnosticsEngine object.
709 ///
710 /// If no diagnostic client is provided, this creates a
711 /// DiagnosticConsumer that is owned by the returned diagnostic
712 /// object, if using directly the caller is responsible for
713 /// releasing the returned DiagnosticsEngine's client eventually.
714 ///
715 /// \param VFS The file system used to load the suppression mappings file.
716 ///
717 /// \param Opts - The diagnostic options; note that the created text
718 /// diagnostic object contains a reference to these options.
719 ///
720 /// \param Client If non-NULL, a diagnostic client that will be
721 /// attached to (and, then, owned by) the returned DiagnosticsEngine
722 /// object. If NULL, the returned DiagnosticsEngine will own a newly-created
723 /// client.
724 ///
725 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
726 /// used by some diagnostics printers (for logging purposes only).
727 ///
728 /// \return The new object on success, or null on failure.
729 static IntrusiveRefCntPtr<DiagnosticsEngine>
730 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
731 DiagnosticConsumer *Client = nullptr,
732 bool ShouldOwnClient = true,
733 const CodeGenOptions *CodeGenOpts = nullptr);
734
735 /// Create the file manager and replace any existing one with it.
736 void createFileManager();
737
738 /// Create the source manager and replace any existing one with it.
739 void createSourceManager();
740
741 /// Create the preprocessor, using the invocation, file, and source managers,
742 /// and replace any existing one with it.
743 void createPreprocessor(TranslationUnitKind TUKind);
744
745 void setDependencyDirectivesGetter(
746 std::unique_ptr<DependencyDirectivesGetter> Getter) {
747 GetDependencyDirectives = std::move(Getter);
748 }
749
750 /// Create the AST context.
751 void createASTContext();
752
753 /// Create an external AST source to read a PCH file and attach it to the AST
754 /// context.
755 void createPCHExternalASTSource(
756 StringRef Path, DisableValidationForModuleKind DisableValidation,
757 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
758 bool OwnDeserializationListener);
759
760 /// Create an external AST source to read a PCH file.
761 ///
762 /// \return - The new object on success, or null on failure.
763 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
764 StringRef Path, StringRef Sysroot,
765 DisableValidationForModuleKind DisableValidation,
766 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
767 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
768 const CodeGenOptions &CodeGenOpts,
769 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
770 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
771 void *DeserializationListener, bool OwnDeserializationListener,
772 bool Preamble, bool UseGlobalModuleIndex);
773
774 /// Create a code completion consumer using the invocation; note that this
775 /// will cause the source manager to truncate the input source file at the
776 /// completion point.
777 void createCodeCompletionConsumer();
778
779 /// Create a code completion consumer to print code completion results, at
780 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
781 static CodeCompleteConsumer *createCodeCompletionConsumer(
782 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
783 const CodeCompleteOptions &Opts, raw_ostream &OS);
784
785 /// Create the Sema object to be used for parsing.
786 void createSema(TranslationUnitKind TUKind,
787 CodeCompleteConsumer *CompletionConsumer);
788
789 /// Create the frontend timer and replace any existing one with it.
790 void createFrontendTimer();
791
792 /// Create the default output file (from the invocation's options) and add it
793 /// to the list of tracked output files.
794 ///
795 /// The files created by this are usually removed on signal, and, depending
796 /// on FrontendOptions, may also use a temporary file (that is, the data is
797 /// written to a temporary file which will atomically replace the target
798 /// output on success).
799 ///
800 /// \return - Null on error.
801 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile(
802 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "",
803 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false,
804 bool ForceUseTemporary = false);
805
806 /// Create a new output file, optionally deriving the output path name, and
807 /// add it to the list of tracked output files.
808 ///
809 /// \return - Null on error.
810 std::unique_ptr<raw_pwrite_stream>
811 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal,
812 bool UseTemporary, bool CreateMissingDirectories = false);
813
814private:
815 /// Create a new output file and add it to the list of tracked output files.
816 ///
817 /// If \p OutputPath is empty, then createOutputFile will derive an output
818 /// path location as \p BaseInput, with any suffix removed, and \p Extension
819 /// appended. If \p OutputPath is not stdout and \p UseTemporary
820 /// is true, createOutputFile will create a new temporary file that must be
821 /// renamed to \p OutputPath in the end.
822 ///
823 /// \param OutputPath - If given, the path to the output file.
824 /// \param Binary - The mode to open the file in.
825 /// \param RemoveFileOnSignal - Whether the file should be registered with
826 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
827 /// multithreaded use, as the underlying signal mechanism is not reentrant
828 /// \param UseTemporary - Create a new temporary file that must be renamed to
829 /// OutputPath in the end.
830 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
831 /// missing directories in the output path.
832 Expected<std::unique_ptr<raw_pwrite_stream>>
833 createOutputFileImpl(StringRef OutputPath, bool Binary,
834 bool RemoveFileOnSignal, bool UseTemporary,
835 bool CreateMissingDirectories);
836
837public:
838 std::unique_ptr<raw_pwrite_stream> createNullOutputFile();
839
840 /// @}
841 /// @name Initialization Utility Methods
842 /// @{
843
844 /// InitializeSourceManager - Initialize the source manager to set InputFile
845 /// as the main file.
846 ///
847 /// \return True on success.
848 bool InitializeSourceManager(const FrontendInputFile &Input);
849
850 /// InitializeSourceManager - Initialize the source manager to set InputFile
851 /// as the main file.
852 ///
853 /// \return True on success.
854 static bool InitializeSourceManager(const FrontendInputFile &Input,
855 DiagnosticsEngine &Diags,
856 FileManager &FileMgr,
857 SourceManager &SourceMgr);
858
859 /// @}
860
861 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) {
862 OutputStream = std::move(OutStream);
863 }
864
865 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() {
866 return std::move(OutputStream);
867 }
868
869 void createASTReader();
870
871 bool loadModuleFile(ModuleFileName FileName,
872 serialization::ModuleFile *&LoadedModuleFile);
873
874 /// Configuration object for making the result of \c cloneForModuleCompile()
875 /// thread-safe.
876 class ThreadSafeCloneConfig {
877 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS;
878 DiagnosticConsumer &DiagConsumer;
879 std::shared_ptr<ModuleCache> ModCache;
880 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
881
882 public:
883 ThreadSafeCloneConfig(
884 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
885 DiagnosticConsumer &DiagConsumer, std::shared_ptr<ModuleCache> ModCache,
886 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector = nullptr)
887 : VFS(std::move(VFS)), DiagConsumer(DiagConsumer),
888 ModCache(std::move(ModCache)),
889 ModuleDepCollector(std::move(ModuleDepCollector)) {
890 assert(this->VFS && "Clone config requires non-null VFS");
891 assert(this->ModCache && "Clone config requires non-null ModuleCache");
892 }
893
894 IntrusiveRefCntPtr<llvm::vfs::FileSystem> getVFS() const { return VFS; }
895 DiagnosticConsumer &getDiagConsumer() const { return DiagConsumer; }
896 std::shared_ptr<ModuleCache> getModuleCache() const { return ModCache; }
897 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const {
898 return ModuleDepCollector;
899 }
900 };
901
902private:
903 /// Find a module, potentially compiling it, before reading its AST. This is
904 /// the guts of loadModule.
905 ///
906 /// For prebuilt modules, the Module is not expected to exist in
907 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the
908 /// ModuleManager, then it will be loaded and looked up.
909 ///
910 /// For implicit modules, the Module is expected to already be in the
911 /// ModuleMap. First attempt to load it from the given path on disk. If that
912 /// fails, defer to compileModuleAndReadAST, which will first build and then
913 /// load it.
914 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
915 SourceLocation ImportLoc,
916 SourceRange ModuleNameRange,
917 bool IsInclusionDirective);
918
919 /// Creates a \c CompilerInstance for compiling a module.
920 ///
921 /// This expects a properly initialized \c FrontendInputFile.
922 std::unique_ptr<CompilerInstance> cloneForModuleCompileImpl(
923 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
924 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
925 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
926
927public:
928 /// Creates a new \c CompilerInstance for compiling a module.
929 ///
930 /// This takes care of creating appropriate \c FrontendInputFile for
931 /// public/private frameworks, inferred modules and such.
932 ///
933 /// The \c ThreadSafeConfig takes precedence over the \c DiagnosticConsumer
934 /// and \c FileSystem of this instance (and disables \c FileManager sharing).
935 std::unique_ptr<CompilerInstance> cloneForModuleCompile(
936 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
937 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig = std::nullopt);
938
939 /// Compile a module file for the given module, using the options
940 /// provided by the importing compiler instance. Returns the PCM file in
941 /// a buffer.
942 // FIXME: This should be private, but it's called from static non-member
943 // functions in the implementation file.
944 std::unique_ptr<llvm::MemoryBuffer> compileModule(SourceLocation ImportLoc,
945 StringRef ModuleName,
946 StringRef ModuleFileName,
947 CompilerInstance &Instance);
948
949 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
950 Module::NameVisibilityKind Visibility,
951 bool IsInclusionDirective) override;
952
953 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName,
954 StringRef Source) override;
955
956 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
957 SourceLocation ImportLoc) override;
958
959 bool hadModuleLoaderFatalFailure() const {
960 return ModuleLoader::HadFatalFailure;
961 }
962
963 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
964
965 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
966
967 void setGenModuleActionWrapper(GenModuleActionWrapperFunc Wrapper) {
968 GenModuleActionWrapper = Wrapper;
969 }
970
971 GenModuleActionWrapperFunc getGenModuleActionWrapper() const {
972 return GenModuleActionWrapper;
973 }
974
975 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
976 DependencyCollectors.push_back(x: std::move(Listener));
977 }
978
979 void clearDependencyCollectors() { DependencyCollectors.clear(); }
980
981 std::vector<std::shared_ptr<DependencyCollector>> &getDependencyCollectors() {
982 return DependencyCollectors;
983 }
984
985 void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS);
986
987 ModuleCache &getModuleCache() const { return *ModCache; }
988 std::shared_ptr<ModuleCache> getModuleCachePtr() const { return ModCache; }
989};
990
991} // end namespace clang
992
993#endif
994