Warning: That file was not part of the compilation database. It may have many parsing errors.

1//===- ToolChain.h - Collections of tools for one platform ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLVM_CLANG_DRIVER_TOOLCHAIN_H
11#define LLVM_CLANG_DRIVER_TOOLCHAIN_H
12
13#include "clang/Basic/LLVM.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/ArrayRef.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Triple.h"
22#include "llvm/MC/MCTargetOptions.h"
23#include "llvm/Option/Option.h"
24#include "llvm/Support/VersionTuple.h"
25#include "llvm/Target/TargetOptions.h"
26#include <cassert>
27#include <memory>
28#include <string>
29#include <utility>
30
31namespace llvm {
32namespace opt {
33
34class Arg;
35class ArgList;
36class DerivedArgList;
37
38} // namespace opt
39} // namespace llvm
40
41namespace clang {
42
43class ObjCRuntime;
44
45namespace vfs {
46
47class FileSystem;
48
49} // namespace vfs
50
51namespace driver {
52
53class Driver;
54class InputInfo;
55class SanitizerArgs;
56class Tool;
57class XRayArgs;
58
59/// Helper structure used to pass information extracted from clang executable
60/// name such as `i686-linux-android-g++`.
61struct ParsedClangName {
62 /// Target part of the executable name, as `i686-linux-android`.
63 std::string TargetPrefix;
64
65 /// Driver mode part of the executable name, as `g++`.
66 std::string ModeSuffix;
67
68 /// Corresponding driver mode argument, as '--driver-mode=g++'
69 const char *DriverMode = nullptr;
70
71 /// True if TargetPrefix is recognized as a registered target name.
72 bool TargetIsValid = false;
73
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,
78 bool IsRegistered)
79 : TargetPrefix(Target), ModeSuffix(Suffix), DriverMode(Mode),
80 TargetIsValid(IsRegistered) {}
81
82 bool isEmpty() const {
83 return TargetPrefix.empty() && ModeSuffix.empty() && DriverMode == nullptr;
84 }
85};
86
87/// ToolChain - Access to tools for a single platform.
88class ToolChain {
89public:
90 using path_list = SmallVector<std::string, 16>;
91
92 enum CXXStdlibType {
93 CST_Libcxx,
94 CST_Libstdcxx
95 };
96
97 enum RuntimeLibType {
98 RLT_CompilerRT,
99 RLT_Libgcc
100 };
101
102 enum RTTIMode {
103 RM_Enabled,
104 RM_Disabled,
105 };
106
107private:
108 friend class RegisterEffectiveTriple;
109
110 const Driver &D;
111 llvm::Triple Triple;
112 const llvm::opt::ArgList &Args;
113
114 // We need to initialize CachedRTTIArg before CachedRTTIMode
115 const llvm::opt::Arg *const CachedRTTIArg;
116
117 const RTTIMode CachedRTTIMode;
118
119 /// The list of toolchain specific path prefixes to search for files.
120 path_list FilePaths;
121
122 /// The list of toolchain specific path prefixes to search for programs.
123 path_list ProgramPaths;
124
125 mutable std::unique_ptr<Tool> Clang;
126 mutable std::unique_ptr<Tool> Assemble;
127 mutable std::unique_ptr<Tool> Link;
128 mutable std::unique_ptr<Tool> OffloadBundler;
129
130 Tool *getClang() const;
131 Tool *getAssemble() const;
132 Tool *getLink() const;
133 Tool *getClangAs() const;
134 Tool *getOffloadBundler() const;
135
136 mutable std::unique_ptr<SanitizerArgs> SanitizerArguments;
137 mutable std::unique_ptr<XRayArgs> XRayArguments;
138
139 /// The effective clang triple for the current Job.
140 mutable llvm::Triple EffectiveTriple;
141
142 /// Set the toolchain's effective clang triple.
143 void setEffectiveTriple(llvm::Triple ET) const {
144 EffectiveTriple = std::move(ET);
145 }
146
147protected:
148 MultilibSet Multilibs;
149
150 ToolChain(const Driver &D, const llvm::Triple &T,
151 const llvm::opt::ArgList &Args);
152
153 void setTripleEnvironment(llvm::Triple::EnvironmentType Env);
154
155 virtual Tool *buildAssembler() const;
156 virtual Tool *buildLinker() const;
157 virtual Tool *getTool(Action::ActionClass AC) const;
158
159 /// \name Utilities for implementing subclasses.
160 ///@{
161 static void addSystemInclude(const llvm::opt::ArgList &DriverArgs,
162 llvm::opt::ArgStringList &CC1Args,
163 const Twine &Path);
164 static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs,
165 llvm::opt::ArgStringList &CC1Args,
166 const Twine &Path);
167 static void
168 addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs,
169 llvm::opt::ArgStringList &CC1Args,
170 const Twine &Path);
171 static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs,
172 llvm::opt::ArgStringList &CC1Args,
173 ArrayRef<StringRef> Paths);
174 ///@}
175
176public:
177 virtual ~ToolChain();
178
179 // Accessors
180
181 const Driver &getDriver() const { return D; }
182 vfs::FileSystem &getVFS() const;
183 const llvm::Triple &getTriple() const { return Triple; }
184
185 /// Get the toolchain's aux triple, if it has one.
186 ///
187 /// Exactly what the aux triple represents depends on the toolchain, but for
188 /// example when compiling CUDA code for the GPU, the triple might be NVPTX,
189 /// while the aux triple is the host (CPU) toolchain, e.g. x86-linux-gnu.
190 virtual const llvm::Triple *getAuxTriple() const { return nullptr; }
191
192 /// Some toolchains need to modify the file name, for example to replace the
193 /// extension for object files with .cubin for OpenMP offloading to Nvidia
194 /// GPUs.
195 virtual std::string getInputFilename(const InputInfo &Input) const;
196
197 llvm::Triple::ArchType getArch() const { return Triple.getArch(); }
198 StringRef getArchName() const { return Triple.getArchName(); }
199 StringRef getPlatform() const { return Triple.getVendorName(); }
200 StringRef getOS() const { return Triple.getOSName(); }
201
202 /// Provide the default architecture name (as expected by -arch) for
203 /// this toolchain.
204 StringRef getDefaultUniversalArchName() const;
205
206 std::string getTripleString() const {
207 return Triple.getTriple();
208 }
209
210 /// Get the toolchain's effective clang triple.
211 const llvm::Triple &getEffectiveTriple() const {
212 assert(!EffectiveTriple.getTriple().empty() && "No effective triple");
213 return EffectiveTriple;
214 }
215
216 path_list &getFilePaths() { return FilePaths; }
217 const path_list &getFilePaths() const { return FilePaths; }
218
219 path_list &getProgramPaths() { return ProgramPaths; }
220 const path_list &getProgramPaths() const { return ProgramPaths; }
221
222 const MultilibSet &getMultilibs() const { return Multilibs; }
223
224 const SanitizerArgs& getSanitizerArgs() const;
225
226 const XRayArgs& getXRayArgs() const;
227
228 // Returns the Arg * that explicitly turned on/off rtti, or nullptr.
229 const llvm::opt::Arg *getRTTIArg() const { return CachedRTTIArg; }
230
231 // Returns the RTTIMode for the toolchain with the current arguments.
232 RTTIMode getRTTIMode() const { return CachedRTTIMode; }
233
234 /// Return any implicit target and/or mode flag for an invocation of
235 /// the compiler driver as `ProgName`.
236 ///
237 /// For example, when called with i686-linux-android-g++, the first element
238 /// of the return value will be set to `"i686-linux-android"` and the second
239 /// will be set to "--driver-mode=g++"`.
240 /// It is OK if the target name is not registered. In this case the return
241 /// value contains false in the field TargetIsValid.
242 ///
243 /// \pre `llvm::InitializeAllTargets()` has been called.
244 /// \param ProgName The name the Clang driver was invoked with (from,
245 /// e.g., argv[0]).
246 /// \return A structure of type ParsedClangName that contains the executable
247 /// name parts.
248 static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName);
249
250 // Tool access.
251
252 /// TranslateArgs - Create a new derived argument list for any argument
253 /// translations this ToolChain may wish to perform, or 0 if no tool chain
254 /// specific translations are needed. If \p DeviceOffloadKind is specified
255 /// the translation specific for that offload kind is performed.
256 ///
257 /// \param BoundArch - The bound architecture name, or 0.
258 /// \param DeviceOffloadKind - The device offload kind used for the
259 /// translation.
260 virtual llvm::opt::DerivedArgList *
261 TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
262 Action::OffloadKind DeviceOffloadKind) const {
263 return nullptr;
264 }
265
266 /// TranslateOpenMPTargetArgs - Create a new derived argument list for
267 /// that contains the OpenMP target specific flags passed via
268 /// -Xopenmp-target -opt=val OR -Xopenmp-target=<triple> -opt=val
269 virtual llvm::opt::DerivedArgList *TranslateOpenMPTargetArgs(
270 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
271 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const;
272
273 /// Choose a tool to use to handle the action \p JA.
274 ///
275 /// This can be overridden when a particular ToolChain needs to use
276 /// a compiler other than Clang.
277 virtual Tool *SelectTool(const JobAction &JA) const;
278
279 // Helper methods
280
281 std::string GetFilePath(const char *Name) const;
282 std::string GetProgramPath(const char *Name) const;
283
284 /// Returns the linker path, respecting the -fuse-ld= argument to determine
285 /// the linker suffix or name.
286 std::string GetLinkerPath() const;
287
288 /// Dispatch to the specific toolchain for verbose printing.
289 ///
290 /// This is used when handling the verbose option to print detailed,
291 /// toolchain-specific information useful for understanding the behavior of
292 /// the driver on a specific platform.
293 virtual void printVerboseInfo(raw_ostream &OS) const {}
294
295 // Platform defaults information
296
297 /// Returns true if the toolchain is targeting a non-native
298 /// architecture.
299 virtual bool isCrossCompiling() const;
300
301 /// HasNativeLTOLinker - Check whether the linker and related tools have
302 /// native LLVM support.
303 virtual bool HasNativeLLVMSupport() const;
304
305 /// LookupTypeForExtension - Return the default language type to use for the
306 /// given extension.
307 virtual types::ID LookupTypeForExtension(StringRef Ext) const;
308
309 /// IsBlocksDefault - Does this tool chain enable -fblocks by default.
310 virtual bool IsBlocksDefault() const { return false; }
311
312 /// IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as
313 /// by default.
314 virtual bool IsIntegratedAssemblerDefault() const { return false; }
315
316 /// Check if the toolchain should use the integrated assembler.
317 virtual bool useIntegratedAs() const;
318
319 /// IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
320 virtual bool IsMathErrnoDefault() const { return true; }
321
322 /// IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable
323 /// -fencode-extended-block-signature by default.
324 virtual bool IsEncodeExtendedBlockSignatureDefault() const { return false; }
325
326 /// IsObjCNonFragileABIDefault - Does this tool chain set
327 /// -fobjc-nonfragile-abi by default.
328 virtual bool IsObjCNonFragileABIDefault() const { return false; }
329
330 /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the
331 /// mixed dispatch method be used?
332 virtual bool UseObjCMixedDispatch() const { return false; }
333
334 /// Check whether to enable x86 relax relocations by default.
335 virtual bool useRelaxRelocations() const;
336
337 /// GetDefaultStackProtectorLevel - Get the default stack protector level for
338 /// this tool chain (0=off, 1=on, 2=strong, 3=all).
339 virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
340 return 0;
341 }
342
343 /// GetDefaultLinker - Get the default linker to use.
344 virtual const char *getDefaultLinker() const { return "ld"; }
345
346 /// GetDefaultRuntimeLibType - Get the default runtime library variant to use.
347 virtual RuntimeLibType GetDefaultRuntimeLibType() const {
348 return ToolChain::RLT_Libgcc;
349 }
350
351 virtual CXXStdlibType GetDefaultCXXStdlibType() const {
352 return ToolChain::CST_Libstdcxx;
353 }
354
355 virtual std::string getCompilerRTPath() const;
356
357 virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
358 StringRef Component,
359 bool Shared = false) const;
360
361 const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
362 StringRef Component,
363 bool Shared = false) const;
364
365 // Returns <ResourceDir>/lib/<OSName>/<arch>. This is used by runtimes (such
366 // as OpenMP) to find arch-specific libraries.
367 std::string getArchSpecificLibPath() const;
368
369 // Returns <OSname> part of above.
370 StringRef getOSLibName() const;
371
372 /// needsProfileRT - returns true if instrumentation profile is on.
373 static bool needsProfileRT(const llvm::opt::ArgList &Args);
374
375 /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
376 /// by default.
377 virtual bool IsUnwindTablesDefault(const llvm::opt::ArgList &Args) const;
378
379 /// Test whether this toolchain defaults to PIC.
380 virtual bool isPICDefault() const = 0;
381
382 /// Test whether this toolchain defaults to PIE.
383 virtual bool isPIEDefault() const = 0;
384
385 /// Tests whether this toolchain forces its default for PIC, PIE or
386 /// non-PIC. If this returns true, any PIC related flags should be ignored
387 /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
388 /// used exclusively.
389 virtual bool isPICDefaultForced() const = 0;
390
391 /// SupportsProfiling - Does this tool chain support -pg.
392 virtual bool SupportsProfiling() const { return true; }
393
394 /// Complain if this tool chain doesn't support Objective-C ARC.
395 virtual void CheckObjCARC() const {}
396
397 /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf
398 /// compile unit information.
399 virtual bool UseDwarfDebugFlags() const { return false; }
400
401 // Return the DWARF version to emit, in the absence of arguments
402 // to the contrary.
403 virtual unsigned GetDefaultDwarfVersion() const { return 4; }
404
405 // True if the driver should assume "-fstandalone-debug"
406 // in the absence of an option specifying otherwise,
407 // provided that debugging was requested in the first place.
408 // i.e. a value of 'true' does not imply that debugging is wanted.
409 virtual bool GetDefaultStandaloneDebug() const { return false; }
410
411 // Return the default debugger "tuning."
412 virtual llvm::DebuggerKind getDefaultDebuggerTuning() const {
413 return llvm::DebuggerKind::GDB;
414 }
415
416 /// Does this toolchain supports given debug info option or not.
417 virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const {
418 return true;
419 }
420
421 /// GetExceptionModel - Return the tool chain exception model.
422 virtual llvm::ExceptionHandling
423 GetExceptionModel(const llvm::opt::ArgList &Args) const;
424
425 /// SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
426 virtual bool SupportsEmbeddedBitcode() const { return false; }
427
428 /// getThreadModel() - Which thread model does this target use?
429 virtual std::string getThreadModel() const { return "posix"; }
430
431 /// isThreadModelSupported() - Does this target support a thread model?
432 virtual bool isThreadModelSupported(const StringRef Model) const;
433
434 /// ComputeLLVMTriple - Return the LLVM target triple to use, after taking
435 /// command line arguments into account.
436 virtual std::string
437 ComputeLLVMTriple(const llvm::opt::ArgList &Args,
438 types::ID InputType = types::TY_INVALID) const;
439
440 /// ComputeEffectiveClangTriple - Return the Clang triple to use for this
441 /// target, which may take into account the command line arguments. For
442 /// example, on Darwin the -mmacosx-version-min= command line argument (which
443 /// sets the deployment target) determines the version in the triple passed to
444 /// Clang.
445 virtual std::string ComputeEffectiveClangTriple(
446 const llvm::opt::ArgList &Args,
447 types::ID InputType = types::TY_INVALID) const;
448
449 /// getDefaultObjCRuntime - Return the default Objective-C runtime
450 /// for this platform.
451 ///
452 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
453 virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const;
454
455 /// hasBlocksRuntime - Given that the user is compiling with
456 /// -fblocks, does this tool chain guarantee the existence of a
457 /// blocks runtime?
458 ///
459 /// FIXME: this really belongs on some sort of DeploymentTarget abstraction
460 virtual bool hasBlocksRuntime() const { return true; }
461
462 /// Add the clang cc1 arguments for system include paths.
463 ///
464 /// This routine is responsible for adding the necessary cc1 arguments to
465 /// include headers from standard system header directories.
466 virtual void
467 AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
468 llvm::opt::ArgStringList &CC1Args) const;
469
470 /// Add options that need to be passed to cc1 for this target.
471 virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
472 llvm::opt::ArgStringList &CC1Args,
473 Action::OffloadKind DeviceOffloadKind) const;
474
475 /// Add warning options that need to be passed to cc1 for this target.
476 virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const;
477
478 // GetRuntimeLibType - Determine the runtime library type to use with the
479 // given compilation arguments.
480 virtual RuntimeLibType
481 GetRuntimeLibType(const llvm::opt::ArgList &Args) const;
482
483 // GetCXXStdlibType - Determine the C++ standard library type to use with the
484 // given compilation arguments.
485 virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
486
487 /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
488 /// the include paths to use for the given C++ standard library type.
489 virtual void
490 AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs,
491 llvm::opt::ArgStringList &CC1Args) const;
492
493 /// Returns if the C++ standard library should be linked in.
494 /// Note that e.g. -lm should still be linked even if this returns false.
495 bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const;
496
497 /// AddCXXStdlibLibArgs - Add the system specific linker arguments to use
498 /// for the given C++ standard library type.
499 virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args,
500 llvm::opt::ArgStringList &CmdArgs) const;
501
502 /// AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
503 void AddFilePathLibArgs(const llvm::opt::ArgList &Args,
504 llvm::opt::ArgStringList &CmdArgs) const;
505
506 /// AddCCKextLibArgs - Add the system specific linker arguments to use
507 /// for kernel extensions (Darwin-specific).
508 virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args,
509 llvm::opt::ArgStringList &CmdArgs) const;
510
511 /// AddFastMathRuntimeIfAvailable - If a runtime library exists that sets
512 /// global flags for unsafe floating point math, add it and return true.
513 ///
514 /// This checks for presence of the -Ofast, -ffast-math or -funsafe-math flags.
515 virtual bool AddFastMathRuntimeIfAvailable(
516 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const;
517
518 /// addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass
519 /// a suitable profile runtime library to the linker.
520 virtual void addProfileRTLibs(const llvm::opt::ArgList &Args,
521 llvm::opt::ArgStringList &CmdArgs) const;
522
523 /// Add arguments to use system-specific CUDA includes.
524 virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs,
525 llvm::opt::ArgStringList &CC1Args) const;
526
527 /// Add arguments to use MCU GCC toolchain includes.
528 virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
529 llvm::opt::ArgStringList &CC1Args) const;
530
531 /// On Windows, returns the MSVC compatibility version.
532 virtual VersionTuple computeMSVCVersion(const Driver *D,
533 const llvm::opt::ArgList &Args) const;
534
535 /// Return sanitizers which are available in this toolchain.
536 virtual SanitizerMask getSupportedSanitizers() const;
537
538 /// Return sanitizers which are enabled by default.
539 virtual SanitizerMask getDefaultSanitizers() const { return 0; }
540};
541
542/// Set a ToolChain's effective triple. Reset it when the registration object
543/// is destroyed.
544class RegisterEffectiveTriple {
545 const ToolChain &TC;
546
547public:
548 RegisterEffectiveTriple(const ToolChain &TC, llvm::Triple T) : TC(TC) {
549 TC.setEffectiveTriple(std::move(T));
550 }
551
552 ~RegisterEffectiveTriple() { TC.setEffectiveTriple(llvm::Triple()); }
553};
554
555} // namespace driver
556
557} // namespace clang
558
559#endif // LLVM_CLANG_DRIVER_TOOLCHAIN_H
560

Warning: That file was not part of the compilation database. It may have many parsing errors.