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