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