CompilerInstance.h revision a93e3b5bde9f0a7b59215f19f176f7d69881b81c
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
10#ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11#define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
12
13#include "clang/Frontend/CompilerInvocation.h"
14#include "llvm/ADT/IntrusiveRefCntPtr.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/OwningPtr.h"
17#include <cassert>
18#include <list>
19#include <string>
20
21namespace llvm {
22class LLVMContext;
23class raw_ostream;
24class raw_fd_ostream;
25class Timer;
26}
27
28namespace clang {
29class ASTContext;
30class ASTConsumer;
31class CodeCompleteConsumer;
32class Diagnostic;
33class DiagnosticClient;
34class ExternalASTSource;
35class FileManager;
36class FrontendAction;
37class PCHReader;
38class Preprocessor;
39class SourceManager;
40class TargetInfo;
41
42/// CompilerInstance - Helper class for managing a single instance of the Clang
43/// compiler.
44///
45/// The CompilerInstance serves two purposes:
46///  (1) It manages the various objects which are necessary to run the compiler,
47///      for example the preprocessor, the target information, and the AST
48///      context.
49///  (2) It provides utility routines for constructing and manipulating the
50///      common Clang objects.
51///
52/// The compiler instance generally owns the instance of all the objects that it
53/// manages. However, clients can still share objects by manually setting the
54/// object and retaking ownership prior to destroying the CompilerInstance.
55///
56/// The compiler instance is intended to simplify clients, but not to lock them
57/// in to the compiler instance for everything. When possible, utility functions
58/// come in two forms; a short form that reuses the CompilerInstance objects,
59/// and a long form that takes explicit instances of any required objects.
60class CompilerInstance {
61  /// The LLVM context used for this instance.
62  llvm::OwningPtr<llvm::LLVMContext> LLVMContext;
63
64  /// The options used in this compiler instance.
65  llvm::OwningPtr<CompilerInvocation> Invocation;
66
67  /// The diagnostics engine instance.
68  llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics;
69
70  /// The diagnostics client instance.
71  llvm::OwningPtr<DiagnosticClient> DiagClient;
72
73  /// The target being compiled for.
74  llvm::OwningPtr<TargetInfo> Target;
75
76  /// The file manager.
77  llvm::OwningPtr<FileManager> FileMgr;
78
79  /// The source manager.
80  llvm::OwningPtr<SourceManager> SourceMgr;
81
82  /// The preprocessor.
83  llvm::OwningPtr<Preprocessor> PP;
84
85  /// The AST context.
86  llvm::OwningPtr<ASTContext> Context;
87
88  /// The AST consumer.
89  llvm::OwningPtr<ASTConsumer> Consumer;
90
91  /// The code completion consumer.
92  llvm::OwningPtr<CodeCompleteConsumer> CompletionConsumer;
93
94  /// The frontend timer
95  llvm::OwningPtr<llvm::Timer> FrontendTimer;
96
97  /// The list of active output files.
98  std::list< std::pair<std::string, llvm::raw_ostream*> > OutputFiles;
99
100  /// The PCH reader. Not owned; the ASTContext owns this.
101  PCHReader *Reader;
102
103  void operator=(const CompilerInstance &);  // DO NOT IMPLEMENT
104  CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT
105public:
106  CompilerInstance();
107  ~CompilerInstance();
108
109  /// @name High-Level Operations
110  /// {
111
112  /// ExecuteAction - Execute the provided action against the compiler's
113  /// CompilerInvocation object.
114  ///
115  /// This function makes the following assumptions:
116  ///
117  ///  - The invocation options should be initialized. This function does not
118  ///    handle the '-help' or '-version' options, clients should handle those
119  ///    directly.
120  ///
121  ///  - The diagnostics engine should have already been created by the client.
122  ///
123  ///  - No other CompilerInstance state should have been initialized (this is
124  ///    an unchecked error).
125  ///
126  ///  - Clients should have initialized any LLVM target features that may be
127  ///    required.
128  ///
129  ///  - Clients should eventually call llvm_shutdown() upon the completion of
130  ///    this routine to ensure that any managed objects are properly destroyed.
131  ///
132  /// Note that this routine may write output to 'stderr'.
133  ///
134  /// \param Act - The action to execute.
135  /// \return - True on success.
136  //
137  // FIXME: This function should take the stream to write any debugging /
138  // verbose output to as an argument.
139  //
140  // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
141  // of the context or else not CompilerInstance specific.
142  bool ExecuteAction(FrontendAction &Act);
143
144  /// }
145  /// @name LLVM Context
146  /// {
147
148  bool hasLLVMContext() const { return LLVMContext != 0; }
149
150  llvm::LLVMContext &getLLVMContext() const {
151    assert(LLVMContext && "Compiler instance has no LLVM context!");
152    return *LLVMContext;
153  }
154
155  llvm::LLVMContext *takeLLVMContext() { return LLVMContext.take(); }
156
157  /// setLLVMContext - Replace the current LLVM context and take ownership of
158  /// \arg Value.
159  void setLLVMContext(llvm::LLVMContext *Value);
160
161  /// }
162  /// @name Compiler Invocation and Options
163  /// {
164
165  bool hasInvocation() const { return Invocation != 0; }
166
167  CompilerInvocation &getInvocation() {
168    assert(Invocation && "Compiler instance has no invocation!");
169    return *Invocation;
170  }
171
172  CompilerInvocation *takeInvocation() { return Invocation.take(); }
173
174  /// setInvocation - Replace the current invocation; the compiler instance
175  /// takes ownership of \arg Value.
176  void setInvocation(CompilerInvocation *Value);
177
178  /// }
179  /// @name Forwarding Methods
180  /// {
181
182  AnalyzerOptions &getAnalyzerOpts() {
183    return Invocation->getAnalyzerOpts();
184  }
185  const AnalyzerOptions &getAnalyzerOpts() const {
186    return Invocation->getAnalyzerOpts();
187  }
188
189  CodeGenOptions &getCodeGenOpts() {
190    return Invocation->getCodeGenOpts();
191  }
192  const CodeGenOptions &getCodeGenOpts() const {
193    return Invocation->getCodeGenOpts();
194  }
195
196  DependencyOutputOptions &getDependencyOutputOpts() {
197    return Invocation->getDependencyOutputOpts();
198  }
199  const DependencyOutputOptions &getDependencyOutputOpts() const {
200    return Invocation->getDependencyOutputOpts();
201  }
202
203  DiagnosticOptions &getDiagnosticOpts() {
204    return Invocation->getDiagnosticOpts();
205  }
206  const DiagnosticOptions &getDiagnosticOpts() const {
207    return Invocation->getDiagnosticOpts();
208  }
209
210  FrontendOptions &getFrontendOpts() {
211    return Invocation->getFrontendOpts();
212  }
213  const FrontendOptions &getFrontendOpts() const {
214    return Invocation->getFrontendOpts();
215  }
216
217  HeaderSearchOptions &getHeaderSearchOpts() {
218    return Invocation->getHeaderSearchOpts();
219  }
220  const HeaderSearchOptions &getHeaderSearchOpts() const {
221    return Invocation->getHeaderSearchOpts();
222  }
223
224  LangOptions &getLangOpts() {
225    return Invocation->getLangOpts();
226  }
227  const LangOptions &getLangOpts() const {
228    return Invocation->getLangOpts();
229  }
230
231  PreprocessorOptions &getPreprocessorOpts() {
232    return Invocation->getPreprocessorOpts();
233  }
234  const PreprocessorOptions &getPreprocessorOpts() const {
235    return Invocation->getPreprocessorOpts();
236  }
237
238  PreprocessorOutputOptions &getPreprocessorOutputOpts() {
239    return Invocation->getPreprocessorOutputOpts();
240  }
241  const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
242    return Invocation->getPreprocessorOutputOpts();
243  }
244
245  TargetOptions &getTargetOpts() {
246    return Invocation->getTargetOpts();
247  }
248  const TargetOptions &getTargetOpts() const {
249    return Invocation->getTargetOpts();
250  }
251
252  /// }
253  /// @name Diagnostics Engine
254  /// {
255
256  bool hasDiagnostics() const { return Diagnostics != 0; }
257
258  Diagnostic &getDiagnostics() const {
259    assert(Diagnostics && "Compiler instance has no diagnostics!");
260    return *Diagnostics;
261  }
262
263  /// setDiagnostics - Replace the current diagnostics engine; the compiler
264  /// instance takes ownership of \arg Value.
265  void setDiagnostics(Diagnostic *Value);
266
267  DiagnosticClient &getDiagnosticClient() const {
268    assert(DiagClient && "Compiler instance has no diagnostic client!");
269    return *DiagClient;
270  }
271
272  /// takeDiagnosticClient - Remove the current diagnostics client and give
273  /// ownership to the caller.
274  DiagnosticClient *takeDiagnosticClient() { return DiagClient.take(); }
275
276  /// setDiagnosticClient - Replace the current diagnostics client; the compiler
277  /// instance takes ownership of \arg Value.
278  void setDiagnosticClient(DiagnosticClient *Value);
279
280  /// }
281  /// @name Target Info
282  /// {
283
284  bool hasTarget() const { return Target != 0; }
285
286  TargetInfo &getTarget() const {
287    assert(Target && "Compiler instance has no target!");
288    return *Target;
289  }
290
291  /// takeTarget - Remove the current diagnostics engine and give ownership
292  /// to the caller.
293  TargetInfo *takeTarget() { return Target.take(); }
294
295  /// setTarget - Replace the current diagnostics engine; the compiler
296  /// instance takes ownership of \arg Value.
297  void setTarget(TargetInfo *Value);
298
299  /// }
300  /// @name File Manager
301  /// {
302
303  bool hasFileManager() const { return FileMgr != 0; }
304
305  FileManager &getFileManager() const {
306    assert(FileMgr && "Compiler instance has no file manager!");
307    return *FileMgr;
308  }
309
310  /// takeFileManager - Remove the current file manager and give ownership to
311  /// the caller.
312  FileManager *takeFileManager() { return FileMgr.take(); }
313
314  /// setFileManager - Replace the current file manager; the compiler instance
315  /// takes ownership of \arg Value.
316  void setFileManager(FileManager *Value);
317
318  /// }
319  /// @name Source Manager
320  /// {
321
322  bool hasSourceManager() const { return SourceMgr != 0; }
323
324  SourceManager &getSourceManager() const {
325    assert(SourceMgr && "Compiler instance has no source manager!");
326    return *SourceMgr;
327  }
328
329  /// takeSourceManager - Remove the current source manager and give ownership
330  /// to the caller.
331  SourceManager *takeSourceManager() { return SourceMgr.take(); }
332
333  /// setSourceManager - Replace the current source manager; the compiler
334  /// instance takes ownership of \arg Value.
335  void setSourceManager(SourceManager *Value);
336
337  /// }
338  /// @name Preprocessor
339  /// {
340
341  bool hasPreprocessor() const { return PP != 0; }
342
343  Preprocessor &getPreprocessor() const {
344    assert(PP && "Compiler instance has no preprocessor!");
345    return *PP;
346  }
347
348  /// takePreprocessor - Remove the current preprocessor and give ownership to
349  /// the caller.
350  Preprocessor *takePreprocessor() { return PP.take(); }
351
352  /// setPreprocessor - Replace the current preprocessor; the compiler instance
353  /// takes ownership of \arg Value.
354  void setPreprocessor(Preprocessor *Value);
355
356  /// }
357  /// @name ASTContext
358  /// {
359
360  bool hasASTContext() const { return Context != 0; }
361
362  ASTContext &getASTContext() const {
363    assert(Context && "Compiler instance has no AST context!");
364    return *Context;
365  }
366
367  /// takeASTContext - Remove the current AST context and give ownership to the
368  /// caller.
369  ASTContext *takeASTContext() { return Context.take(); }
370
371  /// setASTContext - Replace the current AST context; the compiler instance
372  /// takes ownership of \arg Value.
373  void setASTContext(ASTContext *Value);
374
375  /// }
376  /// @name ASTConsumer
377  /// {
378
379  bool hasASTConsumer() const { return Consumer != 0; }
380
381  ASTConsumer &getASTConsumer() const {
382    assert(Consumer && "Compiler instance has no AST consumer!");
383    return *Consumer;
384  }
385
386  /// takeASTConsumer - Remove the current AST consumer and give ownership to
387  /// the caller.
388  ASTConsumer *takeASTConsumer() { return Consumer.take(); }
389
390  /// setASTConsumer - Replace the current AST consumer; the compiler instance
391  /// takes ownership of \arg Value.
392  void setASTConsumer(ASTConsumer *Value);
393
394  /// }
395  /// @name Code Completion
396  /// {
397
398  bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; }
399
400  CodeCompleteConsumer &getCodeCompletionConsumer() const {
401    assert(CompletionConsumer &&
402           "Compiler instance has no code completion consumer!");
403    return *CompletionConsumer;
404  }
405
406  /// takeCodeCompletionConsumer - Remove the current code completion consumer
407  /// and give ownership to the caller.
408  CodeCompleteConsumer *takeCodeCompletionConsumer() {
409    return CompletionConsumer.take();
410  }
411
412  /// setCodeCompletionConsumer - Replace the current code completion consumer;
413  /// the compiler instance takes ownership of \arg Value.
414  void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
415
416  /// }
417  /// @name Frontend timer
418  /// {
419
420  bool hasFrontendTimer() const { return FrontendTimer != 0; }
421
422  llvm::Timer &getFrontendTimer() const {
423    assert(FrontendTimer && "Compiler instance has no frontend timer!");
424    return *FrontendTimer;
425  }
426
427  /// }
428  /// @name Output Files
429  /// {
430
431  /// getOutputFileList - Get the list of (path, output stream) pairs of output
432  /// files; the path may be empty but the stream will always be non-null.
433  const std::list< std::pair<std::string,
434                             llvm::raw_ostream*> > &getOutputFileList() const;
435
436  /// addOutputFile - Add an output file onto the list of tracked output files.
437  ///
438  /// \param Path - The path to the output file, or empty.
439  /// \param OS - The output stream, which should be non-null.
440  void addOutputFile(llvm::StringRef Path, llvm::raw_ostream *OS);
441
442  /// clearOutputFiles - Clear the output file list, destroying the contained
443  /// output streams.
444  ///
445  /// \param EraseFiles - If true, attempt to erase the files from disk.
446  void clearOutputFiles(bool EraseFiles);
447
448  /// }
449  /// @name Construction Utility Methods
450  /// {
451
452  /// Create the diagnostics engine using the invocation's diagnostic options
453  /// and replace any existing one with it.
454  ///
455  /// Note that this routine also replaces the diagnostic client.
456  void createDiagnostics(int Argc, char **Argv);
457
458  /// Create a Diagnostic object with a the TextDiagnosticPrinter.
459  ///
460  /// The \arg Argc and \arg Argv arguments are used only for logging purposes,
461  /// when the diagnostic options indicate that the compiler should output
462  /// logging information.
463  ///
464  /// Note that this creates an unowned DiagnosticClient, if using directly the
465  /// caller is responsible for releasing the returned Diagnostic's client
466  /// eventually.
467  ///
468  /// \param Opts - The diagnostic options; note that the created text
469  /// diagnostic object contains a reference to these options and its lifetime
470  /// must extend past that of the diagnostic engine.
471  ///
472  /// \return The new object on success, or null on failure.
473  static llvm::IntrusiveRefCntPtr<Diagnostic>
474  createDiagnostics(const DiagnosticOptions &Opts, int Argc, char **Argv);
475
476  /// Create the file manager and replace any existing one with it.
477  void createFileManager();
478
479  /// Create the source manager and replace any existing one with it.
480  void createSourceManager();
481
482  /// Create the preprocessor, using the invocation, file, and source managers,
483  /// and replace any existing one with it.
484  void createPreprocessor();
485
486  /// Create a Preprocessor object.
487  ///
488  /// Note that this also creates a new HeaderSearch object which will be owned
489  /// by the resulting Preprocessor.
490  ///
491  /// \return The new object on success, or null on failure.
492  static Preprocessor *createPreprocessor(Diagnostic &, const LangOptions &,
493                                          const PreprocessorOptions &,
494                                          const HeaderSearchOptions &,
495                                          const DependencyOutputOptions &,
496                                          const TargetInfo &,
497                                          const FrontendOptions &,
498                                          SourceManager &, FileManager &);
499
500  /// Create the AST context.
501  void createASTContext();
502
503  /// Create an external AST source to read a PCH file and attach it to the AST
504  /// context.
505  void createPCHExternalASTSource(llvm::StringRef Path);
506
507  /// Create an external AST source to read a PCH file.
508  ///
509  /// \return - The new object on success, or null on failure.
510  static ExternalASTSource *
511  createPCHExternalASTSource(llvm::StringRef Path, const std::string &Sysroot,
512                             Preprocessor &PP, ASTContext &Context);
513
514  /// Get the PCH reader, if any.
515  PCHReader *getPCHReader() { return Reader; }
516
517  /// Create a code completion consumer using the invocation; note that this
518  /// will cause the source manager to truncate the input source file at the
519  /// completion point.
520  void createCodeCompletionConsumer();
521
522  /// Create a code completion consumer to print code completion results, at
523  /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg
524  /// OS.
525  static CodeCompleteConsumer *
526  createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
527                               unsigned Line, unsigned Column,
528                               bool UseDebugPrinter, bool ShowMacros,
529                               bool ShowCodePatterns, llvm::raw_ostream &OS);
530
531  /// Create the frontend timer and replace any existing one with it.
532  void createFrontendTimer();
533
534  /// Create the default output file (from the invocation's options) and add it
535  /// to the list of tracked output files.
536  ///
537  /// \return - Null on error.
538  llvm::raw_fd_ostream *
539  createDefaultOutputFile(bool Binary = true, llvm::StringRef BaseInput = "",
540                          llvm::StringRef Extension = "");
541
542  /// Create a new output file and add it to the list of tracked output files,
543  /// optionally deriving the output path name.
544  ///
545  /// \return - Null on error.
546  llvm::raw_fd_ostream *
547  createOutputFile(llvm::StringRef OutputPath, bool Binary = true,
548                   llvm::StringRef BaseInput = "",
549                   llvm::StringRef Extension = "");
550
551  /// Create a new output file, optionally deriving the output path name.
552  ///
553  /// If \arg OutputPath is empty, then createOutputFile will derive an output
554  /// path location as \arg BaseInput, with any suffix removed, and \arg
555  /// Extension appended.
556  ///
557  /// \param OutputPath - If given, the path to the output file.
558  /// \param Error [out] - On failure, the error message.
559  /// \param BaseInput - If \arg OutputPath is empty, the input path name to use
560  /// for deriving the output path.
561  /// \param Extension - The extension to use for derived output names.
562  /// \param Binary - The mode to open the file in.
563  /// \param ResultPathName [out] - If given, the result path name will be
564  /// stored here on success.
565  static llvm::raw_fd_ostream *
566  createOutputFile(llvm::StringRef OutputPath, std::string &Error,
567                   bool Binary = true, llvm::StringRef BaseInput = "",
568                   llvm::StringRef Extension = "",
569                   std::string *ResultPathName = 0);
570
571  /// }
572  /// @name Initialization Utility Methods
573  /// {
574
575  /// InitializeSourceManager - Initialize the source manager to set InputFile
576  /// as the main file.
577  ///
578  /// \return True on success.
579  bool InitializeSourceManager(llvm::StringRef InputFile);
580
581  /// InitializeSourceManager - Initialize the source manager to set InputFile
582  /// as the main file.
583  ///
584  /// \return True on success.
585  static bool InitializeSourceManager(llvm::StringRef InputFile,
586                                      Diagnostic &Diags,
587                                      FileManager &FileMgr,
588                                      SourceManager &SourceMgr,
589                                      const FrontendOptions &Opts);
590
591  /// }
592};
593
594} // end namespace clang
595
596#endif
597