1//===----- CGCXXABI.h - Interface to C++ ABIs -------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides an abstract class for C++ code generation. Concrete subclasses
11// of this implement code generation for specific C++ ABIs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef CLANG_CODEGEN_CXXABI_H
16#define CLANG_CODEGEN_CXXABI_H
17
18#include "CodeGenFunction.h"
19#include "clang/Basic/LLVM.h"
20
21namespace llvm {
22class Constant;
23class Type;
24class Value;
25}
26
27namespace clang {
28class CastExpr;
29class CXXConstructorDecl;
30class CXXDestructorDecl;
31class CXXMethodDecl;
32class CXXRecordDecl;
33class FieldDecl;
34class MangleContext;
35
36namespace CodeGen {
37class CodeGenFunction;
38class CodeGenModule;
39
40/// \brief Implements C++ ABI-specific code generation functions.
41class CGCXXABI {
42protected:
43  CodeGenModule &CGM;
44  std::unique_ptr<MangleContext> MangleCtx;
45
46  CGCXXABI(CodeGenModule &CGM)
47    : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
48
49protected:
50  ImplicitParamDecl *&getThisDecl(CodeGenFunction &CGF) {
51    return CGF.CXXABIThisDecl;
52  }
53  llvm::Value *&getThisValue(CodeGenFunction &CGF) {
54    return CGF.CXXABIThisValue;
55  }
56
57  /// Issue a diagnostic about unsupported features in the ABI.
58  void ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S);
59
60  /// Get a null value for unsupported member pointers.
61  llvm::Constant *GetBogusMemberPointer(QualType T);
62
63  ImplicitParamDecl *&getStructorImplicitParamDecl(CodeGenFunction &CGF) {
64    return CGF.CXXStructorImplicitParamDecl;
65  }
66  llvm::Value *&getStructorImplicitParamValue(CodeGenFunction &CGF) {
67    return CGF.CXXStructorImplicitParamValue;
68  }
69
70  /// Perform prolog initialization of the parameter variable suitable
71  /// for 'this' emitted by buildThisParam.
72  void EmitThisParam(CodeGenFunction &CGF);
73
74  ASTContext &getContext() const { return CGM.getContext(); }
75
76  virtual bool requiresArrayCookie(const CXXDeleteExpr *E, QualType eltType);
77  virtual bool requiresArrayCookie(const CXXNewExpr *E);
78
79public:
80
81  virtual ~CGCXXABI();
82
83  /// Gets the mangle context.
84  MangleContext &getMangleContext() {
85    return *MangleCtx;
86  }
87
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).
91  ///
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; }
95
96  /// If the C++ ABI requires the given type be returned in a particular way,
97  /// this method sets RetAI and returns true.
98  virtual bool classifyReturnType(CGFunctionInfo &FI) const = 0;
99
100  /// Specify how one should pass an argument of a record type.
101  enum RecordArgABI {
102    /// Pass it using the normal C aggregate rules for the ABI, potentially
103    /// introducing extra copies and passing some or all of it in registers.
104    RAA_Default = 0,
105
106    /// Pass it on the stack using its defined layout.  The argument must be
107    /// evaluated directly into the correct stack position in the arguments area,
108    /// and the call machinery must not move it or introduce extra copies.
109    RAA_DirectInMemory,
110
111    /// Pass it as a pointer to temporary memory.
112    RAA_Indirect
113  };
114
115  /// Returns true if C++ allows us to copy the memory of an object of type RD
116  /// when it is passed as an argument.
117  bool canCopyArgument(const CXXRecordDecl *RD) const;
118
119  /// Returns how an argument of the given record type should be passed.
120  virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
121
122  /// Returns true if the implicit 'sret' parameter comes after the implicit
123  /// 'this' parameter of C++ instance methods.
124  virtual bool isSRetParameterAfterThis() const { return false; }
125
126  /// Find the LLVM type used to represent the given member pointer
127  /// type.
128  virtual llvm::Type *
129  ConvertMemberPointerType(const MemberPointerType *MPT);
130
131  /// Load a member function from an object and a member function
132  /// pointer.  Apply the this-adjustment and set 'This' to the
133  /// adjusted value.
134  virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
135      CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
136      llvm::Value *MemPtr, const MemberPointerType *MPT);
137
138  /// Calculate an l-value from an object and a data member pointer.
139  virtual llvm::Value *
140  EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
141                               llvm::Value *Base, llvm::Value *MemPtr,
142                               const MemberPointerType *MPT);
143
144  /// Perform a derived-to-base, base-to-derived, or bitcast member
145  /// pointer conversion.
146  virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
147                                                   const CastExpr *E,
148                                                   llvm::Value *Src);
149
150  /// Perform a derived-to-base, base-to-derived, or bitcast member
151  /// pointer conversion on a constant value.
152  virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
153                                                      llvm::Constant *Src);
154
155  /// Return true if the given member pointer can be zero-initialized
156  /// (in the C++ sense) with an LLVM zeroinitializer.
157  virtual bool isZeroInitializable(const MemberPointerType *MPT);
158
159  /// Create a null member pointer of the given type.
160  virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
161
162  /// Create a member pointer for the given method.
163  virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
164
165  /// Create a member pointer for the given field.
166  virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
167                                                CharUnits offset);
168
169  /// Create a member pointer for the given member pointer constant.
170  virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
171
172  /// Emit a comparison between two member pointers.  Returns an i1.
173  virtual llvm::Value *
174  EmitMemberPointerComparison(CodeGenFunction &CGF,
175                              llvm::Value *L,
176                              llvm::Value *R,
177                              const MemberPointerType *MPT,
178                              bool Inequality);
179
180  /// Determine if a member pointer is non-null.  Returns an i1.
181  virtual llvm::Value *
182  EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
183                             llvm::Value *MemPtr,
184                             const MemberPointerType *MPT);
185
186protected:
187  /// A utility method for computing the offset required for the given
188  /// base-to-derived or derived-to-base member-pointer conversion.
189  /// Does not handle virtual conversions (in case we ever fully
190  /// support an ABI that allows this).  Returns null if no adjustment
191  /// is required.
192  llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
193
194  /// \brief Computes the non-virtual adjustment needed for a member pointer
195  /// conversion along an inheritance path stored in an APValue.  Unlike
196  /// getMemberPointerAdjustment(), the adjustment can be negative if the path
197  /// is from a derived type to a base type.
198  CharUnits getMemberPointerPathAdjustment(const APValue &MP);
199
200public:
201  /// Adjust the given non-null pointer to an object of polymorphic
202  /// type to point to the complete object.
203  ///
204  /// The IR type of the result should be a pointer but is otherwise
205  /// irrelevant.
206  virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
207                                              llvm::Value *ptr,
208                                              QualType type) = 0;
209
210  virtual llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) = 0;
211
212  virtual bool shouldTypeidBeNullChecked(bool IsDeref,
213                                         QualType SrcRecordTy) = 0;
214  virtual void EmitBadTypeidCall(CodeGenFunction &CGF) = 0;
215  virtual llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
216                                  llvm::Value *ThisPtr,
217                                  llvm::Type *StdTypeInfoPtrTy) = 0;
218
219  virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
220                                                  QualType SrcRecordTy) = 0;
221
222  virtual llvm::Value *
223  EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
224                      QualType SrcRecordTy, QualType DestTy,
225                      QualType DestRecordTy, llvm::BasicBlock *CastEnd) = 0;
226
227  virtual llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF,
228                                             llvm::Value *Value,
229                                             QualType SrcRecordTy,
230                                             QualType DestTy) = 0;
231
232  virtual bool EmitBadCastCall(CodeGenFunction &CGF) = 0;
233
234  virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
235                                                 llvm::Value *This,
236                                                 const CXXRecordDecl *ClassDecl,
237                                        const CXXRecordDecl *BaseClassDecl) = 0;
238
239  /// Build the signature of the given constructor variant by adding
240  /// any required parameters.  For convenience, ArgTys has been initialized
241  /// with the type of 'this' and ResTy has been initialized with the type of
242  /// 'this' if HasThisReturn(GlobalDecl(Ctor, T)) is true or 'void' otherwise
243  /// (although both may be changed by the ABI).
244  ///
245  /// If there are ever any ABIs where the implicit parameters are
246  /// intermixed with the formal parameters, we can address those
247  /// then.
248  virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
249                                         CXXCtorType T,
250                                         CanQualType &ResTy,
251                               SmallVectorImpl<CanQualType> &ArgTys) = 0;
252
253  virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
254                                                          const CXXRecordDecl *RD);
255
256  /// Emit the code to initialize hidden members required
257  /// to handle virtual inheritance, if needed by the ABI.
258  virtual void
259  initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
260                                            const CXXRecordDecl *RD) {}
261
262  /// Emit constructor variants required by this ABI.
263  virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
264
265  /// Build the signature of the given destructor variant by adding
266  /// any required parameters.  For convenience, ArgTys has been initialized
267  /// with the type of 'this' and ResTy has been initialized with the type of
268  /// 'this' if HasThisReturn(GlobalDecl(Dtor, T)) is true or 'void' otherwise
269  /// (although both may be changed by the ABI).
270  virtual void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
271                                        CXXDtorType T,
272                                        CanQualType &ResTy,
273                               SmallVectorImpl<CanQualType> &ArgTys) = 0;
274
275  /// Returns true if the given destructor type should be emitted as a linkonce
276  /// delegating thunk, regardless of whether the dtor is defined in this TU or
277  /// not.
278  virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
279                                      CXXDtorType DT) const = 0;
280
281  /// Emit destructor variants required by this ABI.
282  virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
283
284  /// Get the type of the implicit "this" parameter used by a method. May return
285  /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
286  /// parameter to point to some artificial offset in a complete object due to
287  /// vbases being reordered.
288  virtual const CXXRecordDecl *
289  getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
290    return MD->getParent();
291  }
292
293  /// Perform ABI-specific "this" argument adjustment required prior to
294  /// a call of a virtual function.
295  /// The "VirtualCall" argument is true iff the call itself is virtual.
296  virtual llvm::Value *
297  adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
298                                           llvm::Value *This,
299                                           bool VirtualCall) {
300    return This;
301  }
302
303  /// Build a parameter variable suitable for 'this'.
304  void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
305
306  /// Insert any ABI-specific implicit parameters into the parameter list for a
307  /// function.  This generally involves extra data for constructors and
308  /// destructors.
309  ///
310  /// ABIs may also choose to override the return type, which has been
311  /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
312  /// the formal return type of the function otherwise.
313  virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
314                                         FunctionArgList &Params) = 0;
315
316  /// Perform ABI-specific "this" parameter adjustment in a virtual function
317  /// prologue.
318  virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
319      CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
320    return This;
321  }
322
323  /// Emit the ABI-specific prolog for the function.
324  virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
325
326  /// Add any ABI-specific implicit arguments needed to call a constructor.
327  ///
328  /// \return The number of args added to the call, which is typically zero or
329  /// one.
330  virtual unsigned
331  addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
332                             CXXCtorType Type, bool ForVirtualBase,
333                             bool Delegating, CallArgList &Args) = 0;
334
335  /// Emit the destructor call.
336  virtual void EmitDestructorCall(CodeGenFunction &CGF,
337                                  const CXXDestructorDecl *DD, CXXDtorType Type,
338                                  bool ForVirtualBase, bool Delegating,
339                                  llvm::Value *This) = 0;
340
341  /// Emits the VTable definitions required for the given record type.
342  virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
343                                     const CXXRecordDecl *RD) = 0;
344
345  /// Get the address point of the vtable for the given base subobject while
346  /// building a constructor or a destructor. On return, NeedsVirtualOffset
347  /// tells if a virtual base adjustment is needed in order to get the offset
348  /// of the base subobject.
349  virtual llvm::Value *getVTableAddressPointInStructor(
350      CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
351      const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
352
353  /// Get the address point of the vtable for the given base subobject while
354  /// building a constexpr.
355  virtual llvm::Constant *
356  getVTableAddressPointForConstExpr(BaseSubobject Base,
357                                    const CXXRecordDecl *VTableClass) = 0;
358
359  /// Get the address of the vtable for the given record decl which should be
360  /// used for the vptr at the given offset in RD.
361  virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
362                                                CharUnits VPtrOffset) = 0;
363
364  /// Build a virtual function pointer in the ABI-specific way.
365  virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
366                                                 GlobalDecl GD,
367                                                 llvm::Value *This,
368                                                 llvm::Type *Ty) = 0;
369
370  /// Emit the ABI-specific virtual destructor call.
371  virtual void EmitVirtualDestructorCall(CodeGenFunction &CGF,
372                                         const CXXDestructorDecl *Dtor,
373                                         CXXDtorType DtorType,
374                                         SourceLocation CallLoc,
375                                         llvm::Value *This) = 0;
376
377  virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
378                                                GlobalDecl GD,
379                                                CallArgList &CallArgs) {}
380
381  /// Emit any tables needed to implement virtual inheritance.  For Itanium,
382  /// this emits virtual table tables.  For the MSVC++ ABI, this emits virtual
383  /// base tables.
384  virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
385
386  virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
387                               GlobalDecl GD, bool ReturnAdjustment) = 0;
388
389  virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
390                                             llvm::Value *This,
391                                             const ThisAdjustment &TA) = 0;
392
393  virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
394                                               llvm::Value *Ret,
395                                               const ReturnAdjustment &RA) = 0;
396
397  virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
398                                   RValue RV, QualType ResultType);
399
400  /// Gets the pure virtual member call function.
401  virtual StringRef GetPureVirtualCallName() = 0;
402
403  /// Gets the deleted virtual member call name.
404  virtual StringRef GetDeletedVirtualCallName() = 0;
405
406  /// \brief Returns true iff static data members that are initialized in the
407  /// class definition should have linkonce linkage.
408  virtual bool isInlineInitializedStaticDataMemberLinkOnce() { return false; }
409
410  /**************************** Array cookies ******************************/
411
412  /// Returns the extra size required in order to store the array
413  /// cookie for the given new-expression.  May return 0 to indicate that no
414  /// array cookie is required.
415  ///
416  /// Several cases are filtered out before this method is called:
417  ///   - non-array allocations never need a cookie
418  ///   - calls to \::operator new(size_t, void*) never need a cookie
419  ///
420  /// \param expr - the new-expression being allocated.
421  virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
422
423  /// Initialize the array cookie for the given allocation.
424  ///
425  /// \param NewPtr - a char* which is the presumed-non-null
426  ///   return value of the allocation function
427  /// \param NumElements - the computed number of elements,
428  ///   potentially collapsed from the multidimensional array case;
429  ///   always a size_t
430  /// \param ElementType - the base element allocated type,
431  ///   i.e. the allocated type after stripping all array types
432  virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
433                                             llvm::Value *NewPtr,
434                                             llvm::Value *NumElements,
435                                             const CXXNewExpr *expr,
436                                             QualType ElementType);
437
438  /// Reads the array cookie associated with the given pointer,
439  /// if it has one.
440  ///
441  /// \param Ptr - a pointer to the first element in the array
442  /// \param ElementType - the base element type of elements of the array
443  /// \param NumElements - an out parameter which will be initialized
444  ///   with the number of elements allocated, or zero if there is no
445  ///   cookie
446  /// \param AllocPtr - an out parameter which will be initialized
447  ///   with a char* pointing to the address returned by the allocation
448  ///   function
449  /// \param CookieSize - an out parameter which will be initialized
450  ///   with the size of the cookie, or zero if there is no cookie
451  virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
452                               const CXXDeleteExpr *expr,
453                               QualType ElementType, llvm::Value *&NumElements,
454                               llvm::Value *&AllocPtr, CharUnits &CookieSize);
455
456  /// Return whether the given global decl needs a VTT parameter.
457  virtual bool NeedsVTTParameter(GlobalDecl GD);
458
459protected:
460  /// Returns the extra size required in order to store the array
461  /// cookie for the given type.  Assumes that an array cookie is
462  /// required.
463  virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
464
465  /// Reads the array cookie for an allocation which is known to have one.
466  /// This is called by the standard implementation of ReadArrayCookie.
467  ///
468  /// \param ptr - a pointer to the allocation made for an array, as a char*
469  /// \param cookieSize - the computed cookie size of an array
470  ///
471  /// Other parameters are as above.
472  ///
473  /// \return a size_t
474  virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
475                                           llvm::Value *ptr,
476                                           CharUnits cookieSize);
477
478public:
479
480  /*************************** Static local guards ****************************/
481
482  /// Emits the guarded initializer and destructor setup for the given
483  /// variable, given that it couldn't be emitted as a constant.
484  /// If \p PerformInit is false, the initialization has been folded to a
485  /// constant and should not be performed.
486  ///
487  /// The variable may be:
488  ///   - a static local variable
489  ///   - a static data member of a class template instantiation
490  virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
491                               llvm::GlobalVariable *DeclPtr,
492                               bool PerformInit) = 0;
493
494  /// Emit code to force the execution of a destructor during global
495  /// teardown.  The default implementation of this uses atexit.
496  ///
497  /// \param dtor - a function taking a single pointer argument
498  /// \param addr - a pointer to pass to the destructor function.
499  virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
500                                  llvm::Constant *dtor, llvm::Constant *addr);
501
502  /*************************** thread_local initialization ********************/
503
504  /// Emits ABI-required functions necessary to initialize thread_local
505  /// variables in this translation unit.
506  ///
507  /// \param Decls The thread_local declarations in this translation unit.
508  /// \param InitFunc If this translation unit contains any non-constant
509  ///        initialization or non-trivial destruction for thread_local
510  ///        variables, a function to perform the initialization. Otherwise, 0.
511  virtual void EmitThreadLocalInitFuncs(
512      ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
513      llvm::Function *InitFunc);
514
515  /// Emit a reference to a non-local thread_local variable (including
516  /// triggering the initialization of all thread_local variables in its
517  /// translation unit).
518  virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
519                                              const VarDecl *VD,
520                                              QualType LValType);
521};
522
523// Create an instance of a C++ ABI class:
524
525/// Creates an Itanium-family ABI.
526CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
527
528/// Creates a Microsoft-family ABI.
529CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
530
531}
532}
533
534#endif
535