1 //===- ToolChain.h - Collections of tools for one platform ------*- 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_TOOLCHAIN_H
10 #define LLVM_CLANG_DRIVER_TOOLCHAIN_H
11 
12 #include "clang/Basic/DebugInfoOptions.h"
13 #include "clang/Basic/LLVM.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/Sanitizers.h"
16 #include "clang/Driver/Action.h"
17 #include "clang/Driver/Multilib.h"
18 #include "clang/Driver/Types.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/FloatingPointMode.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/MCTargetOptions.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/VersionTuple.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include <cassert>
30 #include <climits>
31 #include <memory>
32 #include <string>
33 #include <utility>
34 
35 namespace llvm {
36 namespace opt {
37 
38 class Arg;
39 class ArgList;
40 class DerivedArgList;
41 
42 } // namespace opt
43 namespace vfs {
44 
45 class FileSystem;
46 
47 } // namespace vfs
48 } // namespace llvm
49 
50 namespace clang {
51 
52 class ObjCRuntime;
53 
54 namespace driver {
55 
56 class Driver;
57 class InputInfo;
58 class SanitizerArgs;
59 class Tool;
60 class XRayArgs;
61 
62 /// Helper structure used to pass information extracted from clang executable
63 /// name such as `i686-linux-android-g++`.
64 struct ParsedClangName {
65   /// Target part of the executable name, as `i686-linux-android`.
66   std::string TargetPrefix;
67 
68   /// Driver mode part of the executable name, as `g++`.
69   std::string ModeSuffix;
70 
71   /// Corresponding driver mode argument, as '--driver-mode=g++'
72   const char *DriverMode = nullptr;
73 
74   /// True if TargetPrefix is recognized as a registered target name.
75   bool TargetIsValid = false;
76 
77   ParsedClangName() = default;
ParsedClangNameParsedClangName78   ParsedClangName(std::string Suffix, const char *Mode)
79       : ModeSuffix(Suffix), DriverMode(Mode) {}
ParsedClangNameParsedClangName80   ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
81                   bool IsRegistered)
82       : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
83         TargetIsValid(IsRegistered) {}
84 
isEmptyParsedClangName85   bool isEmpty() const {
86     return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
87   }
88 };
89 
90 /// ToolChain - Access to tools for a single platform.
91 class ToolChain {
92 public:
93   using path_list = SmallVector<std::string, 16>;
94 
95   enum CXXStdlibType {
96     CST_Libcxx,
97     CST_Libstdcxx
98   };
99 
100   enum RuntimeLibType {
101     RLT_CompilerRT,
102     RLT_Libgcc
103   };
104 
105   enum UnwindLibType {
106     UNW_None,
107     UNW_CompilerRT,
108     UNW_Libgcc
109   };
110 
111   enum class UnwindTableLevel {
112     None,
113     Synchronous,
114     Asynchronous,
115   };
116 
117   enum RTTIMode {
118     RM_Enabled,
119     RM_Disabled,
120   };
121 
122   struct BitCodeLibraryInfo {
123     std::string Path;
124     bool ShouldInternalize;
125     BitCodeLibraryInfo(StringRef Path, bool ShouldInternalize = true)
PathBitCodeLibraryInfo126         : Path(Path), ShouldInternalize(ShouldInternalize) {}
127   };
128 
129   enum FileType { FT_Object, FT_Static, FT_Shared };
130 
131 private:
132   friend class RegisterEffectiveTriple;
133 
134   const Driver &D;
135   llvm::Triple Triple;
136   const llvm::opt::ArgList &Args;
137 
138   // We need to initialize CachedRTTIArg before CachedRTTIMode
139   const llvm::opt::Arg *const CachedRTTIArg;
140 
141   const RTTIMode CachedRTTIMode;
142 
143   /// The list of toolchain specific path prefixes to search for libraries.
144   path_list LibraryPaths;
145 
146   /// The list of toolchain specific path prefixes to search for files.
147   path_list FilePaths;
148 
149   /// The list of toolchain specific path prefixes to search for programs.
150   path_list ProgramPaths;
151 
152   mutable std::unique_ptr<Tool> Clang;
153   mutable std::unique_ptr<Tool> Flang;
154   mutable std::unique_ptr<Tool> Assemble;
155   mutable std::unique_ptr<Tool> Link;
156   mutable std::unique_ptr<Tool> StaticLibTool;
157   mutable std::unique_ptr<Tool> IfsMerge;
158   mutable std::unique_ptr<Tool> OffloadBundler;
159   mutable std::unique_ptr<Tool> OffloadPackager;
160   mutable std::unique_ptr<Tool> LinkerWrapper;
161 
162   Tool *getClang() const;
163   Tool *getFlang() const;
164   Tool *getAssemble() const;
165   Tool *getLink() const;
166   Tool *getStaticLibTool() const;
167   Tool *getIfsMerge() const;
168   Tool *getClangAs() const;
169   Tool *getOffloadBundler() const;
170   Tool *getOffloadPackager() const;
171   Tool *getLinkerWrapper() const;
172 
173   mutable bool SanitizerArgsChecked = false;
174   mutable std::unique_ptr<XRayArgs> XRayArguments;
175 
176   /// The effective clang triple for the current Job.
177   mutable llvm::Triple EffectiveTriple;
178 
179   /// Set the toolchain's effective clang triple.
setEffectiveTriple(llvm::Triple ET)180   void setEffectiveTriple(llvm::Triple ET) const {
181     EffectiveTriple = std::move(ET);
182   }
183 
184   mutable std::optional<CXXStdlibType> cxxStdlibType;
185   mutable std::optional<RuntimeLibType> runtimeLibType;
186   mutable std::optional<UnwindLibType> unwindLibType;
187 
188 protected:
189   MultilibSet Multilibs;
190   Multilib SelectedMultilib;
191 
192   ToolChain(const Driver &D, const llvm::Triple &T,
193             const llvm::opt::ArgList &Args);
194 
195   /// Executes the given \p Executable and returns the stdout.
196   llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
197   executeToolChainProgram(StringRef Executable) const;
198 
199   void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
200 
201   virtual Tool *buildAssembler() const;
202   virtual Tool *buildLinker() const;
203   virtual Tool *buildStaticLibTool() const;
204   virtual Tool *getTool(Action::ActionClass AC) const;
205 
206   virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args,
207                                               StringRef Component,
208                                               FileType Type,
209                                               bool AddArch) const;
210 
211   /// \name Utilities for implementing subclasses.
212   ///@{
213   static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
214                                llvm::opt::ArgStringList &CC1Args,
215                                const Twine &Path);
216   static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
217                                       llvm::opt::ArgStringList &CC1Args,
218                                       const Twine &Path);
219   static void
220       addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
221                                       llvm::opt::ArgStringList &CC1Args,
222                                       const Twine &Path);
223   static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
224                                 llvm::opt::ArgStringList &CC1Args,
225                                 ArrayRef<StringRef> Paths);
226 
227   static std::string concat(StringRef Path, const Twine &A, const Twine &B = "",
228                             const Twine &C = "", const Twine &D = "");
229   ///@}
230 
231 public:
232   virtual ~ToolChain();
233 
234   // Accessors
235 
getDriver()236   const Driver &getDriver() const { return D; }
237   llvm::vfs::FileSystem &getVFS() const;
getTriple()238   const llvm::Triple &getTriple() const { return Triple; }
239 
240   /// Get the toolchain's aux triple, if it has one.
241   ///
242   /// Exactly what the aux triple represents depends on the toolchain, but for
243   /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
244   /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
getAuxTriple()245   virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
246 
247   /// Some toolchains need to modify the file name, for example to replace the
248   /// extension for object files with .cubin for OpenMP offloading to Nvidia
249   /// GPUs.
250   virtual std::string getInputFilename(const InputInfo &Input) const;
251 
getArch()252   llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
getArchName()253   StringRef getArchName() const { return Triple.getArchName(); }
getPlatform()254   StringRef getPlatform() const { return Triple.getVendorName(); }
getOS()255   StringRef getOS() const { return Triple.getOSName(); }
256 
257   /// Provide the default architecture name (as expected by -arch) for
258   /// this toolchain.
259   StringRef getDefaultUniversalArchName() const;
260 
getTripleString()261   std::string getTripleString() const {
262     return Triple.getTriple();
263   }
264 
265   /// Get the toolchain's effective clang triple.
getEffectiveTriple()266   const llvm::Triple &getEffectiveTriple() const {
267     assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
268     return EffectiveTriple;
269   }
270 
hasEffectiveTriple()271   bool hasEffectiveTriple() const {
272     return !EffectiveTriple.getTriple().empty();
273   }
274 
getLibraryPaths()275   path_list &getLibraryPaths() { return LibraryPaths; }
getLibraryPaths()276   const path_list &getLibraryPaths() const { return LibraryPaths; }
277 
getFilePaths()278   path_list &getFilePaths() { return FilePaths; }
getFilePaths()279   const path_list &getFilePaths() const { return FilePaths; }
280 
getProgramPaths()281   path_list &getProgramPaths() { return ProgramPaths; }
getProgramPaths()282   const path_list &getProgramPaths() const { return ProgramPaths; }
283 
getMultilibs()284   const MultilibSet &getMultilibs() const { return Multilibs; }
285 
getMultilib()286   const Multilib &getMultilib() const { return SelectedMultilib; }
287 
288   SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const;
289 
290   const XRayArgs& getXRayArgs() const;
291 
292   // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
getRTTIArg()293   const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
294 
295   // Returns the RTTIMode for the toolchain with the current arguments.
getRTTIMode()296   RTTIMode getRTTIMode() const { return CachedRTTIMode; }
297 
298   /// Return any implicit target and/or mode flag for an invocation of
299   /// the compiler driver as `ProgName`.
300   ///
301   /// For example, when called with i686-linux-android-g++, the first element
302   /// of the return value will be set to `"i686-linux-android"` and the second
303   /// will be set to "--driver-mode=g++"`.
304   /// It is OK if the target name is not registered. In this case the return
305   /// value contains false in the field TargetIsValid.
306   ///
307   /// \pre `llvm::InitializeAllTargets()` has been called.
308   /// \param ProgName The name the Clang driver was invoked with (from,
309   /// e.g., argv[0]).
310   /// \return A structure of type ParsedClangName that contains the executable
311   /// name parts.
312   static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
313 
314   // Tool access.
315 
316   /// TranslateArgs - Create a new derived argument list for any argument
317   /// translations this ToolChain may wish to perform, or 0 if no tool chain
318   /// specific translations are needed. If \p DeviceOffloadKind is specified
319   /// the translation specific for that offload kind is performed.
320   ///
321   /// \param BoundArch - The bound architecture name, or 0.
322   /// \param DeviceOffloadKind - The device offload kind used for the
323   /// translation.
324   virtual llvm::opt::DerivedArgList *
TranslateArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind DeviceOffloadKind)325   TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
326                 Action::OffloadKind DeviceOffloadKind) const {
327     return nullptr;
328   }
329 
330   /// TranslateOpenMPTargetArgs - Create a new derived argument list for
331   /// that contains the OpenMP target specific flags passed via
332   /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
333   virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
334       const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
335       SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
336 
337   /// Append the argument following \p A to \p DAL assuming \p A is an Xarch
338   /// argument. If \p AllocatedArgs is null pointer, synthesized arguments are
339   /// added to \p DAL, otherwise they are appended to \p AllocatedArgs.
340   virtual void TranslateXarchArgs(
341       const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
342       llvm::opt::DerivedArgList *DAL,
343       SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs = nullptr) const;
344 
345   /// Translate -Xarch_ arguments. If there are no such arguments, return
346   /// a null pointer, otherwise return a DerivedArgList containing the
347   /// translated arguments.
348   virtual llvm::opt::DerivedArgList *
349   TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
350                      Action::OffloadKind DeviceOffloadKind,
351                      SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const;
352 
353   /// Choose a tool to use to handle the action \p JA.
354   ///
355   /// This can be overridden when a particular ToolChain needs to use
356   /// a compiler other than Clang.
357   virtual Tool *SelectTool(const JobAction &JA) const;
358 
359   // Helper methods
360 
361   std::string GetFilePath(const char *Name) const;
362   std::string GetProgramPath(const char *Name) const;
363 
364   /// Returns the linker path, respecting the -fuse-ld= argument to determine
365   /// the linker suffix or name.
366   /// If LinkerIsLLD is non-nullptr, it is set to true if the returned linker
367   /// is LLD. If it's set, it can be assumed that the linker is LLD built
368   /// at the same revision as clang, and clang can make assumptions about
369   /// LLD's supported flags, error output, etc.
370   std::string GetLinkerPath(bool *LinkerIsLLD = nullptr) const;
371 
372   /// Returns the linker path for emitting a static library.
373   std::string GetStaticLibToolPath() const;
374 
375   /// Dispatch to the specific toolchain for verbose printing.
376   ///
377   /// This is used when handling the verbose option to print detailed,
378   /// toolchain-specific information useful for understanding the behavior of
379   /// the driver on a specific platform.
printVerboseInfo(raw_ostream & OS)380   virtual void printVerboseInfo(raw_ostream &OS) const {}
381 
382   // Platform defaults information
383 
384   /// Returns true if the toolchain is targeting a non-native
385   /// architecture.
386   virtual bool isCrossCompiling() const;
387 
388   /// HasNativeLTOLinker - Check whether the linker and related tools have
389   /// native LLVM support.
390   virtual bool HasNativeLLVMSupport() const;
391 
392   /// LookupTypeForExtension - Return the default language type to use for the
393   /// given extension.
394   virtual types::ID LookupTypeForExtension(StringRef Ext) const;
395 
396   /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
IsBlocksDefault()397   virtual bool IsBlocksDefault() const { return false; }
398 
399   /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
400   /// by default.
IsIntegratedAssemblerDefault()401   virtual bool IsIntegratedAssemblerDefault() const { return false; }
402 
403   /// IsIntegratedBackendDefault - Does this tool chain enable
404   /// -fintegrated-objemitter by default.
IsIntegratedBackendDefault()405   virtual bool IsIntegratedBackendDefault() const { return true; }
406 
407   /// IsIntegratedBackendSupported - Does this tool chain support
408   /// -fintegrated-objemitter.
IsIntegratedBackendSupported()409   virtual bool IsIntegratedBackendSupported() const { return true; }
410 
411   /// IsNonIntegratedBackendSupported - Does this tool chain support
412   /// -fno-integrated-objemitter.
IsNonIntegratedBackendSupported()413   virtual bool IsNonIntegratedBackendSupported() const { return false; }
414 
415   /// Check if the toolchain should use the integrated assembler.
416   virtual bool useIntegratedAs() const;
417 
418   /// Check if the toolchain should use the integrated backend.
419   virtual bool useIntegratedBackend() const;
420 
421   /// Check if the toolchain should use AsmParser to parse inlineAsm when
422   /// integrated assembler is not default.
parseInlineAsmUsingAsmParser()423   virtual bool parseInlineAsmUsingAsmParser() const { return false; }
424 
425   /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
IsMathErrnoDefault()426   virtual bool IsMathErrnoDefault() const { return true; }
427 
428   /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
429   /// -fencode-extended-block-signature by default.
IsEncodeExtendedBlockSignatureDefault()430   virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
431 
432   /// IsObjCNonFragileABIDefault - Does this tool chain set
433   /// -fobjc-nonfragile-abi by default.
IsObjCNonFragileABIDefault()434   virtual bool IsObjCNonFragileABIDefault() const { return false; }
435 
436   /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
437   /// mixed dispatch method be used?
UseObjCMixedDispatch()438   virtual bool UseObjCMixedDispatch() const { return false; }
439 
440   /// Check whether to enable x86 relax relocations by default.
441   virtual bool useRelaxRelocations() const;
442 
443   /// Check whether use IEEE binary128 as long double format by default.
444   bool defaultToIEEELongDouble() const;
445 
446   /// GetDefaultStackProtectorLevel - Get the default stack protector level for
447   /// this tool chain.
448   virtual LangOptions::StackProtectorMode
GetDefaultStackProtectorLevel(bool KernelOrKext)449   GetDefaultStackProtectorLevel(bool KernelOrKext) const {
450     return LangOptions::SSPOff;
451   }
452 
453   /// Get the default trivial automatic variable initialization.
454   virtual LangOptions::TrivialAutoVarInitKind
GetDefaultTrivialAutoVarInit()455   GetDefaultTrivialAutoVarInit() const {
456     return LangOptions::TrivialAutoVarInitKind::Uninitialized;
457   }
458 
459   /// GetDefaultLinker - Get the default linker to use.
getDefaultLinker()460   virtual const char *getDefaultLinker() const { return "ld"; }
461 
462   /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
GetDefaultRuntimeLibType()463   virtual RuntimeLibType GetDefaultRuntimeLibType() const {
464     return ToolChain::RLT_Libgcc;
465   }
466 
GetDefaultCXXStdlibType()467   virtual CXXStdlibType GetDefaultCXXStdlibType() const {
468     return ToolChain::CST_Libstdcxx;
469   }
470 
GetDefaultUnwindLibType()471   virtual UnwindLibType GetDefaultUnwindLibType() const {
472     return ToolChain::UNW_None;
473   }
474 
475   virtual std::string getCompilerRTPath() const;
476 
477   virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
478                                     StringRef Component,
479                                     FileType Type = ToolChain::FT_Static) const;
480 
481   const char *
482   getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
483                          FileType Type = ToolChain::FT_Static) const;
484 
485   std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
486                                     StringRef Component,
487                                     FileType Type = ToolChain::FT_Static) const;
488 
489   // Returns target specific runtime paths.
490   path_list getRuntimePaths() const;
491 
492   // Returns target specific standard library paths.
493   path_list getStdlibPaths() const;
494 
495   // Returns <ResourceDir>/lib/<OSName>/<arch>.  This is used by runtimes (such
496   // as OpenMP) to find arch-specific libraries.
497   std::string getArchSpecificLibPath() const;
498 
499   // Returns <OSname> part of above.
500   virtual StringRef getOSLibName() const;
501 
502   /// needsProfileRT - returns true if instrumentation profile is on.
503   static bool needsProfileRT(const llvm::opt::ArgList &Args);
504 
505   /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is on.
506   static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args);
507 
508   /// How detailed should the unwind tables be by default.
509   virtual UnwindTableLevel
510   getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const;
511 
512   /// Test whether this toolchain supports outline atomics by default.
513   virtual bool
IsAArch64OutlineAtomicsDefault(const llvm::opt::ArgList & Args)514   IsAArch64OutlineAtomicsDefault(const llvm::opt::ArgList &Args) const {
515     return false;
516   }
517 
518   /// Test whether this toolchain defaults to PIC.
519   virtual bool isPICDefault() const = 0;
520 
521   /// Test whether this toolchain defaults to PIE.
522   virtual bool isPIEDefault(const llvm::opt::ArgList &Args) const = 0;
523 
524   /// Tests whether this toolchain forces its default for PIC, PIE or
525   /// non-PIC.  If this returns true, any PIC related flags should be ignored
526   /// and instead the results of \c isPICDefault() and \c isPIEDefault(const
527   /// llvm::opt::ArgList &Args) are used exclusively.
528   virtual bool isPICDefaultForced() const = 0;
529 
530   /// SupportsProfiling - Does this tool chain support -pg.
SupportsProfiling()531   virtual bool SupportsProfiling() const { return true; }
532 
533   /// Complain if this tool chain doesn't support Objective-C ARC.
CheckObjCARC()534   virtual void CheckObjCARC() const {}
535 
536   /// Get the default debug info format. Typically, this is DWARF.
getDefaultDebugFormat()537   virtual codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
538     return codegenoptions::DIF_DWARF;
539   }
540 
541   /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
542   /// compile unit information.
UseDwarfDebugFlags()543   virtual bool UseDwarfDebugFlags() const { return false; }
544 
545   /// Add an additional -fdebug-prefix-map entry.
GetGlobalDebugPathRemapping()546   virtual std::string GetGlobalDebugPathRemapping() const { return {}; }
547 
548   // Return the DWARF version to emit, in the absence of arguments
549   // to the contrary.
GetDefaultDwarfVersion()550   virtual unsigned GetDefaultDwarfVersion() const { return 5; }
551 
552   // Some toolchains may have different restrictions on the DWARF version and
553   // may need to adjust it. E.g. NVPTX may need to enforce DWARF2 even when host
554   // compilation uses DWARF5.
getMaxDwarfVersion()555   virtual unsigned getMaxDwarfVersion() const { return UINT_MAX; }
556 
557   // True if the driver should assume "-fstandalone-debug"
558   // in the absence of an option specifying otherwise,
559   // provided that debugging was requested in the first place.
560   // i.e. a value of 'true' does not imply that debugging is wanted.
GetDefaultStandaloneDebug()561   virtual bool GetDefaultStandaloneDebug() const { return false; }
562 
563   // Return the default debugger "tuning."
getDefaultDebuggerTuning()564   virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
565     return llvm::DebuggerKind::GDB;
566   }
567 
568   /// Does this toolchain supports given debug info option or not.
supportsDebugInfoOption(const llvm::opt::Arg *)569   virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
570     return true;
571   }
572 
573   /// Adjust debug information kind considering all passed options.
adjustDebugInfoKind(codegenoptions::DebugInfoKind & DebugInfoKind,const llvm::opt::ArgList & Args)574   virtual void adjustDebugInfoKind(codegenoptions::DebugInfoKind &DebugInfoKind,
575                                    const llvm::opt::ArgList &Args) const {}
576 
577   /// GetExceptionModel - Return the tool chain exception model.
578   virtual llvm::ExceptionHandling
579   GetExceptionModel(const llvm::opt::ArgList &Args) const;
580 
581   /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
SupportsEmbeddedBitcode()582   virtual bool SupportsEmbeddedBitcode() const { return false; }
583 
584   /// getThreadModel() - Which thread model does this target use?
getThreadModel()585   virtual std::string getThreadModel() const { return "posix"; }
586 
587   /// isThreadModelSupported() - Does this target support a thread model?
588   virtual bool isThreadModelSupported(const StringRef Model) const;
589 
590   /// isBareMetal - Is this a bare metal target.
isBareMetal()591   virtual bool isBareMetal() const { return false; }
592 
getMultiarchTriple(const Driver & D,const llvm::Triple & TargetTriple,StringRef SysRoot)593   virtual std::string getMultiarchTriple(const Driver &D,
594                                          const llvm::Triple &TargetTriple,
595                                          StringRef SysRoot) const {
596     return TargetTriple.str();
597   }
598 
599   /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
600   /// command line arguments into account.
601   virtual std::string
602   ComputeLLVMTriple(const llvm::opt::ArgList &Args,
603                     types::ID InputType = types::TY_INVALID) const;
604 
605   /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
606   /// target, which may take into account the command line arguments. For
607   /// example, on Darwin the -mmacosx-version-min= command line argument (which
608   /// sets the deployment target) determines the version in the triple passed to
609   /// Clang.
610   virtual std::string ComputeEffectiveClangTriple(
611       const llvm::opt::ArgList &Args,
612       types::ID InputType = types::TY_INVALID) const;
613 
614   /// getDefaultObjCRuntime - Return the default Objective-C runtime
615   /// for this platform.
616   ///
617   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
618   virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
619 
620   /// hasBlocksRuntime - Given that the user is compiling with
621   /// -fblocks, does this tool chain guarantee the existence of a
622   /// blocks runtime?
623   ///
624   /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
hasBlocksRuntime()625   virtual bool hasBlocksRuntime() const { return true; }
626 
627   /// Return the sysroot, possibly searching for a default sysroot using
628   /// target-specific logic.
629   virtual std::string computeSysRoot() const;
630 
631   /// Add the clang cc1 arguments for system include paths.
632   ///
633   /// This routine is responsible for adding the necessary cc1 arguments to
634   /// include headers from standard system header directories.
635   virtual void
636   AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
637                             llvm::opt::ArgStringList &CC1Args) const;
638 
639   /// Add options that need to be passed to cc1 for this target.
640   virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
641                                      llvm::opt::ArgStringList &CC1Args,
642                                      Action::OffloadKind DeviceOffloadKind) const;
643 
644   /// Add options that need to be passed to cc1as for this target.
645   virtual void
646   addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args,
647                              llvm::opt::ArgStringList &CC1ASArgs) const;
648 
649   /// Add warning options that need to be passed to cc1 for this target.
650   virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
651 
652   // GetRuntimeLibType - Determine the runtime library type to use with the
653   // given compilation arguments.
654   virtual RuntimeLibType
655   GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
656 
657   // GetCXXStdlibType - Determine the C++ standard library type to use with the
658   // given compilation arguments.
659   virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
660 
661   // GetUnwindLibType - Determine the unwind library type to use with the
662   // given compilation arguments.
663   virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const;
664 
665   // Detect the highest available version of libc++ in include path.
666   virtual std::string detectLibcxxVersion(StringRef IncludePath) const;
667 
668   /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
669   /// the include paths to use for the given C++ standard library type.
670   virtual void
671   AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
672                                llvm::opt::ArgStringList &CC1Args) const;
673 
674   /// AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set
675   /// the specified include paths for the C++ standard library.
676   void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs,
677                                     llvm::opt::ArgStringList &CC1Args) const;
678 
679   /// Returns if the C++ standard library should be linked in.
680   /// Note that e.g. -lm should still be linked even if this returns false.
681   bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
682 
683   /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
684   /// for the given C++ standard library type.
685   virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
686                                    llvm::opt::ArgStringList &CmdArgs) const;
687 
688   /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
689   void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
690                           llvm::opt::ArgStringList &CmdArgs) const;
691 
692   /// AddCCKextLibArgs - Add the system specific linker arguments to use
693   /// for kernel extensions (Darwin-specific).
694   virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
695                                 llvm::opt::ArgStringList &CmdArgs) const;
696 
697   /// If a runtime library exists that sets global flags for unsafe floating
698   /// point math, return true.
699   ///
700   /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
701   virtual bool isFastMathRuntimeAvailable(
702     const llvm::opt::ArgList &Args, std::string &Path) const;
703 
704   /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
705   /// global flags for unsafe floating point math, add it and return true.
706   ///
707   /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
708   bool addFastMathRuntimeIfAvailable(
709     const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
710 
711   /// getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
712   virtual Expected<SmallVector<std::string>>
713   getSystemGPUArchs(const llvm::opt::ArgList &Args) const;
714 
715   /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
716   /// a suitable profile runtime library to the linker.
717   virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
718                                 llvm::opt::ArgStringList &CmdArgs) const;
719 
720   /// Add arguments to use system-specific CUDA includes.
721   virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
722                                   llvm::opt::ArgStringList &CC1Args) const;
723 
724   /// Add arguments to use system-specific HIP includes.
725   virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
726                                  llvm::opt::ArgStringList &CC1Args) const;
727 
728   /// Add arguments to use MCU GCC toolchain includes.
729   virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
730                                    llvm::opt::ArgStringList &CC1Args) const;
731 
732   /// On Windows, returns the MSVC compatibility version.
733   virtual VersionTuple computeMSVCVersion(const Driver *D,
734                                           const llvm::opt::ArgList &Args) const;
735 
736   /// Get paths for device libraries.
737   virtual llvm::SmallVector<BitCodeLibraryInfo, 12>
738   getDeviceLibs(const llvm::opt::ArgList &Args) const;
739 
740   /// Add the system specific linker arguments to use
741   /// for the given HIP runtime library type.
AddHIPRuntimeLibArgs(const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)742   virtual void AddHIPRuntimeLibArgs(const llvm::opt::ArgList &Args,
743                                     llvm::opt::ArgStringList &CmdArgs) const {}
744 
745   /// Return sanitizers which are available in this toolchain.
746   virtual SanitizerMask getSupportedSanitizers() const;
747 
748   /// Return sanitizers which are enabled by default.
getDefaultSanitizers()749   virtual SanitizerMask getDefaultSanitizers() const {
750     return SanitizerMask();
751   }
752 
753   /// Returns true when it's possible to split LTO unit to use whole
754   /// program devirtualization and CFI santiizers.
canSplitThinLTOUnit()755   virtual bool canSplitThinLTOUnit() const { return true; }
756 
757   /// Returns the output denormal handling type in the default floating point
758   /// environment for the given \p FPType if given. Otherwise, the default
759   /// assumed mode for any floating point type.
760   virtual llvm::DenormalMode getDefaultDenormalModeForType(
761       const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
762       const llvm::fltSemantics *FPType = nullptr) const {
763     return llvm::DenormalMode::getIEEE();
764   }
765 
766   // We want to expand the shortened versions of the triples passed in to
767   // the values used for the bitcode libraries.
getOpenMPTriple(StringRef TripleStr)768   static llvm::Triple getOpenMPTriple(StringRef TripleStr) {
769     llvm::Triple TT(TripleStr);
770     if (TT.getVendor() == llvm::Triple::UnknownVendor ||
771         TT.getOS() == llvm::Triple::UnknownOS) {
772       if (TT.getArch() == llvm::Triple::nvptx)
773         return llvm::Triple("nvptx-nvidia-cuda");
774       if (TT.getArch() == llvm::Triple::nvptx64)
775         return llvm::Triple("nvptx64-nvidia-cuda");
776       if (TT.getArch() == llvm::Triple::amdgcn)
777         return llvm::Triple("amdgcn-amd-amdhsa");
778     }
779     return TT;
780   }
781 };
782 
783 /// Set a ToolChain's effective triple. Reset it when the registration object
784 /// is destroyed.
785 class RegisterEffectiveTriple {
786   const ToolChain &TC;
787 
788 public:
RegisterEffectiveTriple(const ToolChain & TC,llvm::Triple T)789   RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
790     TC.setEffectiveTriple(std::move(T));
791   }
792 
~RegisterEffectiveTriple()793   ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
794 };
795 
796 } // namespace driver
797 
798 } // namespace clang
799 
800 #endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H
801