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