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