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