CompilerInstance.h 27 KB

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