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