clang  3.7.0
Driver.h
Go to the documentation of this file.
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 
28 namespace llvm {
29 namespace opt {
30  class Arg;
31  class ArgList;
32  class DerivedArgList;
33  class InputArgList;
34  class OptTable;
35 }
36 }
37 
38 namespace clang {
39 namespace driver {
40 
41  class Action;
42  class Command;
43  class Compilation;
44  class InputInfo;
45  class JobList;
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.
52 class 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 
70 public:
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.
77 public:
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 emulate 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.
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.
118 
119  /// The file to log CC_PRINT_OPTIONS output to, if enabled.
121 
122  /// The file to log CC_PRINT_HEADERS output to, if enabled.
124 
125  /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
127 
128  /// A list of inputs and their types for the given arguments.
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 
160 private:
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 
168 public:
169  /// Use lazy precompiled headers for PCH support.
170  unsigned CCCUsePCH : 1;
171 
172 private:
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 
186 private:
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, Command &Cmd);
199 
200  void generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
201  SmallVectorImpl<std::string> &Names) const;
202 
203 public:
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) {
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.
256 
257  /// @name Driver Steps
258  /// @{
259 
260  /// ParseDriverMode - Look for and handle the driver mode option in 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.
310  SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands);
311 
312  /// generateCompilationDiagnostics - Generate diagnostics information
313  /// including preprocessed source file(s).
314  ///
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.
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 llvm::opt::ArgList &Args) const;
406 
407 private:
408  /// \brief Retrieves a ToolChain for a particular \p 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  const llvm::Triple &Target) 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 
421 public:
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.
436 bool isOptimizationLevelFast(const llvm::opt::ArgList &Args);
437 
438 } // end namespace driver
439 } // end namespace clang
440 
441 #endif
void ParseDriverMode(ArrayRef< const char * > Args)
ParseDriverMode - Look for and handle the driver mode option in Args.
Definition: Driver.cpp:82
void BuildUniversalActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args, const InputList &BAInputs, ActionList &Actions) const
Definition: Driver.cpp:955
prefix_list PrefixDirs
Definition: Driver.h:99
unsigned CCPrintHeaders
Definition: Driver.h:150
unsigned CCCUsePCH
Use lazy precompiled headers for PCH support.
Definition: Driver.h:170
std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const
Definition: Driver.cpp:2142
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1118
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:215
std::string DyldPrefix
Dynamic loader prefix, if present.
Definition: Driver.h:105
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:72
static bool GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
Definition: Driver.cpp:2264
Compilation * BuildCompilation(ArrayRef< const char * > Args)
Definition: Driver.cpp:363
bool ShouldUseClangCompiler(const JobAction &JA) const
Definition: Driver.cpp:2246
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:133
void PrintHelp(bool ShowHidden) const
Definition: Driver.cpp:735
unsigned CCLogDiagnostics
Definition: Driver.h:155
const std::string & getTitle()
Definition: Driver.h:223
void PrintActions(const Compilation &C) const
PrintActions - Print the list of actions.
Definition: Driver.cpp:935
std::string Dir
Definition: Driver.h:83
FrontendAction * Action
Definition: Tooling.cpp:168
void BuildActions(const ToolChain &TC, llvm::opt::DerivedArgList &Args, const InputList &Inputs, ActionList &Actions) const
Definition: Driver.cpp:1318
bool HandleImmediateArgs(const Compilation &C)
Definition: Driver.cpp:775
const char * getInstalledDir() const
Get the path to where the clang executable was installed.
Definition: Driver.h:232
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
Driver(StringRef _ClangExecutable, StringRef _DefaultTargetTriple, DiagnosticsEngine &_Diags)
Definition: Driver.cpp:48
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
std::unique_ptr< Action > ConstructPhaseAction(const ToolChain &TC, const llvm::opt::ArgList &Args, phases::ID Phase, std::unique_ptr< Action > Input) const
Definition: Driver.cpp:1493
bool IsUsingLTO(const llvm::opt::ArgList &Args) const
Definition: Driver.cpp:1575
std::string GetFilePath(const char *Name, const ToolChain &TC) const
Definition: Driver.cpp:2059
llvm::opt::InputArgList ParseArgStrings(ArrayRef< const char * > Args)
Definition: Driver.cpp:109
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition: Driver.h:139
void generateCompilationDiagnostics(Compilation &C, const Command &FailingCommand)
Definition: Driver.cpp:497
const char * CCPrintOptionsFilename
The file to log CC_PRINT_OPTIONS output to, if enabled.
Definition: Driver.h:120
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
Definition: Driver.cpp:749
bool isSaveTempsEnabled() const
Definition: Driver.h:241
std::string HostSystem
Definition: Driver.h:117
SmallVector< std::pair< types::ID, const llvm::opt::Arg * >, 16 > InputList
A list of inputs and their types for the given arguments.
Definition: Driver.h:130
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:866
bool getCheckInputsExist() const
Definition: Driver.h:219
unsigned CCPrintOptions
Definition: Driver.h:146
void setCheckInputsExist(bool Value)
Definition: Driver.h:221
int ExecuteCompilation(Compilation &C, SmallVectorImpl< std::pair< int, const Command * > > &FailingCommands)
Definition: Driver.cpp:671
bool UseStdLib
If the standard library is used.
Definition: Driver.h:108
std::string GetProgramPath(const char *Name, const ToolChain &TC) const
Definition: Driver.cpp:2107
void BuildJobs(Compilation &C) const
Definition: Driver.cpp:1579
std::string HostBits
Information about the host which can be overridden by the user.
Definition: Driver.h:117
std::string InstalledDir
The path to the installed clang directory, if any.
Definition: Driver.h:89
bool isSaveTempsObj() const
Definition: Driver.h:242
void setTitle(std::string Value)
Definition: Driver.h:224
const char * getDefaultImageName() const
Returns the default name for linked images (e.g., "a.out").
Definition: Driver.cpp:1862
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
Definition: Driver.h:136
const char * GetNamedOutputPath(Compilation &C, const JobAction &JA, const char *BaseInput, const char *BoundArch, bool AtTopLevel, bool MultipleArchs) const
Definition: Driver.cpp:1900
const char * CCPrintHeadersFilename
The file to log CC_PRINT_HEADERS output to, if enabled.
Definition: Driver.h:123
unsigned CCCPrintBindings
Only print tool bindings, don't build any jobs.
Definition: Driver.h:142
std::string HostMachine
Definition: Driver.h:117
std::string SysRoot
sysroot, if present
Definition: Driver.h:102
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
std::string Name
The name the driver was invoked as.
Definition: Driver.h:79
const char * getClangProgramPath() const
Get the path to the main clang executable.
Definition: Driver.h:227
Defines the Diagnostic-related interfaces.
std::string ClangExecutable
The original path to the clang executable.
Definition: Driver.h:86
void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, InputList &Inputs) const
Definition: Driver.cpp:1078
const DiagnosticsEngine & getDiags() const
Definition: Driver.h:217
SmallVector< std::string, 4 > prefix_list
Definition: Driver.h:98
const char * CCLogDiagnosticsFilename
The file to log CC_LOG_DIAGNOSTICS output to, if enabled.
Definition: Driver.h:126
std::string DefaultTargetTriple
Default target triple.
Definition: Driver.h:111
const StringRef Input
const std::string & getCCCGenericGCCName() const
Name to use when invoking gcc/g++.
Definition: Driver.h:213
void BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, InputInfo &Result) const
Definition: Driver.cpp:1740
std::string DriverTitle
Driver title to use with help.
Definition: Driver.h:114
void setInstalledDir(StringRef Value)
Definition: Driver.h:237
std::string HostRelease
Definition: Driver.h:117
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition: Driver.h:158
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:43
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:92