1 //===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- 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 // This provides an abstract class for C++ code generation. Concrete subclasses
11 // of this implement code generation for specific C++ ABIs.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
16 #define LLVM_CLANG_LIB_CODEGEN_CGCXXABI_H
18 #include "CodeGenFunction.h"
19 #include "clang/Basic/LLVM.h"
29 class CXXConstructorDecl;
30 class CXXDestructorDecl;
37 class CodeGenFunction;
40 /// \brief Implements C++ ABI-specific code generation functions.
44 std::unique_ptr<MangleContext> MangleCtx;
46 CGCXXABI(CodeGenModule &CGM)
47 : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
50 ImplicitParamDecl *&getThisDecl(CodeGenFunction &CGF) {
51 return CGF.CXXABIThisDecl;
53 llvm::Value *&getThisValue(CodeGenFunction &CGF) {
54 return CGF.CXXABIThisValue;
57 /// Issue a diagnostic about unsupported features in the ABI.
58 void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
60 /// Get a null value for unsupported member pointers.
61 llvm::Constant *GetBogusMemberPointer(QualType T);
63 ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
64 return CGF.CXXStructorImplicitParamDecl;
66 llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
67 return CGF.CXXStructorImplicitParamValue;
70 /// Perform prolog initialization of the parameter variable suitable
71 /// for 'this' emitted by buildThisParam.
72 void EmitThisParam(CodeGenFunction &CGF);
74 ASTContext &getContext() const { return CGM.getContext(); }
76 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
77 virtual bool requiresArrayCookie(const CXXNewExpr *E);
83 /// Gets the mangle context.
84 MangleContext &getMangleContext() {
88 /// Returns true if the given constructor or destructor is one of the
89 /// kinds that the ABI says returns 'this' (only applies when called
90 /// non-virtually for destructors).
92 /// There currently is no way to indicate if a destructor returns 'this'
93 /// when called virtually, and code generation does not support the case.
94 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
96 virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
98 /// If the C++ ABI requires the given type be returned in a particular way,
99 /// this method sets RetAI and returns true.
100 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
102 /// Specify how one should pass an argument of a record type.
104 /// Pass it using the normal C aggregate rules for the ABI, potentially
105 /// introducing extra copies and passing some or all of it in registers.
108 /// Pass it on the stack using its defined layout. The argument must be
109 /// evaluated directly into the correct stack position in the arguments area,
110 /// and the call machinery must not move it or introduce extra copies.
113 /// Pass it as a pointer to temporary memory.
117 /// Returns true if C++ allows us to copy the memory of an object of type RD
118 /// when it is passed as an argument.
119 bool canCopyArgument(const CXXRecordDecl *RD) const;
121 /// Returns how an argument of the given record type should be passed.
122 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
124 /// Returns true if the implicit 'sret' parameter comes after the implicit
125 /// 'this' parameter of C++ instance methods.
126 virtual bool isSRetParameterAfterThis() const { return false; }
128 /// Find the LLVM type used to represent the given member pointer
131 ConvertMemberPointerType(const MemberPointerType *MPT);
133 /// Load a member function from an object and a member function
134 /// pointer. Apply the this-adjustment and set 'This' to the
136 virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
137 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
138 llvm::Value *MemPtr, const MemberPointerType *MPT);
140 /// Calculate an l-value from an object and a data member pointer.
141 virtual llvm::Value *
142 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
143 llvm::Value *Base, llvm::Value *MemPtr,
144 const MemberPointerType *MPT);
146 /// Perform a derived-to-base, base-to-derived, or bitcast member
147 /// pointer conversion.
148 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
152 /// Perform a derived-to-base, base-to-derived, or bitcast member
153 /// pointer conversion on a constant value.
154 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
155 llvm::Constant *Src);
157 /// Return true if the given member pointer can be zero-initialized
158 /// (in the C++ sense) with an LLVM zeroinitializer.
159 virtual bool isZeroInitializable(const MemberPointerType *MPT);
161 /// Return whether or not a member pointers type is convertible to an IR type.
162 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
166 virtual bool isTypeInfoCalculable(QualType Ty) const {
167 return !Ty->isIncompleteType();
170 /// Create a null member pointer of the given type.
171 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
173 /// Create a member pointer for the given method.
174 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
176 /// Create a member pointer for the given field.
177 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
180 /// Create a member pointer for the given member pointer constant.
181 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
183 /// Emit a comparison between two member pointers. Returns an i1.
184 virtual llvm::Value *
185 EmitMemberPointerComparison(CodeGenFunction &CGF,
188 const MemberPointerType *MPT,
191 /// Determine if a member pointer is non-null. Returns an i1.
192 virtual llvm::Value *
193 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
195 const MemberPointerType *MPT);
198 /// A utility method for computing the offset required for the given
199 /// base-to-derived or derived-to-base member-pointer conversion.
200 /// Does not handle virtual conversions (in case we ever fully
201 /// support an ABI that allows this). Returns null if no adjustment
203 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
205 /// \brief Computes the non-virtual adjustment needed for a member pointer
206 /// conversion along an inheritance path stored in an APValue. Unlike
207 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
208 /// is from a derived type to a base type.
209 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
212 virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
213 const CXXDeleteExpr *DE,
214 llvm::Value *Ptr, QualType ElementType,
215 const CXXDestructorDecl *Dtor) = 0;
216 virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
218 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
220 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
221 QualType SrcRecordTy) = 0;
222 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
223 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
224 llvm::Value *ThisPtr,
225 llvm::Type *StdTypeInfoPtrTy) = 0;
227 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
228 QualType SrcRecordTy) = 0;
230 virtual llvm::Value *
231 EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
232 QualType SrcRecordTy, QualType DestTy,
233 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
235 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
237 QualType SrcRecordTy,
238 QualType DestTy) = 0;
240 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
242 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
244 const CXXRecordDecl *ClassDecl,
245 const CXXRecordDecl *BaseClassDecl) = 0;
247 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
248 const CXXRecordDecl *RD);
250 /// Emit the code to initialize hidden members required
251 /// to handle virtual inheritance, if needed by the ABI.
253 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
254 const CXXRecordDecl *RD) {}
256 /// Emit constructor variants required by this ABI.
257 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
259 /// Build the signature of the given constructor or destructor variant by
260 /// adding any required parameters. For convenience, ArgTys has been
261 /// initialized with the type of 'this'.
262 virtual void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
263 SmallVectorImpl<CanQualType> &ArgTys) = 0;
265 /// Returns true if the given destructor type should be emitted as a linkonce
266 /// delegating thunk, regardless of whether the dtor is defined in this TU or
268 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
269 CXXDtorType DT) const = 0;
271 /// Emit destructor variants required by this ABI.
272 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
274 /// Get the type of the implicit "this" parameter used by a method. May return
275 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
276 /// parameter to point to some artificial offset in a complete object due to
277 /// vbases being reordered.
278 virtual const CXXRecordDecl *
279 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
280 return MD->getParent();
283 /// Perform ABI-specific "this" argument adjustment required prior to
284 /// a call of a virtual function.
285 /// The "VirtualCall" argument is true iff the call itself is virtual.
286 virtual llvm::Value *
287 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
293 /// Build a parameter variable suitable for 'this'.
294 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
296 /// Insert any ABI-specific implicit parameters into the parameter list for a
297 /// function. This generally involves extra data for constructors and
300 /// ABIs may also choose to override the return type, which has been
301 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
302 /// the formal return type of the function otherwise.
303 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
304 FunctionArgList &Params) = 0;
306 /// Perform ABI-specific "this" parameter adjustment in a virtual function
308 virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
309 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
313 /// Emit the ABI-specific prolog for the function.
314 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
316 /// Add any ABI-specific implicit arguments needed to call a constructor.
318 /// \return The number of args added to the call, which is typically zero or
321 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
322 CXXCtorType Type, bool ForVirtualBase,
323 bool Delegating, CallArgList &Args) = 0;
325 /// Emit the destructor call.
326 virtual void EmitDestructorCall(CodeGenFunction &CGF,
327 const CXXDestructorDecl *DD, CXXDtorType Type,
328 bool ForVirtualBase, bool Delegating,
329 llvm::Value *This) = 0;
331 /// Emits the VTable definitions required for the given record type.
332 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
333 const CXXRecordDecl *RD) = 0;
335 /// Get the address point of the vtable for the given base subobject while
336 /// building a constructor or a destructor. On return, NeedsVirtualOffset
337 /// tells if a virtual base adjustment is needed in order to get the offset
338 /// of the base subobject.
339 virtual llvm::Value *getVTableAddressPointInStructor(
340 CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
341 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
343 /// Get the address point of the vtable for the given base subobject while
344 /// building a constexpr.
345 virtual llvm::Constant *
346 getVTableAddressPointForConstExpr(BaseSubobject Base,
347 const CXXRecordDecl *VTableClass) = 0;
349 /// Get the address of the vtable for the given record decl which should be
350 /// used for the vptr at the given offset in RD.
351 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
352 CharUnits VPtrOffset) = 0;
354 /// Build a virtual function pointer in the ABI-specific way.
355 virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
360 /// Emit the ABI-specific virtual destructor call.
361 virtual llvm::Value *
362 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
363 CXXDtorType DtorType, llvm::Value *This,
364 const CXXMemberCallExpr *CE) = 0;
366 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
368 CallArgList &CallArgs) {}
370 /// Emit any tables needed to implement virtual inheritance. For Itanium,
371 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
373 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
375 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
376 GlobalDecl GD, bool ReturnAdjustment) = 0;
378 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
380 const ThisAdjustment &TA) = 0;
382 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
384 const ReturnAdjustment &RA) = 0;
386 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
387 RValue RV, QualType ResultType);
389 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
390 FunctionArgList &Args) const = 0;
392 /// Gets the pure virtual member call function.
393 virtual StringRef GetPureVirtualCallName() = 0;
395 /// Gets the deleted virtual member call name.
396 virtual StringRef GetDeletedVirtualCallName() = 0;
398 /**************************** Array cookies ******************************/
400 /// Returns the extra size required in order to store the array
401 /// cookie for the given new-expression. May return 0 to indicate that no
402 /// array cookie is required.
404 /// Several cases are filtered out before this method is called:
405 /// - non-array allocations never need a cookie
406 /// - calls to \::operator new(size_t, void*) never need a cookie
408 /// \param expr - the new-expression being allocated.
409 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
411 /// Initialize the array cookie for the given allocation.
413 /// \param NewPtr - a char* which is the presumed-non-null
414 /// return value of the allocation function
415 /// \param NumElements - the computed number of elements,
416 /// potentially collapsed from the multidimensional array case;
418 /// \param ElementType - the base element allocated type,
419 /// i.e. the allocated type after stripping all array types
420 virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
422 llvm::Value *NumElements,
423 const CXXNewExpr *expr,
424 QualType ElementType);
426 /// Reads the array cookie associated with the given pointer,
429 /// \param Ptr - a pointer to the first element in the array
430 /// \param ElementType - the base element type of elements of the array
431 /// \param NumElements - an out parameter which will be initialized
432 /// with the number of elements allocated, or zero if there is no
434 /// \param AllocPtr - an out parameter which will be initialized
435 /// with a char* pointing to the address returned by the allocation
437 /// \param CookieSize - an out parameter which will be initialized
438 /// with the size of the cookie, or zero if there is no cookie
439 virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
440 const CXXDeleteExpr *expr,
441 QualType ElementType, llvm::Value *&NumElements,
442 llvm::Value *&AllocPtr, CharUnits &CookieSize);
444 /// Return whether the given global decl needs a VTT parameter.
445 virtual bool NeedsVTTParameter(GlobalDecl GD);
448 /// Returns the extra size required in order to store the array
449 /// cookie for the given type. Assumes that an array cookie is
451 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
453 /// Reads the array cookie for an allocation which is known to have one.
454 /// This is called by the standard implementation of ReadArrayCookie.
456 /// \param ptr - a pointer to the allocation made for an array, as a char*
457 /// \param cookieSize - the computed cookie size of an array
459 /// Other parameters are as above.
462 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
464 CharUnits cookieSize);
468 /*************************** Static local guards ****************************/
470 /// Emits the guarded initializer and destructor setup for the given
471 /// variable, given that it couldn't be emitted as a constant.
472 /// If \p PerformInit is false, the initialization has been folded to a
473 /// constant and should not be performed.
475 /// The variable may be:
476 /// - a static local variable
477 /// - a static data member of a class template instantiation
478 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
479 llvm::GlobalVariable *DeclPtr,
480 bool PerformInit) = 0;
482 /// Emit code to force the execution of a destructor during global
483 /// teardown. The default implementation of this uses atexit.
485 /// \param Dtor - a function taking a single pointer argument
486 /// \param Addr - a pointer to pass to the destructor function.
487 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
488 llvm::Constant *Dtor,
489 llvm::Constant *Addr) = 0;
491 /*************************** thread_local initialization ********************/
493 /// Emits ABI-required functions necessary to initialize thread_local
494 /// variables in this translation unit.
496 /// \param CXXThreadLocals - The thread_local declarations in this translation
498 /// \param CXXThreadLocalInits - If this translation unit contains any
499 /// non-constant initialization or non-trivial destruction for
500 /// thread_local variables, a list of functions to perform the
502 virtual void EmitThreadLocalInitFuncs(
504 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
506 ArrayRef<llvm::Function *> CXXThreadLocalInits,
507 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) = 0;
509 // Determine if references to thread_local global variables can be made
510 // directly or require access through a thread wrapper function.
511 virtual bool usesThreadWrapperFunction() const = 0;
513 /// Emit a reference to a non-local thread_local variable (including
514 /// triggering the initialization of all thread_local variables in its
515 /// translation unit).
516 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
518 QualType LValType) = 0;
520 /// Emit a single constructor/destructor with the given type from a C++
521 /// constructor Decl.
522 virtual void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) = 0;
525 // Create an instance of a C++ ABI class:
527 /// Creates an Itanium-family ABI.
528 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
530 /// Creates a Microsoft-family ABI.
531 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);