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