CompilerInstance.h 27 KB

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