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