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