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"
30 class CXXConstructorDecl;
31 class CXXDestructorDecl;
39 class CodeGenFunction;
43 /// \brief Implements C++ ABI-specific code generation functions.
47 std::unique_ptr<MangleContext> MangleCtx;
49 CGCXXABI(CodeGenModule &CGM)
50 : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
53 ImplicitParamDecl *getThisDecl(CodeGenFunction &CGF) {
54 return CGF.CXXABIThisDecl;
56 llvm::Value *getThisValue(CodeGenFunction &CGF) {
57 return CGF.CXXABIThisValue;
59 Address getThisAddress(CodeGenFunction &CGF) {
60 return Address(CGF.CXXABIThisValue, CGF.CXXABIThisAlignment);
63 /// Issue a diagnostic about unsupported features in the ABI.
64 void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
66 /// Get a null value for unsupported member pointers.
67 llvm::Constant *GetBogusMemberPointer(QualType T);
69 ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
70 return CGF.CXXStructorImplicitParamDecl;
72 llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
73 return CGF.CXXStructorImplicitParamValue;
76 /// Perform prolog initialization of the parameter variable suitable
77 /// for 'this' emitted by buildThisParam.
78 void EmitThisParam(CodeGenFunction &CGF);
80 ASTContext &getContext() const { return CGM.getContext(); }
82 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
83 virtual bool requiresArrayCookie(const CXXNewExpr *E);
85 /// Determine whether there's something special about the rules of
86 /// the ABI tell us that 'this' is a complete object within the
87 /// given function. Obvious common logic like being defined on a
88 /// final class will have been taken care of by the caller.
89 virtual bool isThisCompleteObject(GlobalDecl GD) const = 0;
95 /// Gets the mangle context.
96 MangleContext &getMangleContext() {
100 /// Returns true if the given constructor or destructor is one of the
101 /// kinds that the ABI says returns 'this' (only applies when called
102 /// non-virtually for destructors).
104 /// There currently is no way to indicate if a destructor returns 'this'
105 /// when called virtually, and code generation does not support the case.
106 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
108 virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
110 /// Returns true if the target allows calling a function through a pointer
111 /// with a different signature than the actual function (or equivalently,
112 /// bitcasting a function or function pointer to a different function type).
113 /// In principle in the most general case this could depend on the target, the
114 /// calling convention, and the actual types of the arguments and return
115 /// value. Here it just means whether the signature mismatch could *ever* be
116 /// allowed; in other words, does the target do strict checking of signatures
118 virtual bool canCallMismatchedFunctionType() const { return true; }
120 /// If the C++ ABI requires the given type be returned in a particular way,
121 /// this method sets RetAI and returns true.
122 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
124 /// Specify how one should pass an argument of a record type.
126 /// Pass it using the normal C aggregate rules for the ABI, potentially
127 /// introducing extra copies and passing some or all of it in registers.
130 /// Pass it on the stack using its defined layout. The argument must be
131 /// evaluated directly into the correct stack position in the arguments area,
132 /// and the call machinery must not move it or introduce extra copies.
135 /// Pass it as a pointer to temporary memory.
139 /// Returns true if C++ allows us to copy the memory of an object of type RD
140 /// when it is passed as an argument.
141 bool canCopyArgument(const CXXRecordDecl *RD) const;
143 /// Returns how an argument of the given record type should be passed.
144 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
146 /// Returns true if the implicit 'sret' parameter comes after the implicit
147 /// 'this' parameter of C++ instance methods.
148 virtual bool isSRetParameterAfterThis() const { return false; }
150 /// Find the LLVM type used to represent the given member pointer
153 ConvertMemberPointerType(const MemberPointerType *MPT);
155 /// Load a member function from an object and a member function
156 /// pointer. Apply the this-adjustment and set 'This' to the
158 virtual CGCallee EmitLoadOfMemberFunctionPointer(
159 CodeGenFunction &CGF, const Expr *E, Address This,
160 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
161 const MemberPointerType *MPT);
163 /// Calculate an l-value from an object and a data member pointer.
164 virtual llvm::Value *
165 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
166 Address Base, llvm::Value *MemPtr,
167 const MemberPointerType *MPT);
169 /// Perform a derived-to-base, base-to-derived, or bitcast member
170 /// pointer conversion.
171 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
175 /// Perform a derived-to-base, base-to-derived, or bitcast member
176 /// pointer conversion on a constant value.
177 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
178 llvm::Constant *Src);
180 /// Return true if the given member pointer can be zero-initialized
181 /// (in the C++ sense) with an LLVM zeroinitializer.
182 virtual bool isZeroInitializable(const MemberPointerType *MPT);
184 /// Return whether or not a member pointers type is convertible to an IR type.
185 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
189 /// Create a null member pointer of the given type.
190 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
192 /// Create a member pointer for the given method.
193 virtual llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD);
195 /// Create a member pointer for the given field.
196 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
199 /// Create a member pointer for the given member pointer constant.
200 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
202 /// Emit a comparison between two member pointers. Returns an i1.
203 virtual llvm::Value *
204 EmitMemberPointerComparison(CodeGenFunction &CGF,
207 const MemberPointerType *MPT,
210 /// Determine if a member pointer is non-null. Returns an i1.
211 virtual llvm::Value *
212 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
214 const MemberPointerType *MPT);
217 /// A utility method for computing the offset required for the given
218 /// base-to-derived or derived-to-base member-pointer conversion.
219 /// Does not handle virtual conversions (in case we ever fully
220 /// support an ABI that allows this). Returns null if no adjustment
222 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
224 /// \brief Computes the non-virtual adjustment needed for a member pointer
225 /// conversion along an inheritance path stored in an APValue. Unlike
226 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
227 /// is from a derived type to a base type.
228 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
231 virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
232 const CXXDeleteExpr *DE,
233 Address Ptr, QualType ElementType,
234 const CXXDestructorDecl *Dtor) = 0;
235 virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
236 virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) = 0;
237 virtual llvm::GlobalVariable *getThrowInfo(QualType T) { return nullptr; }
239 /// \brief Determine whether it's possible to emit a vtable for \p RD, even
240 /// though we do not know that the vtable has been marked as used by semantic
242 virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
244 virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) = 0;
246 virtual llvm::CallInst *
247 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
250 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
251 virtual CatchTypeInfo
252 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) = 0;
253 virtual CatchTypeInfo getCatchAllTypeInfo();
255 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
256 QualType SrcRecordTy) = 0;
257 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
258 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
260 llvm::Type *StdTypeInfoPtrTy) = 0;
262 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
263 QualType SrcRecordTy) = 0;
265 virtual llvm::Value *
266 EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
267 QualType SrcRecordTy, QualType DestTy,
268 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
270 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
272 QualType SrcRecordTy,
273 QualType DestTy) = 0;
275 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
277 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
279 const CXXRecordDecl *ClassDecl,
280 const CXXRecordDecl *BaseClassDecl) = 0;
282 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
283 const CXXRecordDecl *RD);
285 /// Emit the code to initialize hidden members required
286 /// to handle virtual inheritance, if needed by the ABI.
288 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
289 const CXXRecordDecl *RD) {}
291 /// Emit constructor variants required by this ABI.
292 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
294 /// Build the signature of the given constructor or destructor variant by
295 /// adding any required parameters. For convenience, ArgTys has been
296 /// initialized with the type of 'this'.
297 virtual void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
298 SmallVectorImpl<CanQualType> &ArgTys) = 0;
300 /// Returns true if the given destructor type should be emitted as a linkonce
301 /// delegating thunk, regardless of whether the dtor is defined in this TU or
303 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
304 CXXDtorType DT) const = 0;
306 /// Emit destructor variants required by this ABI.
307 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
309 /// Get the type of the implicit "this" parameter used by a method. May return
310 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
311 /// parameter to point to some artificial offset in a complete object due to
312 /// vbases being reordered.
313 virtual const CXXRecordDecl *
314 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
315 return MD->getParent();
318 /// Perform ABI-specific "this" argument adjustment required prior to
319 /// a call of a virtual function.
320 /// The "VirtualCall" argument is true iff the call itself is virtual.
322 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
323 Address This, bool VirtualCall) {
327 /// Build a parameter variable suitable for 'this'.
328 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
330 /// Insert any ABI-specific implicit parameters into the parameter list for a
331 /// function. This generally involves extra data for constructors and
334 /// ABIs may also choose to override the return type, which has been
335 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
336 /// the formal return type of the function otherwise.
337 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
338 FunctionArgList &Params) = 0;
340 /// Get the ABI-specific "this" parameter adjustment to apply in the prologue
341 /// of a virtual function.
342 virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
343 return CharUnits::Zero();
346 /// Perform ABI-specific "this" parameter adjustment in a virtual function
348 virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
349 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
353 /// Emit the ABI-specific prolog for the function.
354 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
356 /// Add any ABI-specific implicit arguments needed to call a constructor.
358 /// \return The number of args added to the call, which is typically zero or
361 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
362 CXXCtorType Type, bool ForVirtualBase,
363 bool Delegating, CallArgList &Args) = 0;
365 /// Emit the destructor call.
366 virtual void EmitDestructorCall(CodeGenFunction &CGF,
367 const CXXDestructorDecl *DD, CXXDtorType Type,
368 bool ForVirtualBase, bool Delegating,
371 /// Emits the VTable definitions required for the given record type.
372 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
373 const CXXRecordDecl *RD) = 0;
375 /// Checks if ABI requires extra virtual offset for vtable field.
377 isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
378 CodeGenFunction::VPtr Vptr) = 0;
380 /// Checks if ABI requires to initilize vptrs for given dynamic class.
381 virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) = 0;
383 /// Get the address point of the vtable for the given base subobject.
384 virtual llvm::Constant *
385 getVTableAddressPoint(BaseSubobject Base,
386 const CXXRecordDecl *VTableClass) = 0;
388 /// Get the address point of the vtable for the given base subobject while
389 /// building a constructor or a destructor.
390 virtual llvm::Value *
391 getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD,
393 const CXXRecordDecl *NearestVBase) = 0;
395 /// Get the address point of the vtable for the given base subobject while
396 /// building a constexpr.
397 virtual llvm::Constant *
398 getVTableAddressPointForConstExpr(BaseSubobject Base,
399 const CXXRecordDecl *VTableClass) = 0;
401 /// Get the address of the vtable for the given record decl which should be
402 /// used for the vptr at the given offset in RD.
403 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
404 CharUnits VPtrOffset) = 0;
406 /// Build a virtual function pointer in the ABI-specific way.
407 virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF,
411 SourceLocation Loc) = 0;
413 /// Emit the ABI-specific virtual destructor call.
414 virtual llvm::Value *
415 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
416 CXXDtorType DtorType, Address This,
417 const CXXMemberCallExpr *CE) = 0;
419 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
421 CallArgList &CallArgs) {}
423 /// Emit any tables needed to implement virtual inheritance. For Itanium,
424 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
426 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
428 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
429 GlobalDecl GD, bool ReturnAdjustment) = 0;
431 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
433 const ThisAdjustment &TA) = 0;
435 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
437 const ReturnAdjustment &RA) = 0;
439 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
440 RValue RV, QualType ResultType);
442 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
443 FunctionArgList &Args) const = 0;
445 /// Gets the offsets of all the virtual base pointers in a given class.
446 virtual std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD);
448 /// Gets the pure virtual member call function.
449 virtual StringRef GetPureVirtualCallName() = 0;
451 /// Gets the deleted virtual member call name.
452 virtual StringRef GetDeletedVirtualCallName() = 0;
454 /**************************** Array cookies ******************************/
456 /// Returns the extra size required in order to store the array
457 /// cookie for the given new-expression. May return 0 to indicate that no
458 /// array cookie is required.
460 /// Several cases are filtered out before this method is called:
461 /// - non-array allocations never need a cookie
462 /// - calls to \::operator new(size_t, void*) never need a cookie
464 /// \param expr - the new-expression being allocated.
465 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
467 /// Initialize the array cookie for the given allocation.
469 /// \param NewPtr - a char* which is the presumed-non-null
470 /// return value of the allocation function
471 /// \param NumElements - the computed number of elements,
472 /// potentially collapsed from the multidimensional array case;
474 /// \param ElementType - the base element allocated type,
475 /// i.e. the allocated type after stripping all array types
476 virtual Address InitializeArrayCookie(CodeGenFunction &CGF,
478 llvm::Value *NumElements,
479 const CXXNewExpr *expr,
480 QualType ElementType);
482 /// Reads the array cookie associated with the given pointer,
485 /// \param Ptr - a pointer to the first element in the array
486 /// \param ElementType - the base element type of elements of the array
487 /// \param NumElements - an out parameter which will be initialized
488 /// with the number of elements allocated, or zero if there is no
490 /// \param AllocPtr - an out parameter which will be initialized
491 /// with a char* pointing to the address returned by the allocation
493 /// \param CookieSize - an out parameter which will be initialized
494 /// with the size of the cookie, or zero if there is no cookie
495 virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr,
496 const CXXDeleteExpr *expr,
497 QualType ElementType, llvm::Value *&NumElements,
498 llvm::Value *&AllocPtr, CharUnits &CookieSize);
500 /// Return whether the given global decl needs a VTT parameter.
501 virtual bool NeedsVTTParameter(GlobalDecl GD);
504 /// Returns the extra size required in order to store the array
505 /// cookie for the given type. Assumes that an array cookie is
507 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
509 /// Reads the array cookie for an allocation which is known to have one.
510 /// This is called by the standard implementation of ReadArrayCookie.
512 /// \param ptr - a pointer to the allocation made for an array, as a char*
513 /// \param cookieSize - the computed cookie size of an array
515 /// Other parameters are as above.
518 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF, Address ptr,
519 CharUnits cookieSize);
523 /*************************** Static local guards ****************************/
525 /// Emits the guarded initializer and destructor setup for the given
526 /// variable, given that it couldn't be emitted as a constant.
527 /// If \p PerformInit is false, the initialization has been folded to a
528 /// constant and should not be performed.
530 /// The variable may be:
531 /// - a static local variable
532 /// - a static data member of a class template instantiation
533 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
534 llvm::GlobalVariable *DeclPtr,
535 bool PerformInit) = 0;
537 /// Emit code to force the execution of a destructor during global
538 /// teardown. The default implementation of this uses atexit.
540 /// \param Dtor - a function taking a single pointer argument
541 /// \param Addr - a pointer to pass to the destructor function.
542 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
543 llvm::Constant *Dtor,
544 llvm::Constant *Addr) = 0;
546 /*************************** thread_local initialization ********************/
548 /// Emits ABI-required functions necessary to initialize thread_local
549 /// variables in this translation unit.
551 /// \param CXXThreadLocals - The thread_local declarations in this translation
553 /// \param CXXThreadLocalInits - If this translation unit contains any
554 /// non-constant initialization or non-trivial destruction for
555 /// thread_local variables, a list of functions to perform the
557 virtual void EmitThreadLocalInitFuncs(
558 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
559 ArrayRef<llvm::Function *> CXXThreadLocalInits,
560 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) = 0;
562 // Determine if references to thread_local global variables can be made
563 // directly or require access through a thread wrapper function.
564 virtual bool usesThreadWrapperFunction() const = 0;
566 /// Emit a reference to a non-local thread_local variable (including
567 /// triggering the initialization of all thread_local variables in its
568 /// translation unit).
569 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
571 QualType LValType) = 0;
573 /// Emit a single constructor/destructor with the given type from a C++
574 /// constructor Decl.
575 virtual void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) = 0;
578 // Create an instance of a C++ ABI class:
580 /// Creates an Itanium-family ABI.
581 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
583 /// Creates a Microsoft-family ABI.
584 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);