Clang Project

clang_source_code/include/clang/Frontend/CompilerInstance.h
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/Frontend/CompilerInvocation.h"
16#include "clang/Frontend/PCHContainerOperations.h"
17#include "clang/Frontend/Utils.h"
18#include "clang/Lex/HeaderSearchOptions.h"
19#include "clang/Lex/ModuleLoader.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntrusiveRefCntPtr.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/BuryPointer.h"
25#include <cassert>
26#include <list>
27#include <memory>
28#include <string>
29#include <utility>
30
31namespace llvm {
32class raw_fd_ostream;
33class Timer;
34class TimerGroup;
35}
36
37namespace clang {
38class ASTContext;
39class ASTReader;
40class CodeCompleteConsumer;
41class DiagnosticsEngine;
42class DiagnosticConsumer;
43class ExternalASTSource;
44class FileEntry;
45class FileManager;
46class FrontendAction;
47class InMemoryModuleCache;
48class Module;
49class Preprocessor;
50class Sema;
51class SourceManager;
52class TargetInfo;
53
54/// CompilerInstance - Helper class for managing a single instance of the Clang
55/// compiler.
56///
57/// The CompilerInstance serves two purposes:
58///  (1) It manages the various objects which are necessary to run the compiler,
59///      for example the preprocessor, the target information, and the AST
60///      context.
61///  (2) It provides utility routines for constructing and manipulating the
62///      common Clang objects.
63///
64/// The compiler instance generally owns the instance of all the objects that it
65/// manages. However, clients can still share objects by manually setting the
66/// object and retaking ownership prior to destroying the CompilerInstance.
67///
68/// The compiler instance is intended to simplify clients, but not to lock them
69/// in to the compiler instance for everything. When possible, utility functions
70/// come in two forms; a short form that reuses the CompilerInstance objects,
71/// and a long form that takes explicit instances of any required objects.
72class CompilerInstance : public ModuleLoader {
73  /// The options used in this compiler instance.
74  std::shared_ptr<CompilerInvocationInvocation;
75
76  /// The diagnostics engine instance.
77  IntrusiveRefCntPtr<DiagnosticsEngineDiagnostics;
78
79  /// The target being compiled for.
80  IntrusiveRefCntPtr<TargetInfoTarget;
81
82  /// Auxiliary Target info.
83  IntrusiveRefCntPtr<TargetInfoAuxTarget;
84
85  /// The file manager.
86  IntrusiveRefCntPtr<FileManagerFileMgr;
87
88  /// The source manager.
89  IntrusiveRefCntPtr<SourceManagerSourceMgr;
90
91  /// The cache of PCM files.
92  IntrusiveRefCntPtr<InMemoryModuleCacheModuleCache;
93
94  /// The preprocessor.
95  std::shared_ptr<PreprocessorPP;
96
97  /// The AST context.
98  IntrusiveRefCntPtr<ASTContextContext;
99
100  /// An optional sema source that will be attached to sema.
101  IntrusiveRefCntPtr<ExternalSemaSourceExternalSemaSrc;
102
103  /// The AST consumer.
104  std::unique_ptr<ASTConsumerConsumer;
105
106  /// The code completion consumer.
107  std::unique_ptr<CodeCompleteConsumerCompletionConsumer;
108
109  /// The semantic analysis object.
110  std::unique_ptr<SemaTheSema;
111
112  /// The frontend timer group.
113  std::unique_ptr<llvm::TimerGroupFrontendTimerGroup;
114
115  /// The frontend timer.
116  std::unique_ptr<llvm::TimerFrontendTimer;
117
118  /// The ASTReader, if one exists.
119  IntrusiveRefCntPtr<ASTReaderModuleManager;
120
121  /// The module dependency collector for crashdumps
122  std::shared_ptr<ModuleDependencyCollectorModuleDepCollector;
123
124  /// The module provider.
125  std::shared_ptr<PCHContainerOperationsThePCHContainerOperations;
126
127  /// The dependency file generator.
128  std::unique_ptr<DependencyFileGeneratorTheDependencyFileGenerator;
129
130  std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
131
132  /// The set of top-level modules that has already been loaded,
133  /// along with the module map
134  llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
135
136  /// The set of top-level modules that has already been built on the
137  /// fly as part of this overall compilation action.
138  std::map<std::stringstd::stringBuiltModules;
139
140  /// Should we delete the BuiltModules when we're done?
141  bool DeleteBuiltModules = true;
142
143  /// The location of the module-import keyword for the last module
144  /// import.
145  SourceLocation LastModuleImportLoc;
146
147  /// The result of the last module import.
148  ///
149  ModuleLoadResult LastModuleImportResult;
150
151  /// Whether we should (re)build the global module index once we
152  /// have finished with this translation unit.
153  bool BuildGlobalModuleIndex = false;
154
155  /// We have a full global module index, with all modules.
156  bool HaveFullGlobalModuleIndex = false;
157
158  /// One or more modules failed to build.
159  bool ModuleBuildFailed = false;
160
161  /// Holds information about the output file.
162  ///
163  /// If TempFilename is not empty we must rename it to Filename at the end.
164  /// TempFilename may be empty and Filename non-empty if creating the temporary
165  /// failed.
166  struct OutputFile {
167    std::string Filename;
168    std::string TempFilename;
169
170    OutputFile(std::string filenamestd::string tempFilename)
171        : Filename(std::move(filename)), TempFilename(std::move(tempFilename)) {
172    }
173  };
174
175  /// If the output doesn't support seeking (terminal, pipe). we switch
176  /// the stream to a buffer_ostream. These are the buffer and the original
177  /// stream.
178  std::unique_ptr<llvm::raw_fd_ostreamNonSeekStream;
179
180  /// The list of active output files.
181  std::list<OutputFileOutputFiles;
182
183  /// Force an output buffer.
184  std::unique_ptr<llvm::raw_pwrite_streamOutputStream;
185
186  CompilerInstance(const CompilerInstance &) = delete;
187  void operator=(const CompilerInstance &) = delete;
188public:
189  explicit CompilerInstance(
190      std::shared_ptr<PCHContainerOperationsPCHContainerOps =
191          std::make_shared<PCHContainerOperations>(),
192      InMemoryModuleCache *SharedModuleCache = nullptr);
193  ~CompilerInstance() override;
194
195  /// @name High-Level Operations
196  /// {
197
198  /// ExecuteAction - Execute the provided action against the compiler's
199  /// CompilerInvocation object.
200  ///
201  /// This function makes the following assumptions:
202  ///
203  ///  - The invocation options should be initialized. This function does not
204  ///    handle the '-help' or '-version' options, clients should handle those
205  ///    directly.
206  ///
207  ///  - The diagnostics engine should have already been created by the client.
208  ///
209  ///  - No other CompilerInstance state should have been initialized (this is
210  ///    an unchecked error).
211  ///
212  ///  - Clients should have initialized any LLVM target features that may be
213  ///    required.
214  ///
215  ///  - Clients should eventually call llvm_shutdown() upon the completion of
216  ///    this routine to ensure that any managed objects are properly destroyed.
217  ///
218  /// Note that this routine may write output to 'stderr'.
219  ///
220  /// \param Act - The action to execute.
221  /// \return - True on success.
222  //
223  // FIXME: This function should take the stream to write any debugging /
224  // verbose output to as an argument.
225  //
226  // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
227  // of the context or else not CompilerInstance specific.
228  bool ExecuteAction(FrontendAction &Act);
229
230  /// }
231  /// @name Compiler Invocation and Options
232  /// {
233
234  bool hasInvocation() const { return Invocation != nullptr; }
235
236  CompilerInvocation &getInvocation() {
237     (0) . __assert_fail ("Invocation && \"Compiler instance has no invocation!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 237, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Invocation && "Compiler instance has no invocation!");
238    return *Invocation;
239  }
240
241  /// setInvocation - Replace the current invocation.
242  void setInvocation(std::shared_ptr<CompilerInvocationValue);
243
244  /// Indicates whether we should (re)build the global module index.
245  bool shouldBuildGlobalModuleIndex() const;
246
247  /// Set the flag indicating whether we should (re)build the global
248  /// module index.
249  void setBuildGlobalModuleIndex(bool Build) {
250    BuildGlobalModuleIndex = Build;
251  }
252
253  /// }
254  /// @name Forwarding Methods
255  /// {
256
257  AnalyzerOptionsRef getAnalyzerOpts() {
258    return Invocation->getAnalyzerOpts();
259  }
260
261  CodeGenOptions &getCodeGenOpts() {
262    return Invocation->getCodeGenOpts();
263  }
264  const CodeGenOptions &getCodeGenOpts() const {
265    return Invocation->getCodeGenOpts();
266  }
267
268  DependencyOutputOptions &getDependencyOutputOpts() {
269    return Invocation->getDependencyOutputOpts();
270  }
271  const DependencyOutputOptions &getDependencyOutputOpts() const {
272    return Invocation->getDependencyOutputOpts();
273  }
274
275  DiagnosticOptions &getDiagnosticOpts() {
276    return Invocation->getDiagnosticOpts();
277  }
278  const DiagnosticOptions &getDiagnosticOpts() const {
279    return Invocation->getDiagnosticOpts();
280  }
281
282  FileSystemOptions &getFileSystemOpts() {
283    return Invocation->getFileSystemOpts();
284  }
285  const FileSystemOptions &getFileSystemOpts() const {
286    return Invocation->getFileSystemOpts();
287  }
288
289  FrontendOptions &getFrontendOpts() {
290    return Invocation->getFrontendOpts();
291  }
292  const FrontendOptions &getFrontendOpts() const {
293    return Invocation->getFrontendOpts();
294  }
295
296  HeaderSearchOptions &getHeaderSearchOpts() {
297    return Invocation->getHeaderSearchOpts();
298  }
299  const HeaderSearchOptions &getHeaderSearchOpts() const {
300    return Invocation->getHeaderSearchOpts();
301  }
302  std::shared_ptr<HeaderSearchOptionsgetHeaderSearchOptsPtr() const {
303    return Invocation->getHeaderSearchOptsPtr();
304  }
305
306  LangOptions &getLangOpts() {
307    return *Invocation->getLangOpts();
308  }
309  const LangOptions &getLangOpts() const {
310    return *Invocation->getLangOpts();
311  }
312
313  PreprocessorOptions &getPreprocessorOpts() {
314    return Invocation->getPreprocessorOpts();
315  }
316  const PreprocessorOptions &getPreprocessorOpts() const {
317    return Invocation->getPreprocessorOpts();
318  }
319
320  PreprocessorOutputOptions &getPreprocessorOutputOpts() {
321    return Invocation->getPreprocessorOutputOpts();
322  }
323  const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
324    return Invocation->getPreprocessorOutputOpts();
325  }
326
327  TargetOptions &getTargetOpts() {
328    return Invocation->getTargetOpts();
329  }
330  const TargetOptions &getTargetOpts() const {
331    return Invocation->getTargetOpts();
332  }
333
334  /// }
335  /// @name Diagnostics Engine
336  /// {
337
338  bool hasDiagnostics() const { return Diagnostics != nullptr; }
339
340  /// Get the current diagnostics engine.
341  DiagnosticsEngine &getDiagnostics() const {
342     (0) . __assert_fail ("Diagnostics && \"Compiler instance has no diagnostics!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 342, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Diagnostics && "Compiler instance has no diagnostics!");
343    return *Diagnostics;
344  }
345
346  /// setDiagnostics - Replace the current diagnostics engine.
347  void setDiagnostics(DiagnosticsEngine *Value);
348
349  DiagnosticConsumer &getDiagnosticClient() const {
350     (0) . __assert_fail ("Diagnostics && Diagnostics->getClient() && \"Compiler instance has no diagnostic client!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 351, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Diagnostics && Diagnostics->getClient() &&
351 (0) . __assert_fail ("Diagnostics && Diagnostics->getClient() && \"Compiler instance has no diagnostic client!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 351, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">           "Compiler instance has no diagnostic client!");
352    return *Diagnostics->getClient();
353  }
354
355  /// }
356  /// @name Target Info
357  /// {
358
359  bool hasTarget() const { return Target != nullptr; }
360
361  TargetInfo &getTarget() const {
362     (0) . __assert_fail ("Target && \"Compiler instance has no target!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 362, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Target && "Compiler instance has no target!");
363    return *Target;
364  }
365
366  /// Replace the current Target.
367  void setTarget(TargetInfo *Value);
368
369  /// }
370  /// @name AuxTarget Info
371  /// {
372
373  TargetInfo *getAuxTarget() const { return AuxTarget.get(); }
374
375  /// Replace the current AuxTarget.
376  void setAuxTarget(TargetInfo *Value);
377
378  /// }
379  /// @name Virtual File System
380  /// {
381
382  llvm::vfs::FileSystem &getVirtualFileSystem() const {
383    return getFileManager().getVirtualFileSystem();
384  }
385
386  /// }
387  /// @name File Manager
388  /// {
389
390  bool hasFileManager() const { return FileMgr != nullptr; }
391
392  /// Return the current file manager to the caller.
393  FileManager &getFileManager() const {
394     (0) . __assert_fail ("FileMgr && \"Compiler instance has no file manager!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 394, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(FileMgr && "Compiler instance has no file manager!");
395    return *FileMgr;
396  }
397
398  void resetAndLeakFileManager() {
399    llvm::BuryPointer(FileMgr.get());
400    FileMgr.resetWithoutRelease();
401  }
402
403  /// Replace the current file manager and virtual file system.
404  void setFileManager(FileManager *Value);
405
406  /// }
407  /// @name Source Manager
408  /// {
409
410  bool hasSourceManager() const { return SourceMgr != nullptr; }
411
412  /// Return the current source manager.
413  SourceManager &getSourceManager() const {
414     (0) . __assert_fail ("SourceMgr && \"Compiler instance has no source manager!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 414, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(SourceMgr && "Compiler instance has no source manager!");
415    return *SourceMgr;
416  }
417
418  void resetAndLeakSourceManager() {
419    llvm::BuryPointer(SourceMgr.get());
420    SourceMgr.resetWithoutRelease();
421  }
422
423  /// setSourceManager - Replace the current source manager.
424  void setSourceManager(SourceManager *Value);
425
426  /// }
427  /// @name Preprocessor
428  /// {
429
430  bool hasPreprocessor() const { return PP != nullptr; }
431
432  /// Return the current preprocessor.
433  Preprocessor &getPreprocessor() const {
434     (0) . __assert_fail ("PP && \"Compiler instance has no preprocessor!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 434, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(PP && "Compiler instance has no preprocessor!");
435    return *PP;
436  }
437
438  std::shared_ptr<PreprocessorgetPreprocessorPtr() { return PP; }
439
440  void resetAndLeakPreprocessor() {
441    llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP));
442  }
443
444  /// Replace the current preprocessor.
445  void setPreprocessor(std::shared_ptr<PreprocessorValue);
446
447  /// }
448  /// @name ASTContext
449  /// {
450
451  bool hasASTContext() const { return Context != nullptr; }
452
453  ASTContext &getASTContext() const {
454     (0) . __assert_fail ("Context && \"Compiler instance has no AST context!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 454, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Context && "Compiler instance has no AST context!");
455    return *Context;
456  }
457
458  void resetAndLeakASTContext() {
459    llvm::BuryPointer(Context.get());
460    Context.resetWithoutRelease();
461  }
462
463  /// setASTContext - Replace the current AST context.
464  void setASTContext(ASTContext *Value);
465
466  /// Replace the current Sema; the compiler instance takes ownership
467  /// of S.
468  void setSema(Sema *S);
469
470  /// }
471  /// @name ASTConsumer
472  /// {
473
474  bool hasASTConsumer() const { return (bool)Consumer; }
475
476  ASTConsumer &getASTConsumer() const {
477     (0) . __assert_fail ("Consumer && \"Compiler instance has no AST consumer!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 477, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Consumer && "Compiler instance has no AST consumer!");
478    return *Consumer;
479  }
480
481  /// takeASTConsumer - Remove the current AST consumer and give ownership to
482  /// the caller.
483  std::unique_ptr<ASTConsumertakeASTConsumer() { return std::move(Consumer); }
484
485  /// setASTConsumer - Replace the current AST consumer; the compiler instance
486  /// takes ownership of \p Value.
487  void setASTConsumer(std::unique_ptr<ASTConsumerValue);
488
489  /// }
490  /// @name Semantic analysis
491  /// {
492  bool hasSema() const { return (bool)TheSema; }
493
494  Sema &getSema() const {
495     (0) . __assert_fail ("TheSema && \"Compiler instance has no Sema object!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 495, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(TheSema && "Compiler instance has no Sema object!");
496    return *TheSema;
497  }
498
499  std::unique_ptr<SematakeSema();
500  void resetAndLeakSema();
501
502  /// }
503  /// @name Module Management
504  /// {
505
506  IntrusiveRefCntPtr<ASTReadergetModuleManager() const;
507  void setModuleManager(IntrusiveRefCntPtr<ASTReaderReader);
508
509  std::shared_ptr<ModuleDependencyCollectorgetModuleDepCollector() const;
510  void setModuleDepCollector(
511      std::shared_ptr<ModuleDependencyCollectorCollector);
512
513  std::shared_ptr<PCHContainerOperationsgetPCHContainerOperations() const {
514    return ThePCHContainerOperations;
515  }
516
517  /// Return the appropriate PCHContainerWriter depending on the
518  /// current CodeGenOptions.
519  const PCHContainerWriter &getPCHContainerWriter() const {
520     (0) . __assert_fail ("Invocation && \"cannot determine module format without invocation\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 520, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Invocation && "cannot determine module format without invocation");
521    StringRef Format = getHeaderSearchOpts().ModuleFormat;
522    auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format);
523    if (!Writer) {
524      if (Diagnostics)
525        Diagnostics->Report(diag::err_module_format_unhandled) << Format;
526      llvm::report_fatal_error("unknown module format");
527    }
528    return *Writer;
529  }
530
531  /// Return the appropriate PCHContainerReader depending on the
532  /// current CodeGenOptions.
533  const PCHContainerReader &getPCHContainerReader() const {
534     (0) . __assert_fail ("Invocation && \"cannot determine module format without invocation\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 534, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Invocation && "cannot determine module format without invocation");
535    StringRef Format = getHeaderSearchOpts().ModuleFormat;
536    auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format);
537    if (!Reader) {
538      if (Diagnostics)
539        Diagnostics->Report(diag::err_module_format_unhandled) << Format;
540      llvm::report_fatal_error("unknown module format");
541    }
542    return *Reader;
543  }
544
545  /// }
546  /// @name Code Completion
547  /// {
548
549  bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
550
551  CodeCompleteConsumer &getCodeCompletionConsumer() const {
552     (0) . __assert_fail ("CompletionConsumer && \"Compiler instance has no code completion consumer!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 553, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(CompletionConsumer &&
553 (0) . __assert_fail ("CompletionConsumer && \"Compiler instance has no code completion consumer!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 553, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">           "Compiler instance has no code completion consumer!");
554    return *CompletionConsumer;
555  }
556
557  /// setCodeCompletionConsumer - Replace the current code completion consumer;
558  /// the compiler instance takes ownership of \p Value.
559  void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
560
561  /// }
562  /// @name Frontend timer
563  /// {
564
565  bool hasFrontendTimer() const { return (bool)FrontendTimer; }
566
567  llvm::Timer &getFrontendTimer() const {
568     (0) . __assert_fail ("FrontendTimer && \"Compiler instance has no frontend timer!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Frontend/CompilerInstance.h", 568, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(FrontendTimer && "Compiler instance has no frontend timer!");
569    return *FrontendTimer;
570  }
571
572  /// }
573  /// @name Output Files
574  /// {
575
576  /// addOutputFile - Add an output file onto the list of tracked output files.
577  ///
578  /// \param OutFile - The output file info.
579  void addOutputFile(OutputFile &&OutFile);
580
581  /// clearOutputFiles - Clear the output file list. The underlying output
582  /// streams must have been closed beforehand.
583  ///
584  /// \param EraseFiles - If true, attempt to erase the files from disk.
585  void clearOutputFiles(bool EraseFiles);
586
587  /// }
588  /// @name Construction Utility Methods
589  /// {
590
591  /// Create the diagnostics engine using the invocation's diagnostic options
592  /// and replace any existing one with it.
593  ///
594  /// Note that this routine also replaces the diagnostic client,
595  /// allocating one if one is not provided.
596  ///
597  /// \param Client If non-NULL, a diagnostic client that will be
598  /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
599  /// unit.
600  ///
601  /// \param ShouldOwnClient If Client is non-NULL, specifies whether
602  /// the diagnostic object should take ownership of the client.
603  void createDiagnostics(DiagnosticConsumer *Client = nullptr,
604                         bool ShouldOwnClient = true);
605
606  /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
607  ///
608  /// If no diagnostic client is provided, this creates a
609  /// DiagnosticConsumer that is owned by the returned diagnostic
610  /// object, if using directly the caller is responsible for
611  /// releasing the returned DiagnosticsEngine's client eventually.
612  ///
613  /// \param Opts - The diagnostic options; note that the created text
614  /// diagnostic object contains a reference to these options.
615  ///
616  /// \param Client If non-NULL, a diagnostic client that will be
617  /// attached to (and, then, owned by) the returned DiagnosticsEngine
618  /// object.
619  ///
620  /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
621  /// used by some diagnostics printers (for logging purposes only).
622  ///
623  /// \return The new object on success, or null on failure.
624  static IntrusiveRefCntPtr<DiagnosticsEngine>
625  createDiagnostics(DiagnosticOptions *Opts,
626                    DiagnosticConsumer *Client = nullptr,
627                    bool ShouldOwnClient = true,
628                    const CodeGenOptions *CodeGenOpts = nullptr);
629
630  /// Create the file manager and replace any existing one with it.
631  ///
632  /// \return The new file manager on success, or null on failure.
633  FileManager *
634  createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystemVFS = nullptr);
635
636  /// Create the source manager and replace any existing one with it.
637  void createSourceManager(FileManager &FileMgr);
638
639  /// Create the preprocessor, using the invocation, file, and source managers,
640  /// and replace any existing one with it.
641  void createPreprocessor(TranslationUnitKind TUKind);
642
643  std::string getSpecificModuleCachePath();
644
645  /// Create the AST context.
646  void createASTContext();
647
648  /// Create an external AST source to read a PCH file and attach it to the AST
649  /// context.
650  void createPCHExternalASTSource(StringRef Pathbool DisablePCHValidation,
651                                  bool AllowPCHWithCompilerErrors,
652                                  void *DeserializationListener,
653                                  bool OwnDeserializationListener);
654
655  /// Create an external AST source to read a PCH file.
656  ///
657  /// \return - The new object on success, or null on failure.
658  static IntrusiveRefCntPtr<ASTReadercreatePCHExternalASTSource(
659      StringRef PathStringRef Sysrootbool DisablePCHValidation,
660      bool AllowPCHWithCompilerErrorsPreprocessor &PP,
661      InMemoryModuleCache &ModuleCacheASTContext &Context,
662      const PCHContainerReader &PCHContainerRdr,
663      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
664      DependencyFileGenerator *DependencyFile,
665      ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
666      void *DeserializationListenerbool OwnDeserializationListener,
667      bool Preamblebool UseGlobalModuleIndex);
668
669  /// Create a code completion consumer using the invocation; note that this
670  /// will cause the source manager to truncate the input source file at the
671  /// completion point.
672  void createCodeCompletionConsumer();
673
674  /// Create a code completion consumer to print code completion results, at
675  /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
676  static CodeCompleteConsumer *createCodeCompletionConsumer(
677      Preprocessor &PPStringRef Filenameunsigned Lineunsigned Column,
678      const CodeCompleteOptions &Optsraw_ostream &OS);
679
680  /// Create the Sema object to be used for parsing.
681  void createSema(TranslationUnitKind TUKind,
682                  CodeCompleteConsumer *CompletionConsumer);
683
684  /// Create the frontend timer and replace any existing one with it.
685  void createFrontendTimer();
686
687  /// Create the default output file (from the invocation's options) and add it
688  /// to the list of tracked output files.
689  ///
690  /// The files created by this function always use temporary files to write to
691  /// their result (that is, the data is written to a temporary file which will
692  /// atomically replace the target output on success).
693  ///
694  /// \return - Null on error.
695  std::unique_ptr<raw_pwrite_stream>
696  createDefaultOutputFile(bool Binary = trueStringRef BaseInput = "",
697                          StringRef Extension = "");
698
699  /// Create a new output file and add it to the list of tracked output files,
700  /// optionally deriving the output path name.
701  ///
702  /// \return - Null on error.
703  std::unique_ptr<raw_pwrite_stream>
704  createOutputFile(StringRef OutputPathbool Binarybool RemoveFileOnSignal,
705                   StringRef BaseInputStringRef Extensionbool UseTemporary,
706                   bool CreateMissingDirectories = false);
707
708  /// Create a new output file, optionally deriving the output path name.
709  ///
710  /// If \p OutputPath is empty, then createOutputFile will derive an output
711  /// path location as \p BaseInput, with any suffix removed, and \p Extension
712  /// appended. If \p OutputPath is not stdout and \p UseTemporary
713  /// is true, createOutputFile will create a new temporary file that must be
714  /// renamed to \p OutputPath in the end.
715  ///
716  /// \param OutputPath - If given, the path to the output file.
717  /// \param Error [out] - On failure, the error.
718  /// \param BaseInput - If \p OutputPath is empty, the input path name to use
719  /// for deriving the output path.
720  /// \param Extension - The extension to use for derived output names.
721  /// \param Binary - The mode to open the file in.
722  /// \param RemoveFileOnSignal - Whether the file should be registered with
723  /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
724  /// multithreaded use, as the underlying signal mechanism is not reentrant
725  /// \param UseTemporary - Create a new temporary file that must be renamed to
726  /// OutputPath in the end.
727  /// \param CreateMissingDirectories - When \p UseTemporary is true, create
728  /// missing directories in the output path.
729  /// \param ResultPathName [out] - If given, the result path name will be
730  /// stored here on success.
731  /// \param TempPathName [out] - If given, the temporary file path name
732  /// will be stored here on success.
733  std::unique_ptr<raw_pwrite_stream>
734  createOutputFile(StringRef OutputPathstd::error_code &Errorbool Binary,
735                   bool RemoveFileOnSignalStringRef BaseInput,
736                   StringRef Extensionbool UseTemporary,
737                   bool CreateMissingDirectoriesstd::string *ResultPathName,
738                   std::string *TempPathName);
739
740  std::unique_ptr<raw_pwrite_streamcreateNullOutputFile();
741
742  /// }
743  /// @name Initialization Utility Methods
744  /// {
745
746  /// InitializeSourceManager - Initialize the source manager to set InputFile
747  /// as the main file.
748  ///
749  /// \return True on success.
750  bool InitializeSourceManager(const FrontendInputFile &Input);
751
752  /// InitializeSourceManager - Initialize the source manager to set InputFile
753  /// as the main file.
754  ///
755  /// \return True on success.
756  static bool InitializeSourceManager(const FrontendInputFile &Input,
757                                      DiagnosticsEngine &Diags,
758                                      FileManager &FileMgr,
759                                      SourceManager &SourceMgr,
760                                      HeaderSearch *HS,
761                                      DependencyOutputOptions &DepOpts,
762                                      const FrontendOptions &Opts);
763
764  /// }
765
766  void setOutputStream(std::unique_ptr<llvm::raw_pwrite_streamOutStream) {
767    OutputStream = std::move(OutStream);
768  }
769
770  std::unique_ptr<llvm::raw_pwrite_streamtakeOutputStream() {
771    return std::move(OutputStream);
772  }
773
774  // Create module manager.
775  void createModuleManager();
776
777  bool loadModuleFile(StringRef FileName);
778
779  ModuleLoadResult loadModule(SourceLocation ImportLocModuleIdPath Path,
780                              Module::NameVisibilityKind Visibility,
781                              bool IsInclusionDirective) override;
782
783  void loadModuleFromSource(SourceLocation ImportLocStringRef ModuleName,
784                            StringRef Source) override;
785
786  void makeModuleVisible(Module *ModModule::NameVisibilityKind Visibility,
787                         SourceLocation ImportLoc) override;
788
789  bool hadModuleLoaderFatalFailure() const {
790    return ModuleLoader::HadFatalFailure;
791  }
792
793  GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
794
795  bool lookupMissingImports(StringRef NameSourceLocation TriggerLoc) override;
796
797  void addDependencyCollector(std::shared_ptr<DependencyCollectorListener) {
798    DependencyCollectors.push_back(std::move(Listener));
799  }
800
801  void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSourceESS);
802
803  InMemoryModuleCache &getModuleCache() const { return *ModuleCache; }
804};
805
806// end namespace clang
807
808#endif
809
clang::CompilerInstance::Invocation
clang::CompilerInstance::Diagnostics
clang::CompilerInstance::Target
clang::CompilerInstance::AuxTarget
clang::CompilerInstance::FileMgr
clang::CompilerInstance::SourceMgr
clang::CompilerInstance::ModuleCache
clang::CompilerInstance::PP
clang::CompilerInstance::Context
clang::CompilerInstance::ExternalSemaSrc
clang::CompilerInstance::Consumer
clang::CompilerInstance::CompletionConsumer
clang::CompilerInstance::TheSema
clang::CompilerInstance::FrontendTimerGroup
clang::CompilerInstance::FrontendTimer
clang::CompilerInstance::ModuleManager
clang::CompilerInstance::ModuleDepCollector
clang::CompilerInstance::ThePCHContainerOperations
clang::CompilerInstance::TheDependencyFileGenerator
clang::CompilerInstance::DependencyCollectors
clang::CompilerInstance::KnownModules
clang::CompilerInstance::BuiltModules
clang::CompilerInstance::DeleteBuiltModules
clang::CompilerInstance::LastModuleImportLoc
clang::CompilerInstance::LastModuleImportResult
clang::CompilerInstance::BuildGlobalModuleIndex
clang::CompilerInstance::HaveFullGlobalModuleIndex
clang::CompilerInstance::ModuleBuildFailed
clang::CompilerInstance::OutputFile
clang::CompilerInstance::OutputFile::Filename
clang::CompilerInstance::OutputFile::TempFilename
clang::CompilerInstance::NonSeekStream
clang::CompilerInstance::OutputFiles
clang::CompilerInstance::OutputStream
clang::CompilerInstance::ExecuteAction
clang::CompilerInstance::hasInvocation
clang::CompilerInstance::getInvocation
clang::CompilerInstance::setInvocation
clang::CompilerInstance::shouldBuildGlobalModuleIndex
clang::CompilerInstance::setBuildGlobalModuleIndex
clang::CompilerInstance::getAnalyzerOpts
clang::CompilerInstance::getCodeGenOpts
clang::CompilerInstance::getCodeGenOpts
clang::CompilerInstance::getDependencyOutputOpts
clang::CompilerInstance::getDependencyOutputOpts
clang::CompilerInstance::getDiagnosticOpts
clang::CompilerInstance::getDiagnosticOpts
clang::CompilerInstance::getFileSystemOpts
clang::CompilerInstance::getFileSystemOpts
clang::CompilerInstance::getFrontendOpts
clang::CompilerInstance::getFrontendOpts
clang::CompilerInstance::getHeaderSearchOpts
clang::CompilerInstance::getHeaderSearchOpts
clang::CompilerInstance::getHeaderSearchOptsPtr
clang::CompilerInstance::getLangOpts
clang::CompilerInstance::getLangOpts
clang::CompilerInstance::getPreprocessorOpts
clang::CompilerInstance::getPreprocessorOpts
clang::CompilerInstance::getPreprocessorOutputOpts
clang::CompilerInstance::getPreprocessorOutputOpts
clang::CompilerInstance::getTargetOpts
clang::CompilerInstance::getTargetOpts
clang::CompilerInstance::hasDiagnostics
clang::CompilerInstance::getDiagnostics
clang::CompilerInstance::setDiagnostics
clang::CompilerInstance::getDiagnosticClient
clang::CompilerInstance::hasTarget
clang::CompilerInstance::getTarget
clang::CompilerInstance::setTarget
clang::CompilerInstance::getAuxTarget
clang::CompilerInstance::setAuxTarget
clang::CompilerInstance::getVirtualFileSystem
clang::CompilerInstance::hasFileManager
clang::CompilerInstance::getFileManager
clang::CompilerInstance::resetAndLeakFileManager
clang::CompilerInstance::setFileManager
clang::CompilerInstance::hasSourceManager
clang::CompilerInstance::getSourceManager
clang::CompilerInstance::resetAndLeakSourceManager
clang::CompilerInstance::setSourceManager
clang::CompilerInstance::hasPreprocessor
clang::CompilerInstance::getPreprocessor
clang::CompilerInstance::getPreprocessorPtr
clang::CompilerInstance::resetAndLeakPreprocessor
clang::CompilerInstance::setPreprocessor
clang::CompilerInstance::hasASTContext
clang::CompilerInstance::getASTContext
clang::CompilerInstance::resetAndLeakASTContext
clang::CompilerInstance::setASTContext
clang::CompilerInstance::setSema
clang::CompilerInstance::hasASTConsumer
clang::CompilerInstance::getASTConsumer
clang::CompilerInstance::takeASTConsumer
clang::CompilerInstance::setASTConsumer
clang::CompilerInstance::hasSema
clang::CompilerInstance::getSema
clang::CompilerInstance::takeSema
clang::CompilerInstance::resetAndLeakSema
clang::CompilerInstance::getModuleManager
clang::CompilerInstance::setModuleManager
clang::CompilerInstance::getModuleDepCollector
clang::CompilerInstance::setModuleDepCollector
clang::CompilerInstance::getPCHContainerOperations
clang::CompilerInstance::getPCHContainerWriter
clang::CompilerInstance::getPCHContainerReader
clang::CompilerInstance::hasCodeCompletionConsumer
clang::CompilerInstance::getCodeCompletionConsumer
clang::CompilerInstance::setCodeCompletionConsumer
clang::CompilerInstance::hasFrontendTimer
clang::CompilerInstance::getFrontendTimer
clang::CompilerInstance::addOutputFile
clang::CompilerInstance::clearOutputFiles
clang::CompilerInstance::createDiagnostics
clang::CompilerInstance::createDiagnostics
clang::CompilerInstance::createFileManager
clang::CompilerInstance::createSourceManager
clang::CompilerInstance::createPreprocessor
clang::CompilerInstance::getSpecificModuleCachePath
clang::CompilerInstance::createASTContext
clang::CompilerInstance::createPCHExternalASTSource
clang::CompilerInstance::createPCHExternalASTSource
clang::CompilerInstance::createCodeCompletionConsumer
clang::CompilerInstance::createCodeCompletionConsumer
clang::CompilerInstance::createSema
clang::CompilerInstance::createFrontendTimer
clang::CompilerInstance::createDefaultOutputFile
clang::CompilerInstance::createOutputFile
clang::CompilerInstance::createOutputFile
clang::CompilerInstance::createNullOutputFile
clang::CompilerInstance::InitializeSourceManager
clang::CompilerInstance::InitializeSourceManager
clang::CompilerInstance::setOutputStream
clang::CompilerInstance::takeOutputStream
clang::CompilerInstance::createModuleManager
clang::CompilerInstance::loadModuleFile
clang::CompilerInstance::loadModule
clang::CompilerInstance::loadModuleFromSource
clang::CompilerInstance::makeModuleVisible
clang::CompilerInstance::hadModuleLoaderFatalFailure
clang::CompilerInstance::loadGlobalModuleIndex
clang::CompilerInstance::lookupMissingImports
clang::CompilerInstance::addDependencyCollector
clang::CompilerInstance::setExternalSemaSource
clang::CompilerInstance::getModuleCache