xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/TargetInfo.h (revision cab6a39d7b343596a5823e65c0f7b426551ec22d)
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 "CodeGenModule.h"
18 #include "CGValue.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/SyncScope.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringRef.h"
24 
25 namespace llvm {
26 class Constant;
27 class GlobalValue;
28 class Type;
29 class Value;
30 }
31 
32 namespace clang {
33 class Decl;
34 
35 namespace CodeGen {
36 class ABIInfo;
37 class CallArgList;
38 class CodeGenFunction;
39 class CGBlockInfo;
40 class CGFunctionInfo;
41 
42 /// TargetCodeGenInfo - This class organizes various target-specific
43 /// codegeneration issues, like target-specific attributes, builtins and so
44 /// on.
45 class TargetCodeGenInfo {
46   std::unique_ptr<ABIInfo> Info = nullptr;
47 
48 public:
49   TargetCodeGenInfo(std::unique_ptr<ABIInfo> Info) : Info(std::move(Info)) {}
50   virtual ~TargetCodeGenInfo();
51 
52   /// getABIInfo() - Returns ABI info helper for the target.
53   const ABIInfo &getABIInfo() const { return *Info; }
54 
55   /// setTargetAttributes - Provides a convenient hook to handle extra
56   /// target-specific attributes for the given global.
57   virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
58                                    CodeGen::CodeGenModule &M) const {}
59 
60   /// emitTargetMetadata - Provides a convenient hook to handle extra
61   /// target-specific metadata for the given globals.
62   virtual void emitTargetMetadata(
63       CodeGen::CodeGenModule &CGM,
64       const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {}
65 
66   /// Any further codegen related checks that need to be done on a function call
67   /// in a target specific manner.
68   virtual void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
69                                     const FunctionDecl *Caller,
70                                     const FunctionDecl *Callee,
71                                     const CallArgList &Args) const {}
72 
73   /// Determines the size of struct _Unwind_Exception on this platform,
74   /// in 8-bit units.  The Itanium ABI defines this as:
75   ///   struct _Unwind_Exception {
76   ///     uint64 exception_class;
77   ///     _Unwind_Exception_Cleanup_Fn exception_cleanup;
78   ///     uint64 private_1;
79   ///     uint64 private_2;
80   ///   };
81   virtual unsigned getSizeOfUnwindException() const;
82 
83   /// Controls whether __builtin_extend_pointer should sign-extend
84   /// pointers to uint64_t or zero-extend them (the default).  Has
85   /// no effect for targets:
86   ///   - that have 64-bit pointers, or
87   ///   - that cannot address through registers larger than pointers, or
88   ///   - that implicitly ignore/truncate the top bits when addressing
89   ///     through such registers.
90   virtual bool extendPointerWithSExt() const { return false; }
91 
92   /// Determines the DWARF register number for the stack pointer, for
93   /// exception-handling purposes.  Implements __builtin_dwarf_sp_column.
94   ///
95   /// Returns -1 if the operation is unsupported by this target.
96   virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
97     return -1;
98   }
99 
100   /// Initializes the given DWARF EH register-size table, a char*.
101   /// Implements __builtin_init_dwarf_reg_size_table.
102   ///
103   /// Returns true if the operation is unsupported by this target.
104   virtual bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
105                                        llvm::Value *Address) const {
106     return true;
107   }
108 
109   /// Performs the code-generation required to convert a return
110   /// address as stored by the system into the actual address of the
111   /// next instruction that will be executed.
112   ///
113   /// Used by __builtin_extract_return_addr().
114   virtual llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
115                                            llvm::Value *Address) const {
116     return Address;
117   }
118 
119   /// Performs the code-generation required to convert the address
120   /// of an instruction into a return address suitable for storage
121   /// by the system in a return slot.
122   ///
123   /// Used by __builtin_frob_return_addr().
124   virtual llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
125                                            llvm::Value *Address) const {
126     return Address;
127   }
128 
129   /// Corrects the low-level LLVM type for a given constraint and "usual"
130   /// type.
131   ///
132   /// \returns A pointer to a new LLVM type, possibly the same as the original
133   /// on success; 0 on failure.
134   virtual llvm::Type *adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
135                                           StringRef Constraint,
136                                           llvm::Type *Ty) const {
137     return Ty;
138   }
139 
140   /// Adds constraints and types for result registers.
141   virtual void addReturnRegisterOutputs(
142       CodeGen::CodeGenFunction &CGF, CodeGen::LValue ReturnValue,
143       std::string &Constraints, std::vector<llvm::Type *> &ResultRegTypes,
144       std::vector<llvm::Type *> &ResultTruncRegTypes,
145       std::vector<CodeGen::LValue> &ResultRegDests, std::string &AsmString,
146       unsigned NumOutputs) const {}
147 
148   /// doesReturnSlotInterfereWithArgs - Return true if the target uses an
149   /// argument slot for an 'sret' type.
150   virtual bool doesReturnSlotInterfereWithArgs() const { return true; }
151 
152   /// Retrieve the address of a function to call immediately before
153   /// calling objc_retainAutoreleasedReturnValue.  The
154   /// implementation of objc_autoreleaseReturnValue sniffs the
155   /// instruction stream following its return address to decide
156   /// whether it's a call to objc_retainAutoreleasedReturnValue.
157   /// This can be prohibitively expensive, depending on the
158   /// relocation model, and so on some targets it instead sniffs for
159   /// a particular instruction sequence.  This functions returns
160   /// that instruction sequence in inline assembly, which will be
161   /// empty if none is required.
162   virtual StringRef getARCRetainAutoreleasedReturnValueMarker() const {
163     return "";
164   }
165 
166   /// Determine whether a call to objc_retainAutoreleasedReturnValue or
167   /// objc_unsafeClaimAutoreleasedReturnValue should be marked as 'notail'.
168   virtual bool markARCOptimizedReturnCallsAsNoTail() const { return false; }
169 
170   /// Return a constant used by UBSan as a signature to identify functions
171   /// possessing type information, or 0 if the platform is unsupported.
172   virtual llvm::Constant *
173   getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
174     return nullptr;
175   }
176 
177   /// Determine whether a call to an unprototyped functions under
178   /// the given calling convention should use the variadic
179   /// convention or the non-variadic convention.
180   ///
181   /// There's a good reason to make a platform's variadic calling
182   /// convention be different from its non-variadic calling
183   /// convention: the non-variadic arguments can be passed in
184   /// registers (better for performance), and the variadic arguments
185   /// can be passed on the stack (also better for performance).  If
186   /// this is done, however, unprototyped functions *must* use the
187   /// non-variadic convention, because C99 states that a call
188   /// through an unprototyped function type must succeed if the
189   /// function was defined with a non-variadic prototype with
190   /// compatible parameters.  Therefore, splitting the conventions
191   /// makes it impossible to call a variadic function through an
192   /// unprototyped type.  Since function prototypes came out in the
193   /// late 1970s, this is probably an acceptable trade-off.
194   /// Nonetheless, not all platforms are willing to make it, and in
195   /// particularly x86-64 bends over backwards to make the
196   /// conventions compatible.
197   ///
198   /// The default is false.  This is correct whenever:
199   ///   - the conventions are exactly the same, because it does not
200   ///     matter and the resulting IR will be somewhat prettier in
201   ///     certain cases; or
202   ///   - the conventions are substantively different in how they pass
203   ///     arguments, because in this case using the variadic convention
204   ///     will lead to C99 violations.
205   ///
206   /// However, some platforms make the conventions identical except
207   /// for passing additional out-of-band information to a variadic
208   /// function: for example, x86-64 passes the number of SSE
209   /// arguments in %al.  On these platforms, it is desirable to
210   /// call unprototyped functions using the variadic convention so
211   /// that unprototyped calls to varargs functions still succeed.
212   ///
213   /// Relatedly, platforms which pass the fixed arguments to this:
214   ///   A foo(B, C, D);
215   /// differently than they would pass them to this:
216   ///   A foo(B, C, D, ...);
217   /// may need to adjust the debugger-support code in Sema to do the
218   /// right thing when calling a function with no know signature.
219   virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args,
220                                      const FunctionNoProtoType *fnType) const;
221 
222   /// Gets the linker options necessary to link a dependent library on this
223   /// platform.
224   virtual void getDependentLibraryOption(llvm::StringRef Lib,
225                                          llvm::SmallString<24> &Opt) const;
226 
227   /// Gets the linker options necessary to detect object file mismatches on
228   /// this platform.
229   virtual void getDetectMismatchOption(llvm::StringRef Name,
230                                        llvm::StringRef Value,
231                                        llvm::SmallString<32> &Opt) const {}
232 
233   /// Get LLVM calling convention for OpenCL kernel.
234   virtual unsigned getOpenCLKernelCallingConv() const;
235 
236   /// Get target specific null pointer.
237   /// \param T is the LLVM type of the null pointer.
238   /// \param QT is the clang QualType of the null pointer.
239   /// \return ConstantPointerNull with the given type \p T.
240   /// Each target can override it to return its own desired constant value.
241   virtual llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
242       llvm::PointerType *T, QualType QT) const;
243 
244   /// Get target favored AST address space of a global variable for languages
245   /// other than OpenCL and CUDA.
246   /// If \p D is nullptr, returns the default target favored address space
247   /// for global variable.
248   virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
249                                           const VarDecl *D) const;
250 
251   /// Get the AST address space for alloca.
252   virtual LangAS getASTAllocaAddressSpace() const { return LangAS::Default; }
253 
254   /// Perform address space cast of an expression of pointer type.
255   /// \param V is the LLVM value to be casted to another address space.
256   /// \param SrcAddr is the language address space of \p V.
257   /// \param DestAddr is the targeted language address space.
258   /// \param DestTy is the destination LLVM pointer type.
259   /// \param IsNonNull is the flag indicating \p V is known to be non null.
260   virtual llvm::Value *performAddrSpaceCast(CodeGen::CodeGenFunction &CGF,
261                                             llvm::Value *V, LangAS SrcAddr,
262                                             LangAS DestAddr, llvm::Type *DestTy,
263                                             bool IsNonNull = false) const;
264 
265   /// Perform address space cast of a constant expression of pointer type.
266   /// \param V is the LLVM constant to be casted to another address space.
267   /// \param SrcAddr is the language address space of \p V.
268   /// \param DestAddr is the targeted language address space.
269   /// \param DestTy is the destination LLVM pointer type.
270   virtual llvm::Constant *performAddrSpaceCast(CodeGenModule &CGM,
271                                                llvm::Constant *V,
272                                                LangAS SrcAddr, LangAS DestAddr,
273                                                llvm::Type *DestTy) const;
274 
275   /// Get address space of pointer parameter for __cxa_atexit.
276   virtual LangAS getAddrSpaceOfCxaAtexitPtrParam() const {
277     return LangAS::Default;
278   }
279 
280   /// Get the syncscope used in LLVM IR.
281   virtual llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
282                                                  SyncScope Scope,
283                                                  llvm::AtomicOrdering Ordering,
284                                                  llvm::LLVMContext &Ctx) const;
285 
286   /// Interface class for filling custom fields of a block literal for OpenCL.
287   class TargetOpenCLBlockHelper {
288   public:
289     typedef std::pair<llvm::Value *, StringRef> ValueTy;
290     TargetOpenCLBlockHelper() {}
291     virtual ~TargetOpenCLBlockHelper() {}
292     /// Get the custom field types for OpenCL blocks.
293     virtual llvm::SmallVector<llvm::Type *, 1> getCustomFieldTypes() = 0;
294     /// Get the custom field values for OpenCL blocks.
295     virtual llvm::SmallVector<ValueTy, 1>
296     getCustomFieldValues(CodeGenFunction &CGF, const CGBlockInfo &Info) = 0;
297     virtual bool areAllCustomFieldValuesConstant(const CGBlockInfo &Info) = 0;
298     /// Get the custom field values for OpenCL blocks if all values are LLVM
299     /// constants.
300     virtual llvm::SmallVector<llvm::Constant *, 1>
301     getCustomFieldValues(CodeGenModule &CGM, const CGBlockInfo &Info) = 0;
302   };
303   virtual TargetOpenCLBlockHelper *getTargetOpenCLBlockHelper() const {
304     return nullptr;
305   }
306 
307   /// Create an OpenCL kernel for an enqueued block. The kernel function is
308   /// a wrapper for the block invoke function with target-specific calling
309   /// convention and ABI as an OpenCL kernel. The wrapper function accepts
310   /// block context and block arguments in target-specific way and calls
311   /// the original block invoke function.
312   virtual llvm::Function *
313   createEnqueuedBlockKernel(CodeGenFunction &CGF,
314                             llvm::Function *BlockInvokeFunc,
315                             llvm::Value *BlockLiteral) const;
316 
317   /// \return true if the target supports alias from the unmangled name to the
318   /// mangled name of functions declared within an extern "C" region and marked
319   /// as 'used', and having internal linkage.
320   virtual bool shouldEmitStaticExternCAliases() const { return true; }
321 
322   virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const {}
323 
324   /// Return the device-side type for the CUDA device builtin surface type.
325   virtual llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const {
326     // By default, no change from the original one.
327     return nullptr;
328   }
329   /// Return the device-side type for the CUDA device builtin texture type.
330   virtual llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const {
331     // By default, no change from the original one.
332     return nullptr;
333   }
334 
335   /// Emit the device-side copy of the builtin surface type.
336   virtual bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF,
337                                                       LValue Dst,
338                                                       LValue Src) const {
339     // DO NOTHING by default.
340     return false;
341   }
342   /// Emit the device-side copy of the builtin texture type.
343   virtual bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF,
344                                                       LValue Dst,
345                                                       LValue Src) const {
346     // DO NOTHING by default.
347     return false;
348   }
349 };
350 
351 } // namespace CodeGen
352 } // namespace clang
353 
354 #endif // LLVM_CLANG_LIB_CODEGEN_TARGETINFO_H
355