Coverage Report

Created: 2021-09-21 08:58

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