]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/llvm/tools/clang/include/clang/Driver/Driver.h
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / llvm / tools / clang / include / clang / Driver / Driver.h
1 //===--- Driver.h - Clang GCC Compatible Driver -----------------*- 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 CLANG_DRIVER_DRIVER_H_
11 #define CLANG_DRIVER_DRIVER_H_
12
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Driver/Phases.h"
16 #include "clang/Driver/Types.h"
17 #include "clang/Driver/Util.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
23                               // lands.
24 #include <list>
25 #include <set>
26 #include <string>
27
28 namespace llvm {
29 namespace opt {
30   class Arg;
31   class ArgList;
32   class DerivedArgList;
33   class InputArgList;
34   class OptTable;
35 }
36 }
37
38 namespace clang {
39 namespace driver {
40
41   class Action;
42   class Command;
43   class Compilation;
44   class InputInfo;
45   class JobAction;
46   class SanitizerArgs;
47   class ToolChain;
48
49 /// Driver - Encapsulate logic for constructing compilation processes
50 /// from a set of gcc-driver-like command line arguments.
51 class Driver {
52   llvm::opt::OptTable *Opts;
53
54   DiagnosticsEngine &Diags;
55
56   enum DriverMode {
57     GCCMode,
58     GXXMode,
59     CPPMode,
60     CLMode
61   } Mode;
62
63 public:
64   // Diag - Forwarding function for diagnostics.
65   DiagnosticBuilder Diag(unsigned DiagID) const {
66     return Diags.Report(DiagID);
67   }
68
69   // FIXME: Privatize once interface is stable.
70 public:
71   /// The name the driver was invoked as.
72   std::string Name;
73
74   /// The path the driver executable was in, as invoked from the
75   /// command line.
76   std::string Dir;
77
78   /// The original path to the clang executable.
79   std::string ClangExecutable;
80
81   /// The path to the installed clang directory, if any.
82   std::string InstalledDir;
83
84   /// The path to the compiler resource directory.
85   std::string ResourceDir;
86
87   /// A prefix directory used to emulated a limited subset of GCC's '-Bprefix'
88   /// functionality.
89   /// FIXME: This type of customization should be removed in favor of the
90   /// universal driver when it is ready.
91   typedef SmallVector<std::string, 4> prefix_list;
92   prefix_list PrefixDirs;
93
94   /// sysroot, if present
95   std::string SysRoot;
96
97   /// Dynamic loader prefix, if present
98   std::string DyldPrefix;
99
100   /// If the standard library is used
101   bool UseStdLib;
102
103   /// Default target triple.
104   std::string DefaultTargetTriple;
105
106   /// Default name for linked images (e.g., "a.out").
107   std::string DefaultImageName;
108
109   /// Driver title to use with help.
110   std::string DriverTitle;
111
112   /// Information about the host which can be overridden by the user.
113   std::string HostBits, HostMachine, HostSystem, HostRelease;
114
115   /// The file to log CC_PRINT_OPTIONS output to, if enabled.
116   const char *CCPrintOptionsFilename;
117
118   /// The file to log CC_PRINT_HEADERS output to, if enabled.
119   const char *CCPrintHeadersFilename;
120
121   /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
122   const char *CCLogDiagnosticsFilename;
123
124   /// A list of inputs and their types for the given arguments.
125   typedef SmallVector<std::pair<types::ID, const llvm::opt::Arg *>, 16>
126       InputList;
127
128   /// Whether the driver should follow g++ like behavior.
129   bool CCCIsCXX() const { return Mode == GXXMode; }
130
131   /// Whether the driver is just the preprocessor.
132   bool CCCIsCPP() const { return Mode == CPPMode; }
133
134   /// Whether the driver should follow cl.exe like behavior.
135   bool IsCLMode() const { return Mode == CLMode; }
136
137   /// Only print tool bindings, don't build any jobs.
138   unsigned CCCPrintBindings : 1;
139
140   /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to
141   /// CCPrintOptionsFilename or to stderr.
142   unsigned CCPrintOptions : 1;
143
144   /// Set CC_PRINT_HEADERS mode, which causes the frontend to log header include
145   /// information to CCPrintHeadersFilename or to stderr.
146   unsigned CCPrintHeaders : 1;
147
148   /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics
149   /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable
150   /// format.
151   unsigned CCLogDiagnostics : 1;
152
153   /// Whether the driver is generating diagnostics for debugging purposes.
154   unsigned CCGenDiagnostics : 1;
155
156 private:
157   /// Name to use when invoking gcc/g++.
158   std::string CCCGenericGCCName;
159
160   /// Whether to check that input files exist when constructing compilation
161   /// jobs.
162   unsigned CheckInputsExist : 1;
163
164 public:
165   /// Use lazy precompiled headers for PCH support.
166   unsigned CCCUsePCH : 1;
167
168 private:
169   /// Certain options suppress the 'no input files' warning.
170   bool SuppressMissingInputWarning : 1;
171
172   std::list<std::string> TempFiles;
173   std::list<std::string> ResultFiles;
174
175   /// \brief Cache of all the ToolChains in use by the driver.
176   ///
177   /// This maps from the string representation of a triple to a ToolChain
178   /// created targeting that triple. The driver owns all the ToolChain objects
179   /// stored in it, and will clean them up when torn down.
180   mutable llvm::StringMap<ToolChain *> ToolChains;
181
182 private:
183   /// TranslateInputArgs - Create a new derived argument list from the input
184   /// arguments, after applying the standard argument translations.
185   llvm::opt::DerivedArgList *
186   TranslateInputArgs(const llvm::opt::InputArgList &Args) const;
187
188   // getFinalPhase - Determine which compilation mode we are in and record 
189   // which option we used to determine the final phase.
190   phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL,
191                            llvm::opt::Arg **FinalPhaseArg = 0) const;
192
193 public:
194   Driver(StringRef _ClangExecutable,
195          StringRef _DefaultTargetTriple,
196          StringRef _DefaultImageName,
197          DiagnosticsEngine &_Diags);
198   ~Driver();
199
200   /// @name Accessors
201   /// @{
202
203   /// Name to use when invoking gcc/g++.
204   const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; }
205
206   const llvm::opt::OptTable &getOpts() const { return *Opts; }
207
208   const DiagnosticsEngine &getDiags() const { return Diags; }
209
210   bool getCheckInputsExist() const { return CheckInputsExist; }
211
212   void setCheckInputsExist(bool Value) { CheckInputsExist = Value; }
213
214   const std::string &getTitle() { return DriverTitle; }
215   void setTitle(std::string Value) { DriverTitle = Value; }
216
217   /// \brief Get the path to the main clang executable.
218   const char *getClangProgramPath() const {
219     return ClangExecutable.c_str();
220   }
221
222   /// \brief Get the path to where the clang executable was installed.
223   const char *getInstalledDir() const {
224     if (!InstalledDir.empty())
225       return InstalledDir.c_str();
226     return Dir.c_str();
227   }
228   void setInstalledDir(StringRef Value) {
229     InstalledDir = Value;
230   }
231
232   /// @}
233   /// @name Primary Functionality
234   /// @{
235
236   /// BuildCompilation - Construct a compilation object for a command
237   /// line argument vector.
238   ///
239   /// \return A compilation, or 0 if none was built for the given
240   /// argument vector. A null return value does not necessarily
241   /// indicate an error condition, the diagnostics should be queried
242   /// to determine if an error occurred.
243   Compilation *BuildCompilation(ArrayRef<const char *> Args);
244
245   /// @name Driver Steps
246   /// @{
247
248   /// ParseDriverMode - Look for and handle the driver mode option in Args.
249   void ParseDriverMode(ArrayRef<const char *> Args);
250
251   /// ParseArgStrings - Parse the given list of strings into an
252   /// ArgList.
253   llvm::opt::InputArgList *ParseArgStrings(ArrayRef<const char *> Args);
254
255   /// BuildInputs - Construct the list of inputs and their types from 
256   /// the given arguments.
257   ///
258   /// \param TC - The default host tool chain.
259   /// \param Args - The input arguments.
260   /// \param Inputs - The list to store the resulting compilation 
261   /// inputs onto.
262   void BuildInputs(const ToolChain &TC, const llvm::opt::DerivedArgList &Args,
263                    InputList &Inputs) const;
264
265   /// BuildActions - Construct the list of actions to perform for the
266   /// given arguments, which are only done for a single architecture.
267   ///
268   /// \param TC - The default host tool chain.
269   /// \param Args - The input arguments.
270   /// \param Actions - The list to store the resulting actions onto.
271   void BuildActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args,
272                     const InputList &Inputs, ActionList &Actions) const;
273
274   /// BuildUniversalActions - Construct the list of actions to perform
275   /// for the given arguments, which may require a universal build.
276   ///
277   /// \param TC - The default host tool chain.
278   /// \param Args - The input arguments.
279   /// \param Actions - The list to store the resulting actions onto.
280   void BuildUniversalActions(const ToolChain &TC,
281                              llvm::opt::DerivedArgList &Args,
282                              const InputList &BAInputs,
283                              ActionList &Actions) const;
284
285   /// BuildJobs - Bind actions to concrete tools and translate
286   /// arguments to form the list of jobs to run.
287   ///
288   /// \param C - The compilation that is being built.
289   void BuildJobs(Compilation &C) const;
290
291   /// ExecuteCompilation - Execute the compilation according to the command line
292   /// arguments and return an appropriate exit code.
293   ///
294   /// This routine handles additional processing that must be done in addition
295   /// to just running the subprocesses, for example reporting errors, removing
296   /// temporary files, etc.
297   int ExecuteCompilation(const Compilation &C,
298      SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) const;
299   
300   /// generateCompilationDiagnostics - Generate diagnostics information 
301   /// including preprocessed source file(s).
302   /// 
303   void generateCompilationDiagnostics(Compilation &C,
304                                       const Command *FailingCommand);
305
306   /// @}
307   /// @name Helper Methods
308   /// @{
309
310   /// PrintActions - Print the list of actions.
311   void PrintActions(const Compilation &C) const;
312
313   /// PrintHelp - Print the help text.
314   ///
315   /// \param ShowHidden - Show hidden options.
316   void PrintHelp(bool ShowHidden) const;
317
318   /// PrintVersion - Print the driver version.
319   void PrintVersion(const Compilation &C, raw_ostream &OS) const;
320
321   /// GetFilePath - Lookup \p Name in the list of file search paths.
322   ///
323   /// \param TC - The tool chain for additional information on
324   /// directories to search.
325   //
326   // FIXME: This should be in CompilationInfo.
327   std::string GetFilePath(const char *Name, const ToolChain &TC) const;
328
329   /// GetProgramPath - Lookup \p Name in the list of program search paths.
330   ///
331   /// \param TC - The provided tool chain for additional information on
332   /// directories to search.
333   //
334   // FIXME: This should be in CompilationInfo.
335   std::string GetProgramPath(const char *Name, const ToolChain &TC) const;
336
337   /// HandleImmediateArgs - Handle any arguments which should be
338   /// treated before building actions or binding tools.
339   ///
340   /// \return Whether any compilation should be built for this
341   /// invocation.
342   bool HandleImmediateArgs(const Compilation &C);
343
344   /// ConstructAction - Construct the appropriate action to do for
345   /// \p Phase on the \p Input, taking in to account arguments
346   /// like -fsyntax-only or --analyze.
347   Action *ConstructPhaseAction(const llvm::opt::ArgList &Args, phases::ID Phase,
348                                Action *Input) const;
349
350   /// BuildJobsForAction - Construct the jobs to perform for the
351   /// action \p A.
352   void BuildJobsForAction(Compilation &C,
353                           const Action *A,
354                           const ToolChain *TC,
355                           const char *BoundArch,
356                           bool AtTopLevel,
357                           bool MultipleArchs,
358                           const char *LinkingOutput,
359                           InputInfo &Result) const;
360
361   /// GetNamedOutputPath - Return the name to use for the output of
362   /// the action \p JA. The result is appended to the compilation's
363   /// list of temporary or result files, as appropriate.
364   ///
365   /// \param C - The compilation.
366   /// \param JA - The action of interest.
367   /// \param BaseInput - The original input file that this action was
368   /// triggered by.
369   /// \param BoundArch - The bound architecture. 
370   /// \param AtTopLevel - Whether this is a "top-level" action.
371   /// \param MultipleArchs - Whether multiple -arch options were supplied.
372   const char *GetNamedOutputPath(Compilation &C,
373                                  const JobAction &JA,
374                                  const char *BaseInput,
375                                  const char *BoundArch,
376                                  bool AtTopLevel,
377                                  bool MultipleArchs) const;
378
379   /// GetTemporaryPath - Return the pathname of a temporary file to use 
380   /// as part of compilation; the file will have the given prefix and suffix.
381   ///
382   /// GCC goes to extra lengths here to be a bit more robust.
383   std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
384
385   /// ShouldUseClangCompiler - Should the clang compiler be used to
386   /// handle this action.
387   bool ShouldUseClangCompiler(const JobAction &JA) const;
388
389   bool IsUsingLTO(const llvm::opt::ArgList &Args) const;
390
391 private:
392   /// \brief Retrieves a ToolChain for a particular target triple.
393   ///
394   /// Will cache ToolChains for the life of the driver object, and create them
395   /// on-demand.
396   const ToolChain &getToolChain(const llvm::opt::ArgList &Args,
397                                 StringRef DarwinArchName = "") const;
398
399   /// @}
400
401   /// \brief Get bitmasks for which option flags to include and exclude based on
402   /// the driver mode.
403   std::pair<unsigned, unsigned> getIncludeExcludeOptionFlagMasks() const;
404
405 public:
406   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
407   /// return the grouped values as integers. Numbers which are not
408   /// provided are set to 0.
409   ///
410   /// \return True if the entire string was parsed (9.2), or all
411   /// groups were parsed (10.3.5extrastuff). HadExtra is true if all
412   /// groups were parsed but extra characters remain at the end.
413   static bool GetReleaseVersion(const char *Str, unsigned &Major,
414                                 unsigned &Minor, unsigned &Micro,
415                                 bool &HadExtra);
416 };
417
418 /// \return True if the last defined optimization level is -Ofast.
419 /// And False otherwise.
420 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
421
422 } // end namespace driver
423 } // end namespace clang
424
425 #endif