1 //===- ToolChain.h - Collections of tools for one platform ------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
10 #define LLVM_CLANG_DRIVER_TOOLCHAIN_H
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/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCTargetOptions.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/VersionTuple.h"
26 #include "llvm/Target/TargetOptions.h"
59 /// Helper structure used to pass information extracted from clang executable
60 /// name such as `i686-linux-android-g++`.
61 struct ParsedClangName {
62 /// Target part of the executable name, as `i686-linux-android`.
63 std::string TargetPrefix;
65 /// Driver mode part of the executable name, as `g++`.
66 std::string ModeSuffix;
68 /// Corresponding driver mode argument, as '--driver-mode=g++'
69 const char *DriverMode = nullptr;
71 /// True if TargetPrefix is recognized as a registered target name.
72 bool TargetIsValid = false;
74 ParsedClangName() = default;
75 ParsedClangName(std::string Suffix, const char *Mode)
76 : ModeSuffix(Suffix), DriverMode(Mode) {}
77 ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
79 : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
80 TargetIsValid(IsRegistered) {}
82 bool isEmpty() const {
83 return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
87 /// ToolChain - Access to tools for a single platform.
90 using path_list = SmallVector<std::string, 16>;
113 enum FileType { FT_Object, FT_Static, FT_Shared };
116 friend class RegisterEffectiveTriple;
120 const llvm::opt::ArgList &Args;
122 // We need to initialize CachedRTTIArg before CachedRTTIMode
123 const llvm::opt::Arg *const CachedRTTIArg;
125 const RTTIMode CachedRTTIMode;
127 /// The list of toolchain specific path prefixes to search for libraries.
128 path_list LibraryPaths;
130 /// The list of toolchain specific path prefixes to search for files.
133 /// The list of toolchain specific path prefixes to search for programs.
134 path_list ProgramPaths;
136 mutable std::unique_ptr<Tool> Clang;
137 mutable std::unique_ptr<Tool> Flang;
138 mutable std::unique_ptr<Tool> Assemble;
139 mutable std::unique_ptr<Tool> Link;
140 mutable std::unique_ptr<Tool> IfsMerge;
141 mutable std::unique_ptr<Tool> OffloadBundler;
142 mutable std::unique_ptr<Tool> OffloadWrapper;
144 Tool *getClang() const;
145 Tool *getFlang() const;
146 Tool *getAssemble() const;
147 Tool *getLink() const;
148 Tool *getIfsMerge() const;
149 Tool *getClangAs() const;
150 Tool *getOffloadBundler() const;
151 Tool *getOffloadWrapper() const;
153 mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
154 mutable std::unique_ptr<XRayArgs> XRayArguments;
156 /// The effective clang triple for the current Job.
157 mutable llvm::Triple EffectiveTriple;
159 /// Set the toolchain's effective clang triple.
160 void setEffectiveTriple(llvm::Triple ET) const {
161 EffectiveTriple = std::move(ET);
165 MultilibSet Multilibs;
166 Multilib SelectedMultilib;
168 ToolChain(const Driver &D, const llvm::Triple &T,
169 const llvm::opt::ArgList &Args);
171 void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
173 virtual Tool *buildAssembler() const;
174 virtual Tool *buildLinker() const;
175 virtual Tool *getTool(Action::ActionClass AC) const;
177 /// \name Utilities for implementing subclasses.
179 static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
180 llvm::opt::ArgStringList &CC1Args,
182 static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
183 llvm::opt::ArgStringList &CC1Args,
186 addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
187 llvm::opt::ArgStringList &CC1Args,
189 static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
190 llvm::opt::ArgStringList &CC1Args,
191 ArrayRef<StringRef> Paths);
195 virtual ~ToolChain();
199 const Driver &getDriver() const { return D; }
200 llvm::vfs::FileSystem &getVFS() const;
201 const llvm::Triple &getTriple() const { return Triple; }
203 /// Get the toolchain's aux triple, if it has one.
205 /// Exactly what the aux triple represents depends on the toolchain, but for
206 /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
207 /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
208 virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
210 /// Some toolchains need to modify the file name, for example to replace the
211 /// extension for object files with .cubin for OpenMP offloading to Nvidia
213 virtual std::string getInputFilename(const InputInfo &Input) const;
215 llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
216 StringRef getArchName() const { return Triple.getArchName(); }
217 StringRef getPlatform() const { return Triple.getVendorName(); }
218 StringRef getOS() const { return Triple.getOSName(); }
220 /// Provide the default architecture name (as expected by -arch) for
222 StringRef getDefaultUniversalArchName() const;
224 std::string getTripleString() const {
225 return Triple.getTriple();
228 /// Get the toolchain's effective clang triple.
229 const llvm::Triple &getEffectiveTriple() const {
230 assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
231 return EffectiveTriple;
234 path_list &getLibraryPaths() { return LibraryPaths; }
235 const path_list &getLibraryPaths() const { return LibraryPaths; }
237 path_list &getFilePaths() { return FilePaths; }
238 const path_list &getFilePaths() const { return FilePaths; }
240 path_list &getProgramPaths() { return ProgramPaths; }
241 const path_list &getProgramPaths() const { return ProgramPaths; }
243 const MultilibSet &getMultilibs() const { return Multilibs; }
245 const Multilib &getMultilib() const { return SelectedMultilib; }
247 const SanitizerArgs& getSanitizerArgs() const;
249 const XRayArgs& getXRayArgs() const;
251 // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
252 const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
254 // Returns the RTTIMode for the toolchain with the current arguments.
255 RTTIMode getRTTIMode() const { return CachedRTTIMode; }
257 /// Return any implicit target and/or mode flag for an invocation of
258 /// the compiler driver as `ProgName`.
260 /// For example, when called with i686-linux-android-g++, the first element
261 /// of the return value will be set to `"i686-linux-android"` and the second
262 /// will be set to "--driver-mode=g++"`.
263 /// It is OK if the target name is not registered. In this case the return
264 /// value contains false in the field TargetIsValid.
266 /// \pre `llvm::InitializeAllTargets()` has been called.
267 /// \param ProgName The name the Clang driver was invoked with (from,
269 /// \return A structure of type ParsedClangName that contains the executable
271 static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
275 /// TranslateArgs - Create a new derived argument list for any argument
276 /// translations this ToolChain may wish to perform, or 0 if no tool chain
277 /// specific translations are needed. If \p DeviceOffloadKind is specified
278 /// the translation specific for that offload kind is performed.
280 /// \param BoundArch - The bound architecture name, or 0.
281 /// \param DeviceOffloadKind - The device offload kind used for the
283 virtual llvm::opt::DerivedArgList *
284 TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
285 Action::OffloadKind DeviceOffloadKind) const {
289 /// TranslateOpenMPTargetArgs - Create a new derived argument list for
290 /// that contains the OpenMP target specific flags passed via
291 /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
292 virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
293 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
294 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
296 /// Choose a tool to use to handle the action \p JA.
298 /// This can be overridden when a particular ToolChain needs to use
299 /// a compiler other than Clang.
300 virtual Tool *SelectTool(const JobAction &JA) const;
304 std::string GetFilePath(const char *Name) const;
305 std::string GetProgramPath(const char *Name) const;
307 /// Returns the linker path, respecting the -fuse-ld= argument to determine
308 /// the linker suffix or name.
309 std::string GetLinkerPath() const;
311 /// Dispatch to the specific toolchain for verbose printing.
313 /// This is used when handling the verbose option to print detailed,
314 /// toolchain-specific information useful for understanding the behavior of
315 /// the driver on a specific platform.
316 virtual void printVerboseInfo(raw_ostream &OS) const {}
318 // Platform defaults information
320 /// Returns true if the toolchain is targeting a non-native
322 virtual bool isCrossCompiling() const;
324 /// HasNativeLTOLinker - Check whether the linker and related tools have
325 /// native LLVM support.
326 virtual bool HasNativeLLVMSupport() const;
328 /// LookupTypeForExtension - Return the default language type to use for the
330 virtual types::ID LookupTypeForExtension(StringRef Ext) const;
332 /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
333 virtual bool IsBlocksDefault() const { return false; }
335 /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
337 virtual bool IsIntegratedAssemblerDefault() const { return false; }
339 /// Check if the toolchain should use the integrated assembler.
340 virtual bool useIntegratedAs() const;
342 /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
343 virtual bool IsMathErrnoDefault() const { return true; }
345 /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
346 /// -fencode-extended-block-signature by default.
347 virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
349 /// IsObjCNonFragileABIDefault - Does this tool chain set
350 /// -fobjc-nonfragile-abi by default.
351 virtual bool IsObjCNonFragileABIDefault() const { return false; }
353 /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
354 /// mixed dispatch method be used?
355 virtual bool UseObjCMixedDispatch() const { return false; }
357 /// Check whether to enable x86 relax relocations by default.
358 virtual bool useRelaxRelocations() const;
360 /// GetDefaultStackProtectorLevel - Get the default stack protector level for
361 /// this tool chain (0=off, 1=on, 2=strong, 3=all).
362 virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
366 /// Get the default trivial automatic variable initialization.
367 virtual LangOptions::TrivialAutoVarInitKind
368 GetDefaultTrivialAutoVarInit() const {
369 return LangOptions::TrivialAutoVarInitKind::Uninitialized;
372 /// GetDefaultLinker - Get the default linker to use.
373 virtual const char *getDefaultLinker() const { return "ld"; }
375 /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
376 virtual RuntimeLibType GetDefaultRuntimeLibType() const {
377 return ToolChain::RLT_Libgcc;
380 virtual CXXStdlibType GetDefaultCXXStdlibType() const {
381 return ToolChain::CST_Libstdcxx;
384 virtual UnwindLibType GetDefaultUnwindLibType() const {
385 return ToolChain::UNW_None;
388 virtual std::string getCompilerRTPath() const;
390 virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
392 FileType Type = ToolChain::FT_Static) const;
395 getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
396 FileType Type = ToolChain::FT_Static) const;
398 // Returns target specific runtime path if it exists.
399 virtual Optional<std::string> getRuntimePath() const;
401 // Returns target specific C++ library path if it exists.
402 virtual Optional<std::string> getCXXStdlibPath() const;
404 // Returns <ResourceDir>/lib/<OSName>/<arch>. This is used by runtimes (such
405 // as OpenMP) to find arch-specific libraries.
406 std::string getArchSpecificLibPath() const;
408 // Returns <OSname> part of above.
409 StringRef getOSLibName() const;
411 /// needsProfileRT - returns true if instrumentation profile is on.
412 static bool needsProfileRT(const llvm::opt::ArgList &Args);
414 /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is on.
415 static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args);
417 /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
419 virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
421 /// Test whether this toolchain defaults to PIC.
422 virtual bool isPICDefault() const = 0;
424 /// Test whether this toolchain defaults to PIE.
425 virtual bool isPIEDefault() const = 0;
427 /// Test whether this toolchaind defaults to non-executable stacks.
428 virtual bool isNoExecStackDefault() const;
430 /// Tests whether this toolchain forces its default for PIC, PIE or
431 /// non-PIC. If this returns true, any PIC related flags should be ignored
432 /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
433 /// used exclusively.
434 virtual bool isPICDefaultForced() const = 0;
436 /// SupportsProfiling - Does this tool chain support -pg.
437 virtual bool SupportsProfiling() const { return true; }
439 /// Complain if this tool chain doesn't support Objective-C ARC.
440 virtual void CheckObjCARC() const {}
442 /// Get the default debug info format. Typically, this is DWARF.
443 virtual codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
444 return codegenoptions::DIF_DWARF;
447 /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
448 /// compile unit information.
449 virtual bool UseDwarfDebugFlags() const { return false; }
451 // Return the DWARF version to emit, in the absence of arguments
453 virtual unsigned GetDefaultDwarfVersion() const { return 4; }
455 // True if the driver should assume "-fstandalone-debug"
456 // in the absence of an option specifying otherwise,
457 // provided that debugging was requested in the first place.
458 // i.e. a value of 'true' does not imply that debugging is wanted.
459 virtual bool GetDefaultStandaloneDebug() const { return false; }
461 // Return the default debugger "tuning."
462 virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
463 return llvm::DebuggerKind::GDB;
466 /// Does this toolchain supports given debug info option or not.
467 virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
471 /// Adjust debug information kind considering all passed options.
472 virtual void adjustDebugInfoKind(codegenoptions::DebugInfoKind &DebugInfoKind,
473 const llvm::opt::ArgList &Args) const {}
475 /// GetExceptionModel - Return the tool chain exception model.
476 virtual llvm::ExceptionHandling
477 GetExceptionModel(const llvm::opt::ArgList &Args) const;
479 /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
480 virtual bool SupportsEmbeddedBitcode() const { return false; }
482 /// getThreadModel() - Which thread model does this target use?
483 virtual std::string getThreadModel() const { return "posix"; }
485 /// isThreadModelSupported() - Does this target support a thread model?
486 virtual bool isThreadModelSupported(const StringRef Model) const;
488 /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
489 /// command line arguments into account.
491 ComputeLLVMTriple(const llvm::opt::ArgList &Args,
492 types::ID InputType = types::TY_INVALID) const;
494 /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
495 /// target, which may take into account the command line arguments. For
496 /// example, on Darwin the -mmacosx-version-min= command line argument (which
497 /// sets the deployment target) determines the version in the triple passed to
499 virtual std::string ComputeEffectiveClangTriple(
500 const llvm::opt::ArgList &Args,
501 types::ID InputType = types::TY_INVALID) const;
503 /// getDefaultObjCRuntime - Return the default Objective-C runtime
504 /// for this platform.
506 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
507 virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
509 /// hasBlocksRuntime - Given that the user is compiling with
510 /// -fblocks, does this tool chain guarantee the existence of a
513 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
514 virtual bool hasBlocksRuntime() const { return true; }
516 /// Add the clang cc1 arguments for system include paths.
518 /// This routine is responsible for adding the necessary cc1 arguments to
519 /// include headers from standard system header directories.
521 AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
522 llvm::opt::ArgStringList &CC1Args) const;
524 /// Add options that need to be passed to cc1 for this target.
525 virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
526 llvm::opt::ArgStringList &CC1Args,
527 Action::OffloadKind DeviceOffloadKind) const;
529 /// Add warning options that need to be passed to cc1 for this target.
530 virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
532 // GetRuntimeLibType - Determine the runtime library type to use with the
533 // given compilation arguments.
534 virtual RuntimeLibType
535 GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
537 // GetCXXStdlibType - Determine the C++ standard library type to use with the
538 // given compilation arguments.
539 virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
541 // GetUnwindLibType - Determine the unwind library type to use with the
542 // given compilation arguments.
543 virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const;
545 /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
546 /// the include paths to use for the given C++ standard library type.
548 AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
549 llvm::opt::ArgStringList &CC1Args) const;
551 /// AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set
552 /// the specified include paths for the C++ standard library.
553 void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs,
554 llvm::opt::ArgStringList &CC1Args) const;
556 /// Returns if the C++ standard library should be linked in.
557 /// Note that e.g. -lm should still be linked even if this returns false.
558 bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
560 /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
561 /// for the given C++ standard library type.
562 virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
563 llvm::opt::ArgStringList &CmdArgs) const;
565 /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
566 void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
567 llvm::opt::ArgStringList &CmdArgs) const;
569 /// AddCCKextLibArgs - Add the system specific linker arguments to use
570 /// for kernel extensions (Darwin-specific).
571 virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
572 llvm::opt::ArgStringList &CmdArgs) const;
574 /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
575 /// global flags for unsafe floating point math, add it and return true.
577 /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
578 virtual bool AddFastMathRuntimeIfAvailable(
579 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
581 /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
582 /// a suitable profile runtime library to the linker.
583 virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
584 llvm::opt::ArgStringList &CmdArgs) const;
586 /// Add arguments to use system-specific CUDA includes.
587 virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
588 llvm::opt::ArgStringList &CC1Args) const;
590 /// Add arguments to use MCU GCC toolchain includes.
591 virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
592 llvm::opt::ArgStringList &CC1Args) const;
594 /// On Windows, returns the MSVC compatibility version.
595 virtual VersionTuple computeMSVCVersion(const Driver *D,
596 const llvm::opt::ArgList &Args) const;
598 /// Return sanitizers which are available in this toolchain.
599 virtual SanitizerMask getSupportedSanitizers() const;
601 /// Return sanitizers which are enabled by default.
602 virtual SanitizerMask getDefaultSanitizers() const {
603 return SanitizerMask();
606 /// Returns true when it's possible to split LTO unit to use whole
607 /// program devirtualization and CFI santiizers.
608 virtual bool canSplitThinLTOUnit() const { return true; }
611 /// Set a ToolChain's effective triple. Reset it when the registration object
613 class RegisterEffectiveTriple {
617 RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
618 TC.setEffectiveTriple(std::move(T));
621 ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
624 } // namespace driver
628 #endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H