1//===---- TargetInfo.h - Encapsulate target details -------------*- 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// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
15#define LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
16
17#include "CGBuilder.h"
18#include "CodeGenModule.h"
19#include "CGValue.h"
20#include "clang/AST/Type.h"
21#include "clang/Basic/LLVM.h"
22#include "clang/Basic/SyncScope.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/StringRef.h"
25
26namespace llvm {
27class Constant;
28class GlobalValue;
29class Type;
30class Value;
31}
32
33namespace clang {
34class Decl;
35
36namespace CodeGen {
37class ABIInfo;
38class CallArgList;
39class CodeGenFunction;
40class CGBlockInfo;
41class SwiftABIInfo;
42
43/// TargetCodeGenInfo - This class organizes various target-specific
44/// codegeneration issues, like target-specific attributes, builtins and so
45/// on.
46class TargetCodeGenInfo {
47 std::unique_ptr<ABIInfo> Info;
48
49protected:
50 // Target hooks supporting Swift calling conventions. The target must
51 // initialize this field if it claims to support these calling conventions
52 // by returning true from TargetInfo::checkCallingConvention for them.
53 std::unique_ptr<SwiftABIInfo> SwiftInfo;
54
55 // Returns ABI info helper for the target. This is for use by derived classes.
56 template <typename T> const T &getABIInfo() const {
57 return static_cast<const T &>(*Info);
58 }
59
60public:
61 TargetCodeGenInfo(std::unique_ptr<ABIInfo> Info);
62 virtual ~TargetCodeGenInfo();
63
64 /// getABIInfo() - Returns ABI info helper for the target.
65 const ABIInfo &getABIInfo() const { return *Info; }
66
67 /// Returns Swift ABI info helper for the target.
68 const SwiftABIInfo &getSwiftABIInfo() const {
69 assert(SwiftInfo && "Swift ABI info has not been initialized");
70 return *SwiftInfo;
71 }
72
73 /// setTargetAttributes - Provides a convenient hook to handle extra
74 /// target-specific attributes for the given global.
75 virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
76 CodeGen::CodeGenModule &M) const {}
77
78 /// emitTargetMetadata - Provides a convenient hook to handle extra
79 /// target-specific metadata for the given globals.
80 virtual void emitTargetMetadata(
81 CodeGen::CodeGenModule &CGM,
82 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {}
83
84 /// Any further codegen related checks that need to be done on a function call
85 /// in a target specific manner.
86 virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
87 const FunctionDecl *Caller,
88 const FunctionDecl *Callee,
89 const CallArgList &Args) const {}
90
91 /// Determines the size of struct _Unwind_Exception on this platform,
92 /// in 8-bit units. The Itanium ABI defines this as:
93 /// struct _Unwind_Exception {
94 /// uint64 exception_class;
95 /// _Unwind_Exception_Cleanup_Fn exception_cleanup;
96 /// uint64 private_1;
97 /// uint64 private_2;
98 /// };
99 virtual unsigned getSizeOfUnwindException() const;
100
101 /// Controls whether __builtin_extend_pointer should sign-extend
102 /// pointers to uint64_t or zero-extend them (the default). Has
103 /// no effect for targets:
104 /// - that have 64-bit pointers, or
105 /// - that cannot address through registers larger than pointers, or
106 /// - that implicitly ignore/truncate the top bits when addressing
107 /// through such registers.
108 virtual bool extendPointerWithSExt() const { return false; }
109
110 /// Determines the DWARF register number for the stack pointer, for
111 /// exception-handling purposes. Implements __builtin_dwarf_sp_column.
112 ///
113 /// Returns -1 if the operation is unsupported by this target.
114 virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
115 return -1;
116 }
117
118 /// Initializes the given DWARF EH register-size table, a char*.
119 /// Implements __builtin_init_dwarf_reg_size_table.
120 ///
121 /// Returns true if the operation is unsupported by this target.
122 virtual bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
123 llvm::Value *Address) const {
124 return true;
125 }
126
127 /// Performs the code-generation required to convert a return
128 /// address as stored by the system into the actual address of the
129 /// next instruction that will be executed.
130 ///
131 /// Used by __builtin_extract_return_addr().
132 virtual llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
133 llvm::Value *Address) const {
134 return Address;
135 }
136
137 /// Performs the code-generation required to convert the address
138 /// of an instruction into a return address suitable for storage
139 /// by the system in a return slot.
140 ///
141 /// Used by __builtin_frob_return_addr().
142 virtual llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
143 llvm::Value *Address) const {
144 return Address;
145 }
146
147 /// Performs a target specific test of a floating point value for things
148 /// like IsNaN, Infinity, ... Nullptr is returned if no implementation
149 /// exists.
150 virtual llvm::Value *
151 testFPKind(llvm::Value *V, unsigned BuiltinID, CGBuilderTy &Builder,
152 CodeGenModule &CGM) const {
153 assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
154 return nullptr;
155 }
156
157 /// Corrects the low-level LLVM type for a given constraint and "usual"
158 /// type.
159 ///
160 /// \returns A pointer to a new LLVM type, possibly the same as the original
161 /// on success; 0 on failure.
162 virtual llvm::Type *adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
163 StringRef Constraint,
164 llvm::Type *Ty) const {
165 return Ty;
166 }
167
168 /// Target hook to decide whether an inline asm operand can be passed
169 /// by value.
170 virtual bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
171 llvm::Type *Ty) const {
172 return false;
173 }
174
175 /// Adds constraints and types for result registers.
176 virtual void addReturnRegisterOutputs(
177 CodeGen::CodeGenFunction &CGF, CodeGen::LValue ReturnValue,
178 std::string &Constraints, std::vector<llvm::Type *> &ResultRegTypes,
179 std::vector<llvm::Type *> &ResultTruncRegTypes,
180 std::vector<CodeGen::LValue> &ResultRegDests, std::string &AsmString,
181 unsigned NumOutputs) const {}
182
183 /// doesReturnSlotInterfereWithArgs - Return true if the target uses an
184 /// argument slot for an 'sret' type.
185 virtual bool doesReturnSlotInterfereWithArgs() const { return true; }
186
187 /// Retrieve the address of a function to call immediately before
188 /// calling objc_retainAutoreleasedReturnValue. The
189 /// implementation of objc_autoreleaseReturnValue sniffs the
190 /// instruction stream following its return address to decide
191 /// whether it's a call to objc_retainAutoreleasedReturnValue.
192 /// This can be prohibitively expensive, depending on the
193 /// relocation model, and so on some targets it instead sniffs for
194 /// a particular instruction sequence. This functions returns
195 /// that instruction sequence in inline assembly, which will be
196 /// empty if none is required.
197 virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const {
198 return "";
199 }
200
201 /// Determine whether a call to objc_retainAutoreleasedReturnValue or
202 /// objc_unsafeClaimAutoreleasedReturnValue should be marked as 'notail'.
203 virtual bool markARCOptimizedReturnCallsAsNoTail() const { return false; }
204
205 /// Return a constant used by UBSan as a signature to identify functions
206 /// possessing type information, or 0 if the platform is unsupported.
207 /// This magic number is invalid instruction encoding in many targets.
208 virtual llvm::Constant *
209 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
210 return llvm::ConstantInt::get(CGM.Int32Ty, 0xc105cafe);
211 }
212
213 /// Determine whether a call to an unprototyped functions under
214 /// the given calling convention should use the variadic
215 /// convention or the non-variadic convention.
216 ///
217 /// There's a good reason to make a platform's variadic calling
218 /// convention be different from its non-variadic calling
219 /// convention: the non-variadic arguments can be passed in
220 /// registers (better for performance), and the variadic arguments
221 /// can be passed on the stack (also better for performance). If
222 /// this is done, however, unprototyped functions *must* use the
223 /// non-variadic convention, because C99 states that a call
224 /// through an unprototyped function type must succeed if the
225 /// function was defined with a non-variadic prototype with
226 /// compatible parameters. Therefore, splitting the conventions
227 /// makes it impossible to call a variadic function through an
228 /// unprototyped type. Since function prototypes came out in the
229 /// late 1970s, this is probably an acceptable trade-off.
230 /// Nonetheless, not all platforms are willing to make it, and in
231 /// particularly x86-64 bends over backwards to make the
232 /// conventions compatible.
233 ///
234 /// The default is false. This is correct whenever:
235 /// - the conventions are exactly the same, because it does not
236 /// matter and the resulting IR will be somewhat prettier in
237 /// certain cases; or
238 /// - the conventions are substantively different in how they pass
239 /// arguments, because in this case using the variadic convention
240 /// will lead to C99 violations.
241 ///
242 /// However, some platforms make the conventions identical except
243 /// for passing additional out-of-band information to a variadic
244 /// function: for example, x86-64 passes the number of SSE
245 /// arguments in %al. On these platforms, it is desirable to
246 /// call unprototyped functions using the variadic convention so
247 /// that unprototyped calls to varargs functions still succeed.
248 ///
249 /// Relatedly, platforms which pass the fixed arguments to this:
250 /// A foo(B, C, D);
251 /// differently than they would pass them to this:
252 /// A foo(B, C, D, ...);
253 /// may need to adjust the debugger-support code in Sema to do the
254 /// right thing when calling a function with no know signature.
255 virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args,
256 const FunctionNoProtoType *fnType) const;
257
258 /// Gets the linker options necessary to link a dependent library on this
259 /// platform.
260 virtual void getDependentLibraryOption(llvm::StringRef Lib,
261 llvm::SmallString<24> &Opt) const;
262
263 /// Gets the linker options necessary to detect object file mismatches on
264 /// this platform.
265 virtual void getDetectMismatchOption(llvm::StringRef Name,
266 llvm::StringRef Value,
267 llvm::SmallString<32> &Opt) const {}
268
269 /// Get LLVM calling convention for OpenCL kernel.
270 virtual unsigned getOpenCLKernelCallingConv() const;
271
272 /// Get target specific null pointer.
273 /// \param T is the LLVM type of the null pointer.
274 /// \param QT is the clang QualType of the null pointer.
275 /// \return ConstantPointerNull with the given type \p T.
276 /// Each target can override it to return its own desired constant value.
277 virtual llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
278 llvm::PointerType *T, QualType QT) const;
279
280 /// Get target favored AST address space of a global variable for languages
281 /// other than OpenCL and CUDA.
282 /// If \p D is nullptr, returns the default target favored address space
283 /// for global variable.
284 virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
285 const VarDecl *D) const;
286
287 /// Get the AST address space for alloca.
288 virtual LangAS getASTAllocaAddressSpace() const { return LangAS::Default; }
289
290 /// Perform address space cast of an expression of pointer type.
291 /// \param V is the LLVM value to be casted to another address space.
292 /// \param SrcAddr is the language address space of \p V.
293 /// \param DestAddr is the targeted language address space.
294 /// \param DestTy is the destination LLVM pointer type.
295 /// \param IsNonNull is the flag indicating \p V is known to be non null.
296 virtual llvm::Value *performAddrSpaceCast(CodeGen::CodeGenFunction &CGF,
297 llvm::Value *V, LangAS SrcAddr,
298 LangAS DestAddr, llvm::Type *DestTy,
299 bool IsNonNull = false) const;
300
301 /// Perform address space cast of a constant expression of pointer type.
302 /// \param V is the LLVM constant to be casted to another address space.
303 /// \param SrcAddr is the language address space of \p V.
304 /// \param DestAddr is the targeted language address space.
305 /// \param DestTy is the destination LLVM pointer type.
306 virtual llvm::Constant *performAddrSpaceCast(CodeGenModule &CGM,
307 llvm::Constant *V,
308 LangAS SrcAddr, LangAS DestAddr,
309 llvm::Type *DestTy) const;
310
311 /// Get address space of pointer parameter for __cxa_atexit.
312 virtual LangAS getAddrSpaceOfCxaAtexitPtrParam() const {
313 return LangAS::Default;
314 }
315
316 /// Get the syncscope used in LLVM IR.
317 virtual llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
318 SyncScope Scope,
319 llvm::AtomicOrdering Ordering,
320 llvm::LLVMContext &Ctx) const;
321
322 /// Interface class for filling custom fields of a block literal for OpenCL.
323 class TargetOpenCLBlockHelper {
324 public:
325 typedef std::pair<llvm::Value *, StringRef> ValueTy;
326 TargetOpenCLBlockHelper() {}
327 virtual ~TargetOpenCLBlockHelper() {}
328 /// Get the custom field types for OpenCL blocks.
329 virtual llvm::SmallVector<llvm::Type *, 1> getCustomFieldTypes() = 0;
330 /// Get the custom field values for OpenCL blocks.
331 virtual llvm::SmallVector<ValueTy, 1>
332 getCustomFieldValues(CodeGenFunction &CGF, const CGBlockInfo &Info) = 0;
333 virtual bool areAllCustomFieldValuesConstant(const CGBlockInfo &Info) = 0;
334 /// Get the custom field values for OpenCL blocks if all values are LLVM
335 /// constants.
336 virtual llvm::SmallVector<llvm::Constant *, 1>
337 getCustomFieldValues(CodeGenModule &CGM, const CGBlockInfo &Info) = 0;
338 };
339 virtual TargetOpenCLBlockHelper *getTargetOpenCLBlockHelper() const {
340 return nullptr;
341 }
342
343 /// Create an OpenCL kernel for an enqueued block. The kernel function is
344 /// a wrapper for the block invoke function with target-specific calling
345 /// convention and ABI as an OpenCL kernel. The wrapper function accepts
346 /// block context and block arguments in target-specific way and calls
347 /// the original block invoke function.
348 virtual llvm::Value *
349 createEnqueuedBlockKernel(CodeGenFunction &CGF,
350 llvm::Function *BlockInvokeFunc,
351 llvm::Type *BlockTy) const;
352
353 /// \return true if the target supports alias from the unmangled name to the
354 /// mangled name of functions declared within an extern "C" region and marked
355 /// as 'used', and having internal linkage.
356 virtual bool shouldEmitStaticExternCAliases() const { return true; }
357
358 /// \return true if annonymous zero-sized bitfields should be emitted to
359 /// correctly distinguish between struct types whose memory layout is the
360 /// same, but whose layout may differ when used as argument passed by value
361 virtual bool shouldEmitDWARFBitFieldSeparators() const { return false; }
362
363 virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const {}
364
365 /// Return the device-side type for the CUDA device builtin surface type.
366 virtual llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const {
367 // By default, no change from the original one.
368 return nullptr;
369 }
370 /// Return the device-side type for the CUDA device builtin texture type.
371 virtual llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const {
372 // By default, no change from the original one.
373 return nullptr;
374 }
375
376 /// Return the WebAssembly externref reference type.
377 virtual llvm::Type *getWasmExternrefReferenceType() const { return nullptr; }
378
379 /// Return the WebAssembly funcref reference type.
380 virtual llvm::Type *getWasmFuncrefReferenceType() const { return nullptr; }
381
382 /// Emit the device-side copy of the builtin surface type.
383 virtual bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF,
384 LValue Dst,
385 LValue Src) const {
386 // DO NOTHING by default.
387 return false;
388 }
389 /// Emit the device-side copy of the builtin texture type.
390 virtual bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF,
391 LValue Dst,
392 LValue Src) const {
393 // DO NOTHING by default.
394 return false;
395 }
396
397 /// Return an LLVM type that corresponds to an OpenCL type.
398 virtual llvm::Type *getOpenCLType(CodeGenModule &CGM, const Type *T) const {
399 return nullptr;
400 }
401
402protected:
403 static std::string qualifyWindowsLibrary(StringRef Lib);
404
405 void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
406 CodeGen::CodeGenModule &CGM) const;
407};
408
409std::unique_ptr<TargetCodeGenInfo>
410createDefaultTargetCodeGenInfo(CodeGenModule &CGM);
411
412enum class AArch64ABIKind {
413 AAPCS = 0,
414 DarwinPCS,
415 Win64,
416};
417
418std::unique_ptr<TargetCodeGenInfo>
419createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind);
420
421std::unique_ptr<TargetCodeGenInfo>
422createWindowsAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind K);
423
424std::unique_ptr<TargetCodeGenInfo>
425createAMDGPUTargetCodeGenInfo(CodeGenModule &CGM);
426
427std::unique_ptr<TargetCodeGenInfo>
428createARCTargetCodeGenInfo(CodeGenModule &CGM);
429
430enum class ARMABIKind {
431 APCS = 0,
432 AAPCS = 1,
433 AAPCS_VFP = 2,
434 AAPCS16_VFP = 3,
435};
436
437std::unique_ptr<TargetCodeGenInfo>
438createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind);
439
440std::unique_ptr<TargetCodeGenInfo>
441createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K);
442
443std::unique_ptr<TargetCodeGenInfo>
444createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR);
445
446std::unique_ptr<TargetCodeGenInfo>
447createBPFTargetCodeGenInfo(CodeGenModule &CGM);
448
449std::unique_ptr<TargetCodeGenInfo>
450createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen);
451
452std::unique_ptr<TargetCodeGenInfo>
453createHexagonTargetCodeGenInfo(CodeGenModule &CGM);
454
455std::unique_ptr<TargetCodeGenInfo>
456createLanaiTargetCodeGenInfo(CodeGenModule &CGM);
457
458std::unique_ptr<TargetCodeGenInfo>
459createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen,
460 unsigned FLen);
461
462std::unique_ptr<TargetCodeGenInfo>
463createM68kTargetCodeGenInfo(CodeGenModule &CGM);
464
465std::unique_ptr<TargetCodeGenInfo>
466createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32);
467
468std::unique_ptr<TargetCodeGenInfo>
469createMSP430TargetCodeGenInfo(CodeGenModule &CGM);
470
471std::unique_ptr<TargetCodeGenInfo>
472createNVPTXTargetCodeGenInfo(CodeGenModule &CGM);
473
474std::unique_ptr<TargetCodeGenInfo>
475createPNaClTargetCodeGenInfo(CodeGenModule &CGM);
476
477enum class PPC64_SVR4_ABIKind {
478 ELFv1 = 0,
479 ELFv2,
480};
481
482std::unique_ptr<TargetCodeGenInfo>
483createAIXTargetCodeGenInfo(CodeGenModule &CGM, bool Is64Bit);
484
485std::unique_ptr<TargetCodeGenInfo>
486createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI);
487
488std::unique_ptr<TargetCodeGenInfo>
489createPPC64TargetCodeGenInfo(CodeGenModule &CGM);
490
491std::unique_ptr<TargetCodeGenInfo>
492createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind,
493 bool SoftFloatABI);
494
495std::unique_ptr<TargetCodeGenInfo>
496createRISCVTargetCodeGenInfo(CodeGenModule &CGM, unsigned XLen, unsigned FLen);
497
498std::unique_ptr<TargetCodeGenInfo>
499createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM);
500
501std::unique_ptr<TargetCodeGenInfo>
502createSPIRVTargetCodeGenInfo(CodeGenModule &CGM);
503
504std::unique_ptr<TargetCodeGenInfo>
505createSparcV8TargetCodeGenInfo(CodeGenModule &CGM);
506
507std::unique_ptr<TargetCodeGenInfo>
508createSparcV9TargetCodeGenInfo(CodeGenModule &CGM);
509
510std::unique_ptr<TargetCodeGenInfo>
511createSystemZTargetCodeGenInfo(CodeGenModule &CGM, bool HasVector,
512 bool SoftFloatABI);
513
514std::unique_ptr<TargetCodeGenInfo>
515createTCETargetCodeGenInfo(CodeGenModule &CGM);
516
517std::unique_ptr<TargetCodeGenInfo>
518createVETargetCodeGenInfo(CodeGenModule &CGM);
519
520enum class WebAssemblyABIKind {
521 MVP = 0,
522 ExperimentalMV = 1,
523};
524
525std::unique_ptr<TargetCodeGenInfo>
526createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K);
527
528/// The AVX ABI level for X86 targets.
529enum class X86AVXABILevel {
530 None,
531 AVX,
532 AVX512,
533};
534
535std::unique_ptr<TargetCodeGenInfo> createX86_32TargetCodeGenInfo(
536 CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI,
537 unsigned NumRegisterParameters, bool SoftFloatABI);
538
539std::unique_ptr<TargetCodeGenInfo>
540createWinX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI,
541 bool Win32StructABI,
542 unsigned NumRegisterParameters);
543
544std::unique_ptr<TargetCodeGenInfo>
545createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel);
546
547std::unique_ptr<TargetCodeGenInfo>
548createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel);
549
550std::unique_ptr<TargetCodeGenInfo>
551createXCoreTargetCodeGenInfo(CodeGenModule &CGM);
552
553} // namespace CodeGen
554} // namespace clang
555
556#endif // LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
557