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 /// 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 /// Loads the incoming C++ this pointer as it was passed by the caller.
77 llvm::Value *loadIncomingCXXThis(CodeGenFunction &CGF);
79 void setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr);
81 ASTContext &getContext() const { return CGM.getContext(); }
83 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
84 virtual bool requiresArrayCookie(const CXXNewExpr *E);
86 /// Determine whether there's something special about the rules of
87 /// the ABI tell us that 'this' is a complete object within the
88 /// given function. Obvious common logic like being defined on a
89 /// final class will have been taken care of by the caller.
90 virtual bool isThisCompleteObject(GlobalDecl GD) const = 0;
96 /// Gets the mangle context.
97 MangleContext &getMangleContext() {
101 /// Returns true if the given constructor or destructor is one of the
102 /// kinds that the ABI says returns 'this' (only applies when called
103 /// non-virtually for destructors).
105 /// There currently is no way to indicate if a destructor returns 'this'
106 /// when called virtually, and code generation does not support the case.
107 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
109 virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
111 /// Returns true if the target allows calling a function through a pointer
112 /// with a different signature than the actual function (or equivalently,
113 /// bitcasting a function or function pointer to a different function type).
114 /// In principle in the most general case this could depend on the target, the
115 /// calling convention, and the actual types of the arguments and return
116 /// value. Here it just means whether the signature mismatch could *ever* be
117 /// allowed; in other words, does the target do strict checking of signatures
119 virtual bool canCallMismatchedFunctionType() const { return true; }
121 /// If the C++ ABI requires the given type be returned in a particular way,
122 /// this method sets RetAI and returns true.
123 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
125 /// Specify how one should pass an argument of a record type.
127 /// Pass it using the normal C aggregate rules for the ABI, potentially
128 /// introducing extra copies and passing some or all of it in registers.
131 /// Pass it on the stack using its defined layout. The argument must be
132 /// evaluated directly into the correct stack position in the arguments area,
133 /// and the call machinery must not move it or introduce extra copies.
136 /// Pass it as a pointer to temporary memory.
140 /// Returns true if C++ allows us to copy the memory of an object of type RD
141 /// when it is passed as an argument.
142 bool canCopyArgument(const CXXRecordDecl *RD) const;
144 /// Returns how an argument of the given record type should be passed.
145 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
147 /// Returns true if the implicit 'sret' parameter comes after the implicit
148 /// 'this' parameter of C++ instance methods.
149 virtual bool isSRetParameterAfterThis() const { return false; }
151 /// Find the LLVM type used to represent the given member pointer
154 ConvertMemberPointerType(const MemberPointerType *MPT);
156 /// Load a member function from an object and a member function
157 /// pointer. Apply the this-adjustment and set 'This' to the
159 virtual CGCallee EmitLoadOfMemberFunctionPointer(
160 CodeGenFunction &CGF, const Expr *E, Address This,
161 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
162 const MemberPointerType *MPT);
164 /// Calculate an l-value from an object and a data member pointer.
165 virtual llvm::Value *
166 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
167 Address Base, llvm::Value *MemPtr,
168 const MemberPointerType *MPT);
170 /// Perform a derived-to-base, base-to-derived, or bitcast member
171 /// pointer conversion.
172 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
176 /// Perform a derived-to-base, base-to-derived, or bitcast member
177 /// pointer conversion on a constant value.
178 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
179 llvm::Constant *Src);
181 /// Return true if the given member pointer can be zero-initialized
182 /// (in the C++ sense) with an LLVM zeroinitializer.
183 virtual bool isZeroInitializable(const MemberPointerType *MPT);
185 /// Return whether or not a member pointers type is convertible to an IR type.
186 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
190 /// Create a null member pointer of the given type.
191 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
193 /// Create a member pointer for the given method.
194 virtual llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD);
196 /// Create a member pointer for the given field.
197 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
200 /// Create a member pointer for the given member pointer constant.
201 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
203 /// Emit a comparison between two member pointers. Returns an i1.
204 virtual llvm::Value *
205 EmitMemberPointerComparison(CodeGenFunction &CGF,
208 const MemberPointerType *MPT,
211 /// Determine if a member pointer is non-null. Returns an i1.
212 virtual llvm::Value *
213 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
215 const MemberPointerType *MPT);
218 /// A utility method for computing the offset required for the given
219 /// base-to-derived or derived-to-base member-pointer conversion.
220 /// Does not handle virtual conversions (in case we ever fully
221 /// support an ABI that allows this). Returns null if no adjustment
223 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
225 /// Computes the non-virtual adjustment needed for a member pointer
226 /// conversion along an inheritance path stored in an APValue. Unlike
227 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
228 /// is from a derived type to a base type.
229 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
232 virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
233 const CXXDeleteExpr *DE,
234 Address Ptr, QualType ElementType,
235 const CXXDestructorDecl *Dtor) = 0;
236 virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
237 virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) = 0;
238 virtual llvm::GlobalVariable *getThrowInfo(QualType T) { return nullptr; }
240 /// Determine whether it's possible to emit a vtable for \p RD, even
241 /// though we do not know that the vtable has been marked as used by semantic
243 virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
245 virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) = 0;
247 virtual llvm::CallInst *
248 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
251 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
252 virtual CatchTypeInfo
253 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) = 0;
254 virtual CatchTypeInfo getCatchAllTypeInfo();
256 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
257 QualType SrcRecordTy) = 0;
258 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
259 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
261 llvm::Type *StdTypeInfoPtrTy) = 0;
263 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
264 QualType SrcRecordTy) = 0;
266 virtual llvm::Value *
267 EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
268 QualType SrcRecordTy, QualType DestTy,
269 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
271 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
273 QualType SrcRecordTy,
274 QualType DestTy) = 0;
276 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
278 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
280 const CXXRecordDecl *ClassDecl,
281 const CXXRecordDecl *BaseClassDecl) = 0;
283 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
284 const CXXRecordDecl *RD);
286 /// Emit the code to initialize hidden members required
287 /// to handle virtual inheritance, if needed by the ABI.
289 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
290 const CXXRecordDecl *RD) {}
292 /// Emit constructor variants required by this ABI.
293 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
295 /// Notes how many arguments were added to the beginning (Prefix) and ending
296 /// (Suffix) of an arg list.
298 /// Note that Prefix actually refers to the number of args *after* the first
299 /// one: `this` arguments always come first.
300 struct AddedStructorArgs {
303 AddedStructorArgs() = default;
304 AddedStructorArgs(unsigned P, unsigned S) : Prefix(P), Suffix(S) {}
305 static AddedStructorArgs prefix(unsigned N) { return {N, 0}; }
306 static AddedStructorArgs suffix(unsigned N) { return {0, N}; }
309 /// Build the signature of the given constructor or destructor variant by
310 /// adding any required parameters. For convenience, ArgTys has been
311 /// initialized with the type of 'this'.
312 virtual AddedStructorArgs
313 buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
314 SmallVectorImpl<CanQualType> &ArgTys) = 0;
316 /// Returns true if the given destructor type should be emitted as a linkonce
317 /// delegating thunk, regardless of whether the dtor is defined in this TU or
319 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
320 CXXDtorType DT) const = 0;
322 virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
323 const CXXDestructorDecl *Dtor,
324 CXXDtorType DT) const;
326 virtual llvm::GlobalValue::LinkageTypes
327 getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
328 CXXDtorType DT) const;
330 /// Emit destructor variants required by this ABI.
331 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
333 /// Get the type of the implicit "this" parameter used by a method. May return
334 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
335 /// parameter to point to some artificial offset in a complete object due to
336 /// vbases being reordered.
337 virtual const CXXRecordDecl *
338 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
339 return MD->getParent();
342 /// Perform ABI-specific "this" argument adjustment required prior to
343 /// a call of a virtual function.
344 /// The "VirtualCall" argument is true iff the call itself is virtual.
346 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
347 Address This, bool VirtualCall) {
351 /// Build a parameter variable suitable for 'this'.
352 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
354 /// Insert any ABI-specific implicit parameters into the parameter list for a
355 /// function. This generally involves extra data for constructors and
358 /// ABIs may also choose to override the return type, which has been
359 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
360 /// the formal return type of the function otherwise.
361 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
362 FunctionArgList &Params) = 0;
364 /// Get the ABI-specific "this" parameter adjustment to apply in the prologue
365 /// of a virtual function.
366 virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
367 return CharUnits::Zero();
370 /// Emit the ABI-specific prolog for the function.
371 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
373 /// Add any ABI-specific implicit arguments needed to call a constructor.
375 /// \return The number of arguments added at the beginning and end of the
376 /// call, which is typically zero or one.
377 virtual AddedStructorArgs
378 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
379 CXXCtorType Type, bool ForVirtualBase,
380 bool Delegating, CallArgList &Args) = 0;
382 /// Emit the destructor call.
383 virtual void EmitDestructorCall(CodeGenFunction &CGF,
384 const CXXDestructorDecl *DD, CXXDtorType Type,
385 bool ForVirtualBase, bool Delegating,
388 /// Emits the VTable definitions required for the given record type.
389 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
390 const CXXRecordDecl *RD) = 0;
392 /// Checks if ABI requires extra virtual offset for vtable field.
394 isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
395 CodeGenFunction::VPtr Vptr) = 0;
397 /// Checks if ABI requires to initialize vptrs for given dynamic class.
398 virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) = 0;
400 /// Get the address point of the vtable for the given base subobject.
401 virtual llvm::Constant *
402 getVTableAddressPoint(BaseSubobject Base,
403 const CXXRecordDecl *VTableClass) = 0;
405 /// Get the address point of the vtable for the given base subobject while
406 /// building a constructor or a destructor.
407 virtual llvm::Value *
408 getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD,
410 const CXXRecordDecl *NearestVBase) = 0;
412 /// Get the address point of the vtable for the given base subobject while
413 /// building a constexpr.
414 virtual llvm::Constant *
415 getVTableAddressPointForConstExpr(BaseSubobject Base,
416 const CXXRecordDecl *VTableClass) = 0;
418 /// Get the address of the vtable for the given record decl which should be
419 /// used for the vptr at the given offset in RD.
420 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
421 CharUnits VPtrOffset) = 0;
423 /// Build a virtual function pointer in the ABI-specific way.
424 virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF,
425 GlobalDecl GD, Address This,
427 SourceLocation Loc) = 0;
429 /// Emit the ABI-specific virtual destructor call.
430 virtual llvm::Value *
431 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
432 CXXDtorType DtorType, Address This,
433 const CXXMemberCallExpr *CE) = 0;
435 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
437 CallArgList &CallArgs) {}
439 /// Emit any tables needed to implement virtual inheritance. For Itanium,
440 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
442 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
444 virtual bool exportThunk() = 0;
445 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
446 GlobalDecl GD, bool ReturnAdjustment) = 0;
448 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
450 const ThisAdjustment &TA) = 0;
452 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
454 const ReturnAdjustment &RA) = 0;
456 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
457 RValue RV, QualType ResultType);
459 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
460 FunctionArgList &Args) const = 0;
462 /// Gets the offsets of all the virtual base pointers in a given class.
463 virtual std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD);
465 /// Gets the pure virtual member call function.
466 virtual StringRef GetPureVirtualCallName() = 0;
468 /// Gets the deleted virtual member call name.
469 virtual StringRef GetDeletedVirtualCallName() = 0;
471 /**************************** Array cookies ******************************/
473 /// Returns the extra size required in order to store the array
474 /// cookie for the given new-expression. May return 0 to indicate that no
475 /// array cookie is required.
477 /// Several cases are filtered out before this method is called:
478 /// - non-array allocations never need a cookie
479 /// - calls to \::operator new(size_t, void*) never need a cookie
481 /// \param expr - the new-expression being allocated.
482 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
484 /// Initialize the array cookie for the given allocation.
486 /// \param NewPtr - a char* which is the presumed-non-null
487 /// return value of the allocation function
488 /// \param NumElements - the computed number of elements,
489 /// potentially collapsed from the multidimensional array case;
491 /// \param ElementType - the base element allocated type,
492 /// i.e. the allocated type after stripping all array types
493 virtual Address InitializeArrayCookie(CodeGenFunction &CGF,
495 llvm::Value *NumElements,
496 const CXXNewExpr *expr,
497 QualType ElementType);
499 /// Reads the array cookie associated with the given pointer,
502 /// \param Ptr - a pointer to the first element in the array
503 /// \param ElementType - the base element type of elements of the array
504 /// \param NumElements - an out parameter which will be initialized
505 /// with the number of elements allocated, or zero if there is no
507 /// \param AllocPtr - an out parameter which will be initialized
508 /// with a char* pointing to the address returned by the allocation
510 /// \param CookieSize - an out parameter which will be initialized
511 /// with the size of the cookie, or zero if there is no cookie
512 virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr,
513 const CXXDeleteExpr *expr,
514 QualType ElementType, llvm::Value *&NumElements,
515 llvm::Value *&AllocPtr, CharUnits &CookieSize);
517 /// Return whether the given global decl needs a VTT parameter.
518 virtual bool NeedsVTTParameter(GlobalDecl GD);
521 /// Returns the extra size required in order to store the array
522 /// cookie for the given type. Assumes that an array cookie is
524 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
526 /// Reads the array cookie for an allocation which is known to have one.
527 /// This is called by the standard implementation of ReadArrayCookie.
529 /// \param ptr - a pointer to the allocation made for an array, as a char*
530 /// \param cookieSize - the computed cookie size of an array
532 /// Other parameters are as above.
535 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF, Address ptr,
536 CharUnits cookieSize);
540 /*************************** Static local guards ****************************/
542 /// Emits the guarded initializer and destructor setup for the given
543 /// variable, given that it couldn't be emitted as a constant.
544 /// If \p PerformInit is false, the initialization has been folded to a
545 /// constant and should not be performed.
547 /// The variable may be:
548 /// - a static local variable
549 /// - a static data member of a class template instantiation
550 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
551 llvm::GlobalVariable *DeclPtr,
552 bool PerformInit) = 0;
554 /// Emit code to force the execution of a destructor during global
555 /// teardown. The default implementation of this uses atexit.
557 /// \param Dtor - a function taking a single pointer argument
558 /// \param Addr - a pointer to pass to the destructor function.
559 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
560 llvm::Constant *Dtor,
561 llvm::Constant *Addr) = 0;
563 /*************************** thread_local initialization ********************/
565 /// Emits ABI-required functions necessary to initialize thread_local
566 /// variables in this translation unit.
568 /// \param CXXThreadLocals - The thread_local declarations in this translation
570 /// \param CXXThreadLocalInits - If this translation unit contains any
571 /// non-constant initialization or non-trivial destruction for
572 /// thread_local variables, a list of functions to perform the
574 virtual void EmitThreadLocalInitFuncs(
575 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
576 ArrayRef<llvm::Function *> CXXThreadLocalInits,
577 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) = 0;
579 // Determine if references to thread_local global variables can be made
580 // directly or require access through a thread wrapper function.
581 virtual bool usesThreadWrapperFunction() const = 0;
583 /// Emit a reference to a non-local thread_local variable (including
584 /// triggering the initialization of all thread_local variables in its
585 /// translation unit).
586 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
588 QualType LValType) = 0;
590 /// Emit a single constructor/destructor with the given type from a C++
591 /// constructor Decl.
592 virtual void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) = 0;
594 /// Load a vtable from This, an object of polymorphic type RD, or from one of
595 /// its virtual bases if it does not have its own vtable. Returns the vtable
596 /// and the class from which the vtable was loaded.
597 virtual std::pair<llvm::Value *, const CXXRecordDecl *>
598 LoadVTablePtr(CodeGenFunction &CGF, Address This,
599 const CXXRecordDecl *RD) = 0;
602 // Create an instance of a C++ ABI class:
604 /// Creates an Itanium-family ABI.
605 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
607 /// Creates a Microsoft-family ABI.
608 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
610 struct CatchRetScope final : EHScopeStack::Cleanup {
611 llvm::CatchPadInst *CPI;
613 CatchRetScope(llvm::CatchPadInst *CPI) : CPI(CPI) {}
615 void Emit(CodeGenFunction &CGF, Flags flags) override {
616 llvm::BasicBlock *BB = CGF.createBasicBlock("catchret.dest");
617 CGF.Builder.CreateCatchRet(CPI, BB);