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;
38 class CodeGenFunction;
42 /// \brief Implements C++ ABI-specific code generation functions.
46 std::unique_ptr<MangleContext> MangleCtx;
48 CGCXXABI(CodeGenModule &CGM)
49 : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
52 ImplicitParamDecl *getThisDecl(CodeGenFunction &CGF) {
53 return CGF.CXXABIThisDecl;
55 llvm::Value *getThisValue(CodeGenFunction &CGF) {
56 return CGF.CXXABIThisValue;
58 Address getThisAddress(CodeGenFunction &CGF) {
59 return Address(CGF.CXXABIThisValue, CGF.CXXABIThisAlignment);
62 /// Issue a diagnostic about unsupported features in the ABI.
63 void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
65 /// Get a null value for unsupported member pointers.
66 llvm::Constant *GetBogusMemberPointer(QualType T);
68 ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
69 return CGF.CXXStructorImplicitParamDecl;
71 llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
72 return CGF.CXXStructorImplicitParamValue;
75 /// Perform prolog initialization of the parameter variable suitable
76 /// for 'this' emitted by buildThisParam.
77 void EmitThisParam(CodeGenFunction &CGF);
79 ASTContext &getContext() const { return CGM.getContext(); }
81 virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
82 virtual bool requiresArrayCookie(const CXXNewExpr *E);
84 /// Determine whether there's something special about the rules of
85 /// the ABI tell us that 'this' is a complete object within the
86 /// given function. Obvious common logic like being defined on a
87 /// final class will have been taken care of by the caller.
88 virtual bool isThisCompleteObject(GlobalDecl GD) const = 0;
94 /// Gets the mangle context.
95 MangleContext &getMangleContext() {
99 /// Returns true if the given constructor or destructor is one of the
100 /// kinds that the ABI says returns 'this' (only applies when called
101 /// non-virtually for destructors).
103 /// There currently is no way to indicate if a destructor returns 'this'
104 /// when called virtually, and code generation does not support the case.
105 virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
107 virtual bool hasMostDerivedReturn(GlobalDecl GD) const { return false; }
109 /// If the C++ ABI requires the given type be returned in a particular way,
110 /// this method sets RetAI and returns true.
111 virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
113 /// Specify how one should pass an argument of a record type.
115 /// Pass it using the normal C aggregate rules for the ABI, potentially
116 /// introducing extra copies and passing some or all of it in registers.
119 /// Pass it on the stack using its defined layout. The argument must be
120 /// evaluated directly into the correct stack position in the arguments area,
121 /// and the call machinery must not move it or introduce extra copies.
124 /// Pass it as a pointer to temporary memory.
128 /// Returns true if C++ allows us to copy the memory of an object of type RD
129 /// when it is passed as an argument.
130 bool canCopyArgument(const CXXRecordDecl *RD) const;
132 /// Returns how an argument of the given record type should be passed.
133 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
135 /// Returns true if the implicit 'sret' parameter comes after the implicit
136 /// 'this' parameter of C++ instance methods.
137 virtual bool isSRetParameterAfterThis() const { return false; }
139 /// Find the LLVM type used to represent the given member pointer
142 ConvertMemberPointerType(const MemberPointerType *MPT);
144 /// Load a member function from an object and a member function
145 /// pointer. Apply the this-adjustment and set 'This' to the
147 virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
148 CodeGenFunction &CGF, const Expr *E, Address This,
149 llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
150 const MemberPointerType *MPT);
152 /// Calculate an l-value from an object and a data member pointer.
153 virtual llvm::Value *
154 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
155 Address Base, llvm::Value *MemPtr,
156 const MemberPointerType *MPT);
158 /// Perform a derived-to-base, base-to-derived, or bitcast member
159 /// pointer conversion.
160 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
164 /// Perform a derived-to-base, base-to-derived, or bitcast member
165 /// pointer conversion on a constant value.
166 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
167 llvm::Constant *Src);
169 /// Return true if the given member pointer can be zero-initialized
170 /// (in the C++ sense) with an LLVM zeroinitializer.
171 virtual bool isZeroInitializable(const MemberPointerType *MPT);
173 /// Return whether or not a member pointers type is convertible to an IR type.
174 virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const {
178 /// Create a null member pointer of the given type.
179 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
181 /// Create a member pointer for the given method.
182 virtual llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD);
184 /// Create a member pointer for the given field.
185 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
188 /// Create a member pointer for the given member pointer constant.
189 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
191 /// Emit a comparison between two member pointers. Returns an i1.
192 virtual llvm::Value *
193 EmitMemberPointerComparison(CodeGenFunction &CGF,
196 const MemberPointerType *MPT,
199 /// Determine if a member pointer is non-null. Returns an i1.
200 virtual llvm::Value *
201 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
203 const MemberPointerType *MPT);
206 /// A utility method for computing the offset required for the given
207 /// base-to-derived or derived-to-base member-pointer conversion.
208 /// Does not handle virtual conversions (in case we ever fully
209 /// support an ABI that allows this). Returns null if no adjustment
211 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
213 /// \brief Computes the non-virtual adjustment needed for a member pointer
214 /// conversion along an inheritance path stored in an APValue. Unlike
215 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
216 /// is from a derived type to a base type.
217 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
220 virtual void emitVirtualObjectDelete(CodeGenFunction &CGF,
221 const CXXDeleteExpr *DE,
222 Address Ptr, QualType ElementType,
223 const CXXDestructorDecl *Dtor) = 0;
224 virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) = 0;
225 virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) = 0;
226 virtual llvm::GlobalVariable *getThrowInfo(QualType T) { return nullptr; }
228 /// \brief Determine whether it's possible to emit a vtable for \p RD, even
229 /// though we do not know that the vtable has been marked as used by semantic
231 virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
233 virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) = 0;
235 virtual llvm::CallInst *
236 emitTerminateForUnexpectedException(CodeGenFunction &CGF,
239 virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
240 virtual CatchTypeInfo
241 getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) = 0;
242 virtual CatchTypeInfo getCatchAllTypeInfo();
244 virtual bool shouldTypeidBeNullChecked(bool IsDeref,
245 QualType SrcRecordTy) = 0;
246 virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
247 virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
249 llvm::Type *StdTypeInfoPtrTy) = 0;
251 virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
252 QualType SrcRecordTy) = 0;
254 virtual llvm::Value *
255 EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
256 QualType SrcRecordTy, QualType DestTy,
257 QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
259 virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
261 QualType SrcRecordTy,
262 QualType DestTy) = 0;
264 virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
266 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
268 const CXXRecordDecl *ClassDecl,
269 const CXXRecordDecl *BaseClassDecl) = 0;
271 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
272 const CXXRecordDecl *RD);
274 /// Emit the code to initialize hidden members required
275 /// to handle virtual inheritance, if needed by the ABI.
277 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
278 const CXXRecordDecl *RD) {}
280 /// Emit constructor variants required by this ABI.
281 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
283 /// Build the signature of the given constructor or destructor variant by
284 /// adding any required parameters. For convenience, ArgTys has been
285 /// initialized with the type of 'this'.
286 virtual void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
287 SmallVectorImpl<CanQualType> &ArgTys) = 0;
289 /// Returns true if the given destructor type should be emitted as a linkonce
290 /// delegating thunk, regardless of whether the dtor is defined in this TU or
292 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
293 CXXDtorType DT) const = 0;
295 /// Emit destructor variants required by this ABI.
296 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
298 /// Get the type of the implicit "this" parameter used by a method. May return
299 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
300 /// parameter to point to some artificial offset in a complete object due to
301 /// vbases being reordered.
302 virtual const CXXRecordDecl *
303 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
304 return MD->getParent();
307 /// Perform ABI-specific "this" argument adjustment required prior to
308 /// a call of a virtual function.
309 /// The "VirtualCall" argument is true iff the call itself is virtual.
311 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
312 Address This, bool VirtualCall) {
316 /// Build a parameter variable suitable for 'this'.
317 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
319 /// Insert any ABI-specific implicit parameters into the parameter list for a
320 /// function. This generally involves extra data for constructors and
323 /// ABIs may also choose to override the return type, which has been
324 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
325 /// the formal return type of the function otherwise.
326 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
327 FunctionArgList &Params) = 0;
329 /// Perform ABI-specific "this" parameter adjustment in a virtual function
331 virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
332 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
336 /// Emit the ABI-specific prolog for the function.
337 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
339 /// Add any ABI-specific implicit arguments needed to call a constructor.
341 /// \return The number of args added to the call, which is typically zero or
344 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
345 CXXCtorType Type, bool ForVirtualBase,
346 bool Delegating, CallArgList &Args) = 0;
348 /// Emit the destructor call.
349 virtual void EmitDestructorCall(CodeGenFunction &CGF,
350 const CXXDestructorDecl *DD, CXXDtorType Type,
351 bool ForVirtualBase, bool Delegating,
354 /// Emits the VTable definitions required for the given record type.
355 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
356 const CXXRecordDecl *RD) = 0;
358 /// Checks if ABI requires extra virtual offset for vtable field.
360 isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
361 CodeGenFunction::VPtr Vptr) = 0;
363 /// Checks if ABI requires to initilize vptrs for given dynamic class.
364 virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) = 0;
366 /// Get the address point of the vtable for the given base subobject.
367 virtual llvm::Constant *
368 getVTableAddressPoint(BaseSubobject Base,
369 const CXXRecordDecl *VTableClass) = 0;
371 /// Get the address point of the vtable for the given base subobject while
372 /// building a constructor or a destructor.
373 virtual llvm::Value *
374 getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD,
376 const CXXRecordDecl *NearestVBase) = 0;
378 /// Get the address point of the vtable for the given base subobject while
379 /// building a constexpr.
380 virtual llvm::Constant *
381 getVTableAddressPointForConstExpr(BaseSubobject Base,
382 const CXXRecordDecl *VTableClass) = 0;
384 /// Get the address of the vtable for the given record decl which should be
385 /// used for the vptr at the given offset in RD.
386 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
387 CharUnits VPtrOffset) = 0;
389 /// Build a virtual function pointer in the ABI-specific way.
390 virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
394 SourceLocation Loc) = 0;
396 /// Emit the ABI-specific virtual destructor call.
397 virtual llvm::Value *
398 EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor,
399 CXXDtorType DtorType, Address This,
400 const CXXMemberCallExpr *CE) = 0;
402 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
404 CallArgList &CallArgs) {}
406 /// Emit any tables needed to implement virtual inheritance. For Itanium,
407 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
409 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
411 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
412 GlobalDecl GD, bool ReturnAdjustment) = 0;
414 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
416 const ThisAdjustment &TA) = 0;
418 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
420 const ReturnAdjustment &RA) = 0;
422 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
423 RValue RV, QualType ResultType);
425 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
426 FunctionArgList &Args) const = 0;
428 /// Gets the offsets of all the virtual base pointers in a given class.
429 virtual std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD);
431 /// Gets the pure virtual member call function.
432 virtual StringRef GetPureVirtualCallName() = 0;
434 /// Gets the deleted virtual member call name.
435 virtual StringRef GetDeletedVirtualCallName() = 0;
437 /**************************** Array cookies ******************************/
439 /// Returns the extra size required in order to store the array
440 /// cookie for the given new-expression. May return 0 to indicate that no
441 /// array cookie is required.
443 /// Several cases are filtered out before this method is called:
444 /// - non-array allocations never need a cookie
445 /// - calls to \::operator new(size_t, void*) never need a cookie
447 /// \param expr - the new-expression being allocated.
448 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
450 /// Initialize the array cookie for the given allocation.
452 /// \param NewPtr - a char* which is the presumed-non-null
453 /// return value of the allocation function
454 /// \param NumElements - the computed number of elements,
455 /// potentially collapsed from the multidimensional array case;
457 /// \param ElementType - the base element allocated type,
458 /// i.e. the allocated type after stripping all array types
459 virtual Address InitializeArrayCookie(CodeGenFunction &CGF,
461 llvm::Value *NumElements,
462 const CXXNewExpr *expr,
463 QualType ElementType);
465 /// Reads the array cookie associated with the given pointer,
468 /// \param Ptr - a pointer to the first element in the array
469 /// \param ElementType - the base element type of elements of the array
470 /// \param NumElements - an out parameter which will be initialized
471 /// with the number of elements allocated, or zero if there is no
473 /// \param AllocPtr - an out parameter which will be initialized
474 /// with a char* pointing to the address returned by the allocation
476 /// \param CookieSize - an out parameter which will be initialized
477 /// with the size of the cookie, or zero if there is no cookie
478 virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr,
479 const CXXDeleteExpr *expr,
480 QualType ElementType, llvm::Value *&NumElements,
481 llvm::Value *&AllocPtr, CharUnits &CookieSize);
483 /// Return whether the given global decl needs a VTT parameter.
484 virtual bool NeedsVTTParameter(GlobalDecl GD);
487 /// Returns the extra size required in order to store the array
488 /// cookie for the given type. Assumes that an array cookie is
490 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
492 /// Reads the array cookie for an allocation which is known to have one.
493 /// This is called by the standard implementation of ReadArrayCookie.
495 /// \param ptr - a pointer to the allocation made for an array, as a char*
496 /// \param cookieSize - the computed cookie size of an array
498 /// Other parameters are as above.
501 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF, Address ptr,
502 CharUnits cookieSize);
506 /*************************** Static local guards ****************************/
508 /// Emits the guarded initializer and destructor setup for the given
509 /// variable, given that it couldn't be emitted as a constant.
510 /// If \p PerformInit is false, the initialization has been folded to a
511 /// constant and should not be performed.
513 /// The variable may be:
514 /// - a static local variable
515 /// - a static data member of a class template instantiation
516 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
517 llvm::GlobalVariable *DeclPtr,
518 bool PerformInit) = 0;
520 /// Emit code to force the execution of a destructor during global
521 /// teardown. The default implementation of this uses atexit.
523 /// \param Dtor - a function taking a single pointer argument
524 /// \param Addr - a pointer to pass to the destructor function.
525 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
526 llvm::Constant *Dtor,
527 llvm::Constant *Addr) = 0;
529 /*************************** thread_local initialization ********************/
531 /// Emits ABI-required functions necessary to initialize thread_local
532 /// variables in this translation unit.
534 /// \param CXXThreadLocals - The thread_local declarations in this translation
536 /// \param CXXThreadLocalInits - If this translation unit contains any
537 /// non-constant initialization or non-trivial destruction for
538 /// thread_local variables, a list of functions to perform the
540 virtual void EmitThreadLocalInitFuncs(
541 CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
542 ArrayRef<llvm::Function *> CXXThreadLocalInits,
543 ArrayRef<const VarDecl *> CXXThreadLocalInitVars) = 0;
545 // Determine if references to thread_local global variables can be made
546 // directly or require access through a thread wrapper function.
547 virtual bool usesThreadWrapperFunction() const = 0;
549 /// Emit a reference to a non-local thread_local variable (including
550 /// triggering the initialization of all thread_local variables in its
551 /// translation unit).
552 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
554 QualType LValType) = 0;
556 /// Emit a single constructor/destructor with the given type from a C++
557 /// constructor Decl.
558 virtual void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) = 0;
561 // Create an instance of a C++ ABI class:
563 /// Creates an Itanium-family ABI.
564 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
566 /// Creates a Microsoft-family ABI.
567 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);