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