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/Sanitizers.h"
14 #include "clang/Basic/VersionTuple.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Multilib.h"
17 #include "clang/Driver/Types.h"
18 #include "clang/Driver/Util.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Target/TargetOptions.h"
41 class CudaInstallationDetector;
45 class RegisterEffectiveTriple;
50 /// Helper structure used to pass information extracted from clang executable
51 /// name such as `i686-linux-android-g++`.
53 struct ParsedClangName {
54 /// Target part of the executable name, as `i686-linux-android`.
55 std::string TargetPrefix;
56 /// Driver mode part of the executable name, as `g++`.
57 std::string ModeSuffix;
58 /// Corresponding driver mode argument, as '--driver-mode=g++'
59 const char *DriverMode;
60 /// True if TargetPrefix is recognized as a registered target name.
63 ParsedClangName() : DriverMode(nullptr), TargetIsValid(false) {}
64 ParsedClangName(std::string Suffix, const char *Mode)
65 : ModeSuffix(Suffix), DriverMode(Mode), TargetIsValid(false) {}
66 ParsedClangName(std::string Target, std::string Suffix, const char *Mode,
68 : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
69 TargetIsValid(IsRegistered) {}
72 /// ToolChain - Access to tools for a single platform.
75 typedef SmallVector<std::string, 16> path_list;
90 RM_DisabledExplicitly,
97 const llvm::opt::ArgList &Args;
98 // We need to initialize CachedRTTIArg before CachedRTTIMode
99 const llvm::opt::Arg *const CachedRTTIArg;
100 const RTTIMode CachedRTTIMode;
102 /// The list of toolchain specific path prefixes to search for
106 /// The list of toolchain specific path prefixes to search for
108 path_list ProgramPaths;
110 mutable std::unique_ptr<Tool> Clang;
111 mutable std::unique_ptr<Tool> Assemble;
112 mutable std::unique_ptr<Tool> Link;
113 mutable std::unique_ptr<Tool> OffloadBundler;
114 Tool *getClang() const;
115 Tool *getAssemble() const;
116 Tool *getLink() const;
117 Tool *getClangAs() const;
118 Tool *getOffloadBundler() const;
120 mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
121 mutable std::unique_ptr<XRayArgs> XRayArguments;
123 /// The effective clang triple for the current Job.
124 mutable llvm::Triple EffectiveTriple;
126 /// Set the toolchain's effective clang triple.
127 void setEffectiveTriple(llvm::Triple ET) const {
128 EffectiveTriple = std::move(ET);
131 friend class RegisterEffectiveTriple;
134 MultilibSet Multilibs;
136 ToolChain(const Driver &D, const llvm::Triple &T,
137 const llvm::opt::ArgList &Args);
139 void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
141 virtual Tool *buildAssembler() const;
142 virtual Tool *buildLinker() const;
143 virtual Tool *getTool(Action::ActionClass AC) const;
145 /// \name Utilities for implementing subclasses.
147 static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
148 llvm::opt::ArgStringList &CC1Args,
150 static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
151 llvm::opt::ArgStringList &CC1Args,
154 addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
155 llvm::opt::ArgStringList &CC1Args,
157 static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
158 llvm::opt::ArgStringList &CC1Args,
159 ArrayRef<StringRef> Paths);
163 virtual ~ToolChain();
167 const Driver &getDriver() const { return D; }
168 vfs::FileSystem &getVFS() const;
169 const llvm::Triple &getTriple() const { return Triple; }
171 /// Get the toolchain's aux triple, if it has one.
173 /// Exactly what the aux triple represents depends on the toolchain, but for
174 /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
175 /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
176 virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
178 /// Some toolchains need to modify the file name, for example to replace the
179 /// extension for object files with .cubin for OpenMP offloading to Nvidia
181 virtual std::string getInputFilename(const InputInfo &Input) const;
183 llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
184 StringRef getArchName() const { return Triple.getArchName(); }
185 StringRef getPlatform() const { return Triple.getVendorName(); }
186 StringRef getOS() const { return Triple.getOSName(); }
188 /// \brief Provide the default architecture name (as expected by -arch) for
190 StringRef getDefaultUniversalArchName() const;
192 std::string getTripleString() const {
193 return Triple.getTriple();
196 /// Get the toolchain's effective clang triple.
197 const llvm::Triple &getEffectiveTriple() const {
198 assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
199 return EffectiveTriple;
202 path_list &getFilePaths() { return FilePaths; }
203 const path_list &getFilePaths() const { return FilePaths; }
205 path_list &getProgramPaths() { return ProgramPaths; }
206 const path_list &getProgramPaths() const { return ProgramPaths; }
208 const MultilibSet &getMultilibs() const { return Multilibs; }
210 const SanitizerArgs& getSanitizerArgs() const;
212 const XRayArgs& getXRayArgs() const;
214 // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
215 const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
217 // Returns the RTTIMode for the toolchain with the current arguments.
218 RTTIMode getRTTIMode() const { return CachedRTTIMode; }
220 /// \brief Return any implicit target and/or mode flag for an invocation of
221 /// the compiler driver as `ProgName`.
223 /// For example, when called with i686-linux-android-g++, the first element
224 /// of the return value will be set to `"i686-linux-android"` and the second
225 /// will be set to "--driver-mode=g++"`.
226 /// It is OK if the target name is not registered. In this case the return
227 /// value contains false in the field TargetIsValid.
229 /// \pre `llvm::InitializeAllTargets()` has been called.
230 /// \param ProgName The name the Clang driver was invoked with (from,
232 /// \return A structure of type ParsedClangName that contains the executable
235 static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
239 /// TranslateArgs - Create a new derived argument list for any argument
240 /// translations this ToolChain may wish to perform, or 0 if no tool chain
241 /// specific translations are needed. If \p DeviceOffloadKind is specified
242 /// the translation specific for that offload kind is performed.
244 /// \param BoundArch - The bound architecture name, or 0.
245 /// \param DeviceOffloadKind - The device offload kind used for the
247 virtual llvm::opt::DerivedArgList *
248 TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
249 Action::OffloadKind DeviceOffloadKind) const {
253 /// TranslateOpenMPTargetArgs - Create a new derived argument list for
254 /// that contains the OpenMP target specific flags passed via
255 /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
256 virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
257 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
258 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
260 /// Choose a tool to use to handle the action \p JA.
262 /// This can be overridden when a particular ToolChain needs to use
263 /// a compiler other than Clang.
264 virtual Tool *SelectTool(const JobAction &JA) const;
268 std::string GetFilePath(const char *Name) const;
269 std::string GetProgramPath(const char *Name) const;
271 /// Returns the linker path, respecting the -fuse-ld= argument to determine
272 /// the linker suffix or name.
273 std::string GetLinkerPath() const;
275 /// \brief Dispatch to the specific toolchain for verbose printing.
277 /// This is used when handling the verbose option to print detailed,
278 /// toolchain-specific information useful for understanding the behavior of
279 /// the driver on a specific platform.
280 virtual void printVerboseInfo(raw_ostream &OS) const {}
282 // Platform defaults information
284 /// \brief Returns true if the toolchain is targeting a non-native
286 virtual bool isCrossCompiling() const;
288 /// HasNativeLTOLinker - Check whether the linker and related tools have
289 /// native LLVM support.
290 virtual bool HasNativeLLVMSupport() const;
292 /// LookupTypeForExtension - Return the default language type to use for the
294 virtual types::ID LookupTypeForExtension(StringRef Ext) const;
296 /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
297 virtual bool IsBlocksDefault() const { return false; }
299 /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
301 virtual bool IsIntegratedAssemblerDefault() const { return false; }
303 /// \brief Check if the toolchain should use the integrated assembler.
304 virtual bool useIntegratedAs() const;
306 /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
307 virtual bool IsMathErrnoDefault() const { return true; }
309 /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
310 /// -fencode-extended-block-signature by default.
311 virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
313 /// IsObjCNonFragileABIDefault - Does this tool chain set
314 /// -fobjc-nonfragile-abi by default.
315 virtual bool IsObjCNonFragileABIDefault() const { return false; }
317 /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
318 /// mixed dispatch method be used?
319 virtual bool UseObjCMixedDispatch() const { return false; }
321 /// \brief Check whether to enable x86 relax relocations by default.
322 virtual bool useRelaxRelocations() const;
324 /// GetDefaultStackProtectorLevel - Get the default stack protector level for
325 /// this tool chain (0=off, 1=on, 2=strong, 3=all).
326 virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
330 /// GetDefaultLinker - Get the default linker to use.
331 virtual const char *getDefaultLinker() const {
335 /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
336 virtual RuntimeLibType GetDefaultRuntimeLibType() const {
337 return ToolChain::RLT_Libgcc;
340 virtual CXXStdlibType GetDefaultCXXStdlibType() const {
341 return ToolChain::CST_Libstdcxx;
344 virtual std::string getCompilerRTPath() const;
346 virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
348 bool Shared = false) const;
350 const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
352 bool Shared = false) const;
354 // Returns <ResourceDir>/lib/<OSName>/<arch>. This is used by runtimes (such
355 // as OpenMP) to find arch-specific libraries.
356 std::string getArchSpecificLibPath() const;
358 /// needsProfileRT - returns true if instrumentation profile is on.
359 static bool needsProfileRT(const llvm::opt::ArgList &Args);
361 /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
363 virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
365 /// \brief Test whether this toolchain defaults to PIC.
366 virtual bool isPICDefault() const = 0;
368 /// \brief Test whether this toolchain defaults to PIE.
369 virtual bool isPIEDefault() const = 0;
371 /// \brief Tests whether this toolchain forces its default for PIC, PIE or
372 /// non-PIC. If this returns true, any PIC related flags should be ignored
373 /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
374 /// used exclusively.
375 virtual bool isPICDefaultForced() const = 0;
377 /// SupportsProfiling - Does this tool chain support -pg.
378 virtual bool SupportsProfiling() const { return true; }
380 /// Complain if this tool chain doesn't support Objective-C ARC.
381 virtual void CheckObjCARC() const {}
383 /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
384 /// compile unit information.
385 virtual bool UseDwarfDebugFlags() const { return false; }
387 // Return the DWARF version to emit, in the absence of arguments
389 virtual unsigned GetDefaultDwarfVersion() const { return 4; }
391 // True if the driver should assume "-fstandalone-debug"
392 // in the absence of an option specifying otherwise,
393 // provided that debugging was requested in the first place.
394 // i.e. a value of 'true' does not imply that debugging is wanted.
395 virtual bool GetDefaultStandaloneDebug() const { return false; }
397 // Return the default debugger "tuning."
398 virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
399 return llvm::DebuggerKind::GDB;
402 /// GetExceptionModel - Return the tool chain exception model.
403 virtual llvm::ExceptionHandling
404 GetExceptionModel(const llvm::opt::ArgList &Args) const;
406 /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
407 virtual bool SupportsEmbeddedBitcode() const {
411 /// getThreadModel() - Which thread model does this target use?
412 virtual std::string getThreadModel() const { return "posix"; }
414 /// isThreadModelSupported() - Does this target support a thread model?
415 virtual bool isThreadModelSupported(const StringRef Model) const;
417 /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
418 /// command line arguments into account.
420 ComputeLLVMTriple(const llvm::opt::ArgList &Args,
421 types::ID InputType = types::TY_INVALID) const;
423 /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
424 /// target, which may take into account the command line arguments. For
425 /// example, on Darwin the -mmacosx-version-min= command line argument (which
426 /// sets the deployment target) determines the version in the triple passed to
428 virtual std::string ComputeEffectiveClangTriple(
429 const llvm::opt::ArgList &Args,
430 types::ID InputType = types::TY_INVALID) const;
432 /// getDefaultObjCRuntime - Return the default Objective-C runtime
433 /// for this platform.
435 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
436 virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
438 /// hasBlocksRuntime - Given that the user is compiling with
439 /// -fblocks, does this tool chain guarantee the existence of a
442 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
443 virtual bool hasBlocksRuntime() const { return true; }
445 /// \brief Add the clang cc1 arguments for system include paths.
447 /// This routine is responsible for adding the necessary cc1 arguments to
448 /// include headers from standard system header directories.
450 AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
451 llvm::opt::ArgStringList &CC1Args) const;
453 /// \brief Add options that need to be passed to cc1 for this target.
454 virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
455 llvm::opt::ArgStringList &CC1Args,
456 Action::OffloadKind DeviceOffloadKind) const;
458 /// \brief Add warning options that need to be passed to cc1 for this target.
459 virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
461 // GetRuntimeLibType - Determine the runtime library type to use with the
462 // given compilation arguments.
463 virtual RuntimeLibType
464 GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
466 // GetCXXStdlibType - Determine the C++ standard library type to use with the
467 // given compilation arguments.
468 virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
470 /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
471 /// the include paths to use for the given C++ standard library type.
473 AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
474 llvm::opt::ArgStringList &CC1Args) const;
476 /// Returns if the C++ standard library should be linked in.
477 /// Note that e.g. -lm should still be linked even if this returns false.
478 bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
480 /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
481 /// for the given C++ standard library type.
482 virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
483 llvm::opt::ArgStringList &CmdArgs) const;
485 /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
486 void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
487 llvm::opt::ArgStringList &CmdArgs) const;
489 /// AddCCKextLibArgs - Add the system specific linker arguments to use
490 /// for kernel extensions (Darwin-specific).
491 virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
492 llvm::opt::ArgStringList &CmdArgs) const;
494 /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
495 /// global flags for unsafe floating point math, add it and return true.
497 /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
498 virtual bool AddFastMathRuntimeIfAvailable(
499 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
500 /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
501 /// a suitable profile runtime library to the linker.
502 virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
503 llvm::opt::ArgStringList &CmdArgs) const;
505 /// \brief Add arguments to use system-specific CUDA includes.
506 virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
507 llvm::opt::ArgStringList &CC1Args) const;
509 /// \brief Add arguments to use MCU GCC toolchain includes.
510 virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
511 llvm::opt::ArgStringList &CC1Args) const;
513 /// \brief On Windows, returns the MSVC compatibility version.
514 virtual VersionTuple computeMSVCVersion(const Driver *D,
515 const llvm::opt::ArgList &Args) const;
517 /// \brief Return sanitizers which are available in this toolchain.
518 virtual SanitizerMask getSupportedSanitizers() const;
520 /// \brief Return sanitizers which are enabled by default.
521 virtual SanitizerMask getDefaultSanitizers() const { return 0; }
524 /// Set a ToolChain's effective triple. Reset it when the registration object
526 class RegisterEffectiveTriple {
530 RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
531 TC.setEffectiveTriple(std::move(T));
534 ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
537 } // end namespace driver
538 } // end namespace clang