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