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