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