1 //===- ToolChain.h - Collections of tools for one platform ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
11 #define LLVM_CLANG_DRIVER_TOOLCHAIN_H
13 #include "clang/Basic/DebugInfoOptions.h"
14 #include "clang/Basic/LLVM.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Driver/Action.h"
18 #include "clang/Driver/Multilib.h"
19 #include "clang/Driver/Types.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.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"
60 /// Helper structure used to pass information extracted from clang executable
61 /// name such as `i686-linux-android-g++`.
62 struct ParsedClangName {
63 /// Target part of the executable name, as `i686-linux-android`.
64 std::string TargetPrefix;
66 /// Driver mode part of the executable name, as `g++`.
67 std::string ModeSuffix;
69 /// Corresponding driver mode argument, as '--driver-mode=g++'
70 const char *DriverMode = nullptr;
72 /// True if TargetPrefix is recognized as a registered target name.
73 bool TargetIsValid = false;
75 ParsedClangName() = default;
76 ParsedClangName(std::string Suffix, const char *Mode)
77 : ModeSuffix(Suffix), DriverMode(Mode) {}
78 ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
80 : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
81 TargetIsValid(IsRegistered) {}
83 bool isEmpty() const {
84 return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
88 /// ToolChain - Access to tools for a single platform.
91 using path_list = SmallVector<std::string, 16>;
109 friend class RegisterEffectiveTriple;
113 const llvm::opt::ArgList &Args;
115 // We need to initialize CachedRTTIArg before CachedRTTIMode
116 const llvm::opt::Arg *const CachedRTTIArg;
118 const RTTIMode CachedRTTIMode;
120 /// The list of toolchain specific path prefixes to search for libraries.
121 path_list LibraryPaths;
123 /// The list of toolchain specific path prefixes to search for files.
126 /// The list of toolchain specific path prefixes to search for programs.
127 path_list ProgramPaths;
129 mutable std::unique_ptr<Tool> Clang;
130 mutable std::unique_ptr<Tool> Assemble;
131 mutable std::unique_ptr<Tool> Link;
132 mutable std::unique_ptr<Tool> OffloadBundler;
134 Tool *getClang() const;
135 Tool *getAssemble() const;
136 Tool *getLink() const;
137 Tool *getClangAs() const;
138 Tool *getOffloadBundler() const;
140 mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
141 mutable std::unique_ptr<XRayArgs> XRayArguments;
143 /// The effective clang triple for the current Job.
144 mutable llvm::Triple EffectiveTriple;
146 /// Set the toolchain's effective clang triple.
147 void setEffectiveTriple(llvm::Triple ET) const {
148 EffectiveTriple = std::move(ET);
152 MultilibSet Multilibs;
153 Multilib SelectedMultilib;
155 ToolChain(const Driver &D, const llvm::Triple &T,
156 const llvm::opt::ArgList &Args);
158 void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
160 virtual Tool *buildAssembler() const;
161 virtual Tool *buildLinker() const;
162 virtual Tool *getTool(Action::ActionClass AC) const;
164 /// \name Utilities for implementing subclasses.
166 static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
167 llvm::opt::ArgStringList &CC1Args,
169 static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
170 llvm::opt::ArgStringList &CC1Args,
173 addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
174 llvm::opt::ArgStringList &CC1Args,
176 static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
177 llvm::opt::ArgStringList &CC1Args,
178 ArrayRef<StringRef> Paths);
182 virtual ~ToolChain();
186 const Driver &getDriver() const { return D; }
187 llvm::vfs::FileSystem &getVFS() const;
188 const llvm::Triple &getTriple() const { return Triple; }
190 /// Get the toolchain's aux triple, if it has one.
192 /// Exactly what the aux triple represents depends on the toolchain, but for
193 /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
194 /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
195 virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
197 /// Some toolchains need to modify the file name, for example to replace the
198 /// extension for object files with .cubin for OpenMP offloading to Nvidia
200 virtual std::string getInputFilename(const InputInfo &Input) const;
202 llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
203 StringRef getArchName() const { return Triple.getArchName(); }
204 StringRef getPlatform() const { return Triple.getVendorName(); }
205 StringRef getOS() const { return Triple.getOSName(); }
207 /// Provide the default architecture name (as expected by -arch) for
209 StringRef getDefaultUniversalArchName() const;
211 std::string getTripleString() const {
212 return Triple.getTriple();
215 /// Get the toolchain's effective clang triple.
216 const llvm::Triple &getEffectiveTriple() const {
217 assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
218 return EffectiveTriple;
221 path_list &getLibraryPaths() { return LibraryPaths; }
222 const path_list &getLibraryPaths() const { return LibraryPaths; }
224 path_list &getFilePaths() { return FilePaths; }
225 const path_list &getFilePaths() const { return FilePaths; }
227 path_list &getProgramPaths() { return ProgramPaths; }
228 const path_list &getProgramPaths() const { return ProgramPaths; }
230 const MultilibSet &getMultilibs() const { return Multilibs; }
232 const Multilib &getMultilib() const { return SelectedMultilib; }
234 const SanitizerArgs& getSanitizerArgs() const;
236 const XRayArgs& getXRayArgs() const;
238 // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
239 const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
241 // Returns the RTTIMode for the toolchain with the current arguments.
242 RTTIMode getRTTIMode() const { return CachedRTTIMode; }
244 /// Return any implicit target and/or mode flag for an invocation of
245 /// the compiler driver as `ProgName`.
247 /// For example, when called with i686-linux-android-g++, the first element
248 /// of the return value will be set to `"i686-linux-android"` and the second
249 /// will be set to "--driver-mode=g++"`.
250 /// It is OK if the target name is not registered. In this case the return
251 /// value contains false in the field TargetIsValid.
253 /// \pre `llvm::InitializeAllTargets()` has been called.
254 /// \param ProgName The name the Clang driver was invoked with (from,
256 /// \return A structure of type ParsedClangName that contains the executable
258 static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
262 /// TranslateArgs - Create a new derived argument list for any argument
263 /// translations this ToolChain may wish to perform, or 0 if no tool chain
264 /// specific translations are needed. If \p DeviceOffloadKind is specified
265 /// the translation specific for that offload kind is performed.
267 /// \param BoundArch - The bound architecture name, or 0.
268 /// \param DeviceOffloadKind - The device offload kind used for the
270 virtual llvm::opt::DerivedArgList *
271 TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
272 Action::OffloadKind DeviceOffloadKind) const {
276 /// TranslateOpenMPTargetArgs - Create a new derived argument list for
277 /// that contains the OpenMP target specific flags passed via
278 /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
279 virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
280 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
281 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
283 /// Choose a tool to use to handle the action \p JA.
285 /// This can be overridden when a particular ToolChain needs to use
286 /// a compiler other than Clang.
287 virtual Tool *SelectTool(const JobAction &JA) const;
291 std::string GetFilePath(const char *Name) const;
292 std::string GetProgramPath(const char *Name) const;
294 /// Returns the linker path, respecting the -fuse-ld= argument to determine
295 /// the linker suffix or name.
296 std::string GetLinkerPath() const;
298 /// Dispatch to the specific toolchain for verbose printing.
300 /// This is used when handling the verbose option to print detailed,
301 /// toolchain-specific information useful for understanding the behavior of
302 /// the driver on a specific platform.
303 virtual void printVerboseInfo(raw_ostream &OS) const {}
305 // Platform defaults information
307 /// Returns true if the toolchain is targeting a non-native
309 virtual bool isCrossCompiling() const;
311 /// HasNativeLTOLinker - Check whether the linker and related tools have
312 /// native LLVM support.
313 virtual bool HasNativeLLVMSupport() const;
315 /// LookupTypeForExtension - Return the default language type to use for the
317 virtual types::ID LookupTypeForExtension(StringRef Ext) const;
319 /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
320 virtual bool IsBlocksDefault() const { return false; }
322 /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
324 virtual bool IsIntegratedAssemblerDefault() const { return false; }
326 /// Check if the toolchain should use the integrated assembler.
327 virtual bool useIntegratedAs() const;
329 /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
330 virtual bool IsMathErrnoDefault() const { return true; }
332 /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
333 /// -fencode-extended-block-signature by default.
334 virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
336 /// IsObjCNonFragileABIDefault - Does this tool chain set
337 /// -fobjc-nonfragile-abi by default.
338 virtual bool IsObjCNonFragileABIDefault() const { return false; }
340 /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
341 /// mixed dispatch method be used?
342 virtual bool UseObjCMixedDispatch() const { return false; }
344 /// Check whether to enable x86 relax relocations by default.
345 virtual bool useRelaxRelocations() const;
347 /// GetDefaultStackProtectorLevel - Get the default stack protector level for
348 /// this tool chain (0=off, 1=on, 2=strong, 3=all).
349 virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
353 /// Get the default trivial automatic variable initialization.
354 virtual LangOptions::TrivialAutoVarInitKind
355 GetDefaultTrivialAutoVarInit() const {
356 return LangOptions::TrivialAutoVarInitKind::Uninitialized;
359 /// GetDefaultLinker - Get the default linker to use.
360 virtual const char *getDefaultLinker() const { return "ld"; }
362 /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
363 virtual RuntimeLibType GetDefaultRuntimeLibType() const {
364 return ToolChain::RLT_Libgcc;
367 virtual CXXStdlibType GetDefaultCXXStdlibType() const {
368 return ToolChain::CST_Libstdcxx;
371 virtual std::string getCompilerRTPath() const;
373 virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
375 bool Shared = false) const;
377 const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
379 bool Shared = false) const;
381 // Returns <ResourceDir>/lib/<OSName>/<arch>. This is used by runtimes (such
382 // as OpenMP) to find arch-specific libraries.
383 std::string getArchSpecificLibPath() const;
385 // Returns <OSname> part of above.
386 StringRef getOSLibName() const;
388 /// needsProfileRT - returns true if instrumentation profile is on.
389 static bool needsProfileRT(const llvm::opt::ArgList &Args);
391 /// Returns true if gcov instrumentation (-fprofile-arcs or --coverage) is on.
392 static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args);
394 /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
396 virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
398 /// Test whether this toolchain defaults to PIC.
399 virtual bool isPICDefault() const = 0;
401 /// Test whether this toolchain defaults to PIE.
402 virtual bool isPIEDefault() const = 0;
404 /// Tests whether this toolchain forces its default for PIC, PIE or
405 /// non-PIC. If this returns true, any PIC related flags should be ignored
406 /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
407 /// used exclusively.
408 virtual bool isPICDefaultForced() const = 0;
410 /// SupportsProfiling - Does this tool chain support -pg.
411 virtual bool SupportsProfiling() const { return true; }
413 /// Complain if this tool chain doesn't support Objective-C ARC.
414 virtual void CheckObjCARC() const {}
416 /// Get the default debug info format. Typically, this is DWARF.
417 virtual codegenoptions::DebugInfoFormat getDefaultDebugFormat() const {
418 return codegenoptions::DIF_DWARF;
421 /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
422 /// compile unit information.
423 virtual bool UseDwarfDebugFlags() const { return false; }
425 // Return the DWARF version to emit, in the absence of arguments
427 virtual unsigned GetDefaultDwarfVersion() const { return 4; }
429 // True if the driver should assume "-fstandalone-debug"
430 // in the absence of an option specifying otherwise,
431 // provided that debugging was requested in the first place.
432 // i.e. a value of 'true' does not imply that debugging is wanted.
433 virtual bool GetDefaultStandaloneDebug() const { return false; }
435 // Return the default debugger "tuning."
436 virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
437 return llvm::DebuggerKind::GDB;
440 /// Does this toolchain supports given debug info option or not.
441 virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
445 /// Adjust debug information kind considering all passed options.
446 virtual void adjustDebugInfoKind(codegenoptions::DebugInfoKind &DebugInfoKind,
447 const llvm::opt::ArgList &Args) const {}
449 /// GetExceptionModel - Return the tool chain exception model.
450 virtual llvm::ExceptionHandling
451 GetExceptionModel(const llvm::opt::ArgList &Args) const;
453 /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
454 virtual bool SupportsEmbeddedBitcode() const { return false; }
456 /// getThreadModel() - Which thread model does this target use?
457 virtual std::string getThreadModel() const { return "posix"; }
459 /// isThreadModelSupported() - Does this target support a thread model?
460 virtual bool isThreadModelSupported(const StringRef Model) const;
462 /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
463 /// command line arguments into account.
465 ComputeLLVMTriple(const llvm::opt::ArgList &Args,
466 types::ID InputType = types::TY_INVALID) const;
468 /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
469 /// target, which may take into account the command line arguments. For
470 /// example, on Darwin the -mmacosx-version-min= command line argument (which
471 /// sets the deployment target) determines the version in the triple passed to
473 virtual std::string ComputeEffectiveClangTriple(
474 const llvm::opt::ArgList &Args,
475 types::ID InputType = types::TY_INVALID) const;
477 /// getDefaultObjCRuntime - Return the default Objective-C runtime
478 /// for this platform.
480 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
481 virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
483 /// hasBlocksRuntime - Given that the user is compiling with
484 /// -fblocks, does this tool chain guarantee the existence of a
487 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
488 virtual bool hasBlocksRuntime() const { return true; }
490 /// Add the clang cc1 arguments for system include paths.
492 /// This routine is responsible for adding the necessary cc1 arguments to
493 /// include headers from standard system header directories.
495 AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
496 llvm::opt::ArgStringList &CC1Args) const;
498 /// Add options that need to be passed to cc1 for this target.
499 virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
500 llvm::opt::ArgStringList &CC1Args,
501 Action::OffloadKind DeviceOffloadKind) const;
503 /// Add warning options that need to be passed to cc1 for this target.
504 virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
506 // GetRuntimeLibType - Determine the runtime library type to use with the
507 // given compilation arguments.
508 virtual RuntimeLibType
509 GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
511 // GetCXXStdlibType - Determine the C++ standard library type to use with the
512 // given compilation arguments.
513 virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
515 /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
516 /// the include paths to use for the given C++ standard library type.
518 AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
519 llvm::opt::ArgStringList &CC1Args) const;
521 /// Returns if the C++ standard library should be linked in.
522 /// Note that e.g. -lm should still be linked even if this returns false.
523 bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
525 /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
526 /// for the given C++ standard library type.
527 virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
528 llvm::opt::ArgStringList &CmdArgs) const;
530 /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
531 void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
532 llvm::opt::ArgStringList &CmdArgs) const;
534 /// AddCCKextLibArgs - Add the system specific linker arguments to use
535 /// for kernel extensions (Darwin-specific).
536 virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
537 llvm::opt::ArgStringList &CmdArgs) const;
539 /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
540 /// global flags for unsafe floating point math, add it and return true.
542 /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
543 virtual bool AddFastMathRuntimeIfAvailable(
544 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
546 /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
547 /// a suitable profile runtime library to the linker.
548 virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
549 llvm::opt::ArgStringList &CmdArgs) const;
551 /// Add arguments to use system-specific CUDA includes.
552 virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
553 llvm::opt::ArgStringList &CC1Args) const;
555 /// Add arguments to use MCU GCC toolchain includes.
556 virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
557 llvm::opt::ArgStringList &CC1Args) const;
559 /// On Windows, returns the MSVC compatibility version.
560 virtual VersionTuple computeMSVCVersion(const Driver *D,
561 const llvm::opt::ArgList &Args) const;
563 /// Return sanitizers which are available in this toolchain.
564 virtual SanitizerMask getSupportedSanitizers() const;
566 /// Return sanitizers which are enabled by default.
567 virtual SanitizerMask getDefaultSanitizers() const { return 0; }
570 /// Set a ToolChain's effective triple. Reset it when the registration object
572 class RegisterEffectiveTriple {
576 RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
577 TC.setEffectiveTriple(std::move(T));
580 ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
583 } // namespace driver
587 #endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H