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 CLANG_CODEGEN_CXXABI_H
16 #define CLANG_CODEGEN_CXXABI_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 /// Returns true if the given record type should be returned indirectly.
97 virtual bool isReturnTypeIndirect(const CXXRecordDecl *RD) const = 0;
99 /// Specify how one should pass an argument of a record type.
101 /// Pass it using the normal C aggregate rules for the ABI, potentially
102 /// introducing extra copies and passing some or all of it in registers.
105 /// Pass it on the stack using its defined layout. The argument must be
106 /// evaluated directly into the correct stack position in the arguments area,
107 /// and the call machinery must not move it or introduce extra copies.
110 /// Pass it as a pointer to temporary memory.
114 /// Returns how an argument of the given record type should be passed.
115 virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
117 /// Find the LLVM type used to represent the given member pointer
120 ConvertMemberPointerType(const MemberPointerType *MPT);
122 /// Load a member function from an object and a member function
123 /// pointer. Apply the this-adjustment and set 'This' to the
125 virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
126 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
127 llvm::Value *MemPtr, const MemberPointerType *MPT);
129 /// Calculate an l-value from an object and a data member pointer.
130 virtual llvm::Value *
131 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
132 llvm::Value *Base, llvm::Value *MemPtr,
133 const MemberPointerType *MPT);
135 /// Perform a derived-to-base, base-to-derived, or bitcast member
136 /// pointer conversion.
137 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
141 /// Perform a derived-to-base, base-to-derived, or bitcast member
142 /// pointer conversion on a constant value.
143 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
144 llvm::Constant *Src);
146 /// Return true if the given member pointer can be zero-initialized
147 /// (in the C++ sense) with an LLVM zeroinitializer.
148 virtual bool isZeroInitializable(const MemberPointerType *MPT);
150 /// Create a null member pointer of the given type.
151 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
153 /// Create a member pointer for the given method.
154 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
156 /// Create a member pointer for the given field.
157 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
160 /// Create a member pointer for the given member pointer constant.
161 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
163 /// Emit a comparison between two member pointers. Returns an i1.
164 virtual llvm::Value *
165 EmitMemberPointerComparison(CodeGenFunction &CGF,
168 const MemberPointerType *MPT,
171 /// Determine if a member pointer is non-null. Returns an i1.
172 virtual llvm::Value *
173 EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
175 const MemberPointerType *MPT);
178 /// A utility method for computing the offset required for the given
179 /// base-to-derived or derived-to-base member-pointer conversion.
180 /// Does not handle virtual conversions (in case we ever fully
181 /// support an ABI that allows this). Returns null if no adjustment
183 llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
185 /// \brief Computes the non-virtual adjustment needed for a member pointer
186 /// conversion along an inheritance path stored in an APValue. Unlike
187 /// getMemberPointerAdjustment(), the adjustment can be negative if the path
188 /// is from a derived type to a base type.
189 CharUnits getMemberPointerPathAdjustment(const APValue &MP);
192 /// Adjust the given non-null pointer to an object of polymorphic
193 /// type to point to the complete object.
195 /// The IR type of the result should be a pointer but is otherwise
197 virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
201 virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
203 const CXXRecordDecl *ClassDecl,
204 const CXXRecordDecl *BaseClassDecl) = 0;
206 /// Build the signature of the given constructor variant by adding
207 /// any required parameters. For convenience, ArgTys has been initialized
208 /// with the type of 'this' and ResTy has been initialized with the type of
209 /// 'this' if HasThisReturn(GlobalDecl(Ctor, T)) is true or 'void' otherwise
210 /// (although both may be changed by the ABI).
212 /// If there are ever any ABIs where the implicit parameters are
213 /// intermixed with the formal parameters, we can address those
215 virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
218 SmallVectorImpl<CanQualType> &ArgTys) = 0;
220 virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
221 const CXXRecordDecl *RD);
223 /// Emit the code to initialize hidden members required
224 /// to handle virtual inheritance, if needed by the ABI.
226 initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
227 const CXXRecordDecl *RD) {}
229 /// Emit constructor variants required by this ABI.
230 virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
232 /// Build the signature of the given destructor variant by adding
233 /// any required parameters. For convenience, ArgTys has been initialized
234 /// with the type of 'this' and ResTy has been initialized with the type of
235 /// 'this' if HasThisReturn(GlobalDecl(Dtor, T)) is true or 'void' otherwise
236 /// (although both may be changed by the ABI).
237 virtual void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
240 SmallVectorImpl<CanQualType> &ArgTys) = 0;
242 /// Returns true if the given destructor type should be emitted as a linkonce
243 /// delegating thunk, regardless of whether the dtor is defined in this TU or
245 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
246 CXXDtorType DT) const = 0;
248 /// Emit destructor variants required by this ABI.
249 virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
251 /// Get the type of the implicit "this" parameter used by a method. May return
252 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
253 /// parameter to point to some artificial offset in a complete object due to
254 /// vbases being reordered.
255 virtual const CXXRecordDecl *
256 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
257 return MD->getParent();
260 /// Perform ABI-specific "this" argument adjustment required prior to
261 /// a call of a virtual function.
262 /// The "VirtualCall" argument is true iff the call itself is virtual.
263 virtual llvm::Value *
264 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
270 /// Build a parameter variable suitable for 'this'.
271 void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
273 /// Insert any ABI-specific implicit parameters into the parameter list for a
274 /// function. This generally involves extra data for constructors and
277 /// ABIs may also choose to override the return type, which has been
278 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
279 /// the formal return type of the function otherwise.
280 virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
281 FunctionArgList &Params) = 0;
283 /// Perform ABI-specific "this" parameter adjustment in a virtual function
285 virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
286 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
290 /// Emit the ABI-specific prolog for the function.
291 virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
293 /// Add any ABI-specific implicit arguments needed to call a constructor.
295 /// \return The number of args added to the call, which is typically zero or
298 addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
299 CXXCtorType Type, bool ForVirtualBase,
300 bool Delegating, CallArgList &Args) = 0;
302 /// Emit the destructor call.
303 virtual void EmitDestructorCall(CodeGenFunction &CGF,
304 const CXXDestructorDecl *DD, CXXDtorType Type,
305 bool ForVirtualBase, bool Delegating,
306 llvm::Value *This) = 0;
308 /// Emits the VTable definitions required for the given record type.
309 virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
310 const CXXRecordDecl *RD) = 0;
312 /// Get the address point of the vtable for the given base subobject while
313 /// building a constructor or a destructor. On return, NeedsVirtualOffset
314 /// tells if a virtual base adjustment is needed in order to get the offset
315 /// of the base subobject.
316 virtual llvm::Value *getVTableAddressPointInStructor(
317 CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
318 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
320 /// Get the address point of the vtable for the given base subobject while
321 /// building a constexpr.
322 virtual llvm::Constant *
323 getVTableAddressPointForConstExpr(BaseSubobject Base,
324 const CXXRecordDecl *VTableClass) = 0;
326 /// Get the address of the vtable for the given record decl which should be
327 /// used for the vptr at the given offset in RD.
328 virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
329 CharUnits VPtrOffset) = 0;
331 /// Build a virtual function pointer in the ABI-specific way.
332 virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
337 /// Emit the ABI-specific virtual destructor call.
338 virtual void EmitVirtualDestructorCall(CodeGenFunction &CGF,
339 const CXXDestructorDecl *Dtor,
340 CXXDtorType DtorType,
341 SourceLocation CallLoc,
342 llvm::Value *This) = 0;
344 virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
346 CallArgList &CallArgs) {}
348 /// Emit any tables needed to implement virtual inheritance. For Itanium,
349 /// this emits virtual table tables. For the MSVC++ ABI, this emits virtual
351 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
353 virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) = 0;
355 virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
357 const ThisAdjustment &TA) = 0;
359 virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
361 const ReturnAdjustment &RA) = 0;
363 virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
364 RValue RV, QualType ResultType);
366 /// Gets the pure virtual member call function.
367 virtual StringRef GetPureVirtualCallName() = 0;
369 /// Gets the deleted virtual member call name.
370 virtual StringRef GetDeletedVirtualCallName() = 0;
372 /// \brief Returns true iff static data members that are initialized in the
373 /// class definition should have linkonce linkage.
374 virtual bool isInlineInitializedStaticDataMemberLinkOnce() { return false; }
376 /**************************** Array cookies ******************************/
378 /// Returns the extra size required in order to store the array
379 /// cookie for the given new-expression. May return 0 to indicate that no
380 /// array cookie is required.
382 /// Several cases are filtered out before this method is called:
383 /// - non-array allocations never need a cookie
384 /// - calls to \::operator new(size_t, void*) never need a cookie
386 /// \param expr - the new-expression being allocated.
387 virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
389 /// Initialize the array cookie for the given allocation.
391 /// \param NewPtr - a char* which is the presumed-non-null
392 /// return value of the allocation function
393 /// \param NumElements - the computed number of elements,
394 /// potentially collapsed from the multidimensional array case;
396 /// \param ElementType - the base element allocated type,
397 /// i.e. the allocated type after stripping all array types
398 virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
400 llvm::Value *NumElements,
401 const CXXNewExpr *expr,
402 QualType ElementType);
404 /// Reads the array cookie associated with the given pointer,
407 /// \param Ptr - a pointer to the first element in the array
408 /// \param ElementType - the base element type of elements of the array
409 /// \param NumElements - an out parameter which will be initialized
410 /// with the number of elements allocated, or zero if there is no
412 /// \param AllocPtr - an out parameter which will be initialized
413 /// with a char* pointing to the address returned by the allocation
415 /// \param CookieSize - an out parameter which will be initialized
416 /// with the size of the cookie, or zero if there is no cookie
417 virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
418 const CXXDeleteExpr *expr,
419 QualType ElementType, llvm::Value *&NumElements,
420 llvm::Value *&AllocPtr, CharUnits &CookieSize);
422 /// Return whether the given global decl needs a VTT parameter.
423 virtual bool NeedsVTTParameter(GlobalDecl GD);
426 /// Returns the extra size required in order to store the array
427 /// cookie for the given type. Assumes that an array cookie is
429 virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
431 /// Reads the array cookie for an allocation which is known to have one.
432 /// This is called by the standard implementation of ReadArrayCookie.
434 /// \param ptr - a pointer to the allocation made for an array, as a char*
435 /// \param cookieSize - the computed cookie size of an array
437 /// Other parameters are as above.
440 virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
442 CharUnits cookieSize);
446 /*************************** Static local guards ****************************/
448 /// Emits the guarded initializer and destructor setup for the given
449 /// variable, given that it couldn't be emitted as a constant.
450 /// If \p PerformInit is false, the initialization has been folded to a
451 /// constant and should not be performed.
453 /// The variable may be:
454 /// - a static local variable
455 /// - a static data member of a class template instantiation
456 virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
457 llvm::GlobalVariable *DeclPtr,
458 bool PerformInit) = 0;
460 /// Emit code to force the execution of a destructor during global
461 /// teardown. The default implementation of this uses atexit.
463 /// \param dtor - a function taking a single pointer argument
464 /// \param addr - a pointer to pass to the destructor function.
465 virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
466 llvm::Constant *dtor, llvm::Constant *addr);
468 /*************************** thread_local initialization ********************/
470 /// Emits ABI-required functions necessary to initialize thread_local
471 /// variables in this translation unit.
473 /// \param Decls The thread_local declarations in this translation unit.
474 /// \param InitFunc If this translation unit contains any non-constant
475 /// initialization or non-trivial destruction for thread_local
476 /// variables, a function to perform the initialization. Otherwise, 0.
477 virtual void EmitThreadLocalInitFuncs(
478 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
479 llvm::Function *InitFunc);
481 /// Emit a reference to a non-local thread_local variable (including
482 /// triggering the initialization of all thread_local variables in its
483 /// translation unit).
484 virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
488 /**************************** RTTI Uniqueness ******************************/
491 /// Returns true if the ABI requires RTTI type_info objects to be unique
492 /// across a program.
493 virtual bool shouldRTTIBeUnique() { return true; }
496 /// What sort of unique-RTTI behavior should we use?
497 enum RTTIUniquenessKind {
498 /// We are guaranteeing, or need to guarantee, that the RTTI string
502 /// We are not guaranteeing uniqueness for the RTTI string, so we
503 /// can demote to hidden visibility but must use string comparisons.
506 /// We are not guaranteeing uniqueness for the RTTI string, so we
507 /// have to use string comparisons, but we also have to emit it with
508 /// non-hidden visibility.
512 /// Return the required visibility status for the given type and linkage in
515 classifyRTTIUniqueness(QualType CanTy,
516 llvm::GlobalValue::LinkageTypes Linkage);
519 // Create an instance of a C++ ABI class:
521 /// Creates an Itanium-family ABI.
522 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
524 /// Creates a Microsoft-family ABI.
525 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);