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