]> granicus.if.org Git - clang/blob - lib/CodeGen/CGCXXABI.h
Replace OwningPtr with std::unique_ptr.
[clang] / lib / CodeGen / CGCXXABI.h
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
21 namespace llvm {
22   class Constant;
23   class Type;
24   class Value;
25 }
26
27 namespace clang {
28   class CastExpr;
29   class CXXConstructorDecl;
30   class CXXDestructorDecl;
31   class CXXMethodDecl;
32   class CXXRecordDecl;
33   class FieldDecl;
34   class MangleContext;
35
36 namespace CodeGen {
37   class CodeGenFunction;
38   class CodeGenModule;
39
40 /// \brief Implements C++ ABI-specific code generation functions.
41 class CGCXXABI {
42 protected:
43   CodeGenModule &CGM;
44   std::unique_ptr<MangleContext> MangleCtx;
45
46   CGCXXABI(CodeGenModule &CGM)
47     : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
48
49 protected:
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
79 public:
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   /// Returns true if the given record type should be returned indirectly.
97   virtual bool isReturnTypeIndirect(const CXXRecordDecl *RD) const = 0;
98
99   /// Specify how one should pass an argument of a record type.
100   enum RecordArgABI {
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.
103     RAA_Default = 0,
104
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.
108     RAA_DirectInMemory,
109
110     /// Pass it as a pointer to temporary memory.
111     RAA_Indirect
112   };
113
114   /// Returns how an argument of the given record type should be passed.
115   virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
116
117   /// Find the LLVM type used to represent the given member pointer
118   /// type.
119   virtual llvm::Type *
120   ConvertMemberPointerType(const MemberPointerType *MPT);
121
122   /// Load a member function from an object and a member function
123   /// pointer.  Apply the this-adjustment and set 'This' to the
124   /// adjusted value.
125   virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
126       CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
127       llvm::Value *MemPtr, const MemberPointerType *MPT);
128
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);
134
135   /// Perform a derived-to-base, base-to-derived, or bitcast member
136   /// pointer conversion.
137   virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
138                                                    const CastExpr *E,
139                                                    llvm::Value *Src);
140
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);
145
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);
149
150   /// Create a null member pointer of the given type.
151   virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
152
153   /// Create a member pointer for the given method.
154   virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
155
156   /// Create a member pointer for the given field.
157   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
158                                                 CharUnits offset);
159
160   /// Create a member pointer for the given member pointer constant.
161   virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
162
163   /// Emit a comparison between two member pointers.  Returns an i1.
164   virtual llvm::Value *
165   EmitMemberPointerComparison(CodeGenFunction &CGF,
166                               llvm::Value *L,
167                               llvm::Value *R,
168                               const MemberPointerType *MPT,
169                               bool Inequality);
170
171   /// Determine if a member pointer is non-null.  Returns an i1.
172   virtual llvm::Value *
173   EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
174                              llvm::Value *MemPtr,
175                              const MemberPointerType *MPT);
176
177 protected:
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
182   /// is required.
183   llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
184
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);
190
191 public:
192   /// Adjust the given non-null pointer to an object of polymorphic
193   /// type to point to the complete object.
194   ///
195   /// The IR type of the result should be a pointer but is otherwise
196   /// irrelevant.
197   virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
198                                               llvm::Value *ptr,
199                                               QualType type) = 0;
200
201   virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
202                                                  llvm::Value *This,
203                                                  const CXXRecordDecl *ClassDecl,
204                                         const CXXRecordDecl *BaseClassDecl) = 0;
205
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).
211   ///
212   /// If there are ever any ABIs where the implicit parameters are
213   /// intermixed with the formal parameters, we can address those
214   /// then.
215   virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
216                                          CXXCtorType T,
217                                          CanQualType &ResTy,
218                                SmallVectorImpl<CanQualType> &ArgTys) = 0;
219
220   virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
221                                                           const CXXRecordDecl *RD);
222
223   /// Emit the code to initialize hidden members required
224   /// to handle virtual inheritance, if needed by the ABI.
225   virtual void
226   initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
227                                             const CXXRecordDecl *RD) {}
228
229   /// Emit constructor variants required by this ABI.
230   virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
231
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,
238                                         CXXDtorType T,
239                                         CanQualType &ResTy,
240                                SmallVectorImpl<CanQualType> &ArgTys) = 0;
241
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
244   /// not.
245   virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
246                                       CXXDtorType DT) const = 0;
247
248   /// Emit destructor variants required by this ABI.
249   virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
250
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();
258   }
259
260   /// Perform ABI-specific "this" argument adjustment required prior to
261   /// a virtual function call.
262   virtual llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
263                                                         GlobalDecl GD,
264                                                         llvm::Value *This) {
265     return This;
266   }
267
268   /// Build a parameter variable suitable for 'this'.
269   void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
270
271   /// Insert any ABI-specific implicit parameters into the parameter list for a
272   /// function.  This generally involves extra data for constructors and
273   /// destructors.
274   ///
275   /// ABIs may also choose to override the return type, which has been
276   /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
277   /// the formal return type of the function otherwise.
278   virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
279                                          FunctionArgList &Params) = 0;
280
281   /// Perform ABI-specific "this" parameter adjustment in a virtual function
282   /// prologue.
283   virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
284       CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
285     return This;
286   }
287
288   /// Emit the ABI-specific prolog for the function.
289   virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
290
291   /// Add any ABI-specific implicit arguments needed to call a constructor.
292   ///
293   /// \return The number of args added to the call, which is typically zero or
294   /// one.
295   virtual unsigned
296   addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
297                              CXXCtorType Type, bool ForVirtualBase,
298                              bool Delegating, CallArgList &Args) = 0;
299
300   /// Emit the destructor call.
301   virtual void EmitDestructorCall(CodeGenFunction &CGF,
302                                   const CXXDestructorDecl *DD, CXXDtorType Type,
303                                   bool ForVirtualBase, bool Delegating,
304                                   llvm::Value *This) = 0;
305
306   /// Emits the VTable definitions required for the given record type.
307   virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
308                                      const CXXRecordDecl *RD) = 0;
309
310   /// Get the address point of the vtable for the given base subobject while
311   /// building a constructor or a destructor. On return, NeedsVirtualOffset
312   /// tells if a virtual base adjustment is needed in order to get the offset
313   /// of the base subobject.
314   virtual llvm::Value *getVTableAddressPointInStructor(
315       CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
316       const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
317
318   /// Get the address point of the vtable for the given base subobject while
319   /// building a constexpr.
320   virtual llvm::Constant *
321   getVTableAddressPointForConstExpr(BaseSubobject Base,
322                                     const CXXRecordDecl *VTableClass) = 0;
323
324   /// Get the address of the vtable for the given record decl which should be
325   /// used for the vptr at the given offset in RD.
326   virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
327                                                 CharUnits VPtrOffset) = 0;
328
329   /// Build a virtual function pointer in the ABI-specific way.
330   virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
331                                                  GlobalDecl GD,
332                                                  llvm::Value *This,
333                                                  llvm::Type *Ty) = 0;
334
335   /// Emit the ABI-specific virtual destructor call.
336   virtual void EmitVirtualDestructorCall(CodeGenFunction &CGF,
337                                          const CXXDestructorDecl *Dtor,
338                                          CXXDtorType DtorType,
339                                          SourceLocation CallLoc,
340                                          llvm::Value *This) = 0;
341
342   virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
343                                                 GlobalDecl GD,
344                                                 CallArgList &CallArgs) {}
345
346   /// Emit any tables needed to implement virtual inheritance.  For Itanium,
347   /// this emits virtual table tables.  For the MSVC++ ABI, this emits virtual
348   /// base tables.
349   virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
350
351   virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) = 0;
352
353   virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
354                                              llvm::Value *This,
355                                              const ThisAdjustment &TA) = 0;
356
357   virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
358                                                llvm::Value *Ret,
359                                                const ReturnAdjustment &RA) = 0;
360
361   virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
362                                    RValue RV, QualType ResultType);
363
364   /// Gets the pure virtual member call function.
365   virtual StringRef GetPureVirtualCallName() = 0;
366
367   /// Gets the deleted virtual member call name.
368   virtual StringRef GetDeletedVirtualCallName() = 0;
369
370   /// \brief Returns true iff static data members that are initialized in the
371   /// class definition should have linkonce linkage.
372   virtual bool isInlineInitializedStaticDataMemberLinkOnce() { return false; }
373
374   /**************************** Array cookies ******************************/
375
376   /// Returns the extra size required in order to store the array
377   /// cookie for the given new-expression.  May return 0 to indicate that no
378   /// array cookie is required.
379   ///
380   /// Several cases are filtered out before this method is called:
381   ///   - non-array allocations never need a cookie
382   ///   - calls to \::operator new(size_t, void*) never need a cookie
383   ///
384   /// \param expr - the new-expression being allocated.
385   virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
386
387   /// Initialize the array cookie for the given allocation.
388   ///
389   /// \param NewPtr - a char* which is the presumed-non-null
390   ///   return value of the allocation function
391   /// \param NumElements - the computed number of elements,
392   ///   potentially collapsed from the multidimensional array case;
393   ///   always a size_t
394   /// \param ElementType - the base element allocated type,
395   ///   i.e. the allocated type after stripping all array types
396   virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
397                                              llvm::Value *NewPtr,
398                                              llvm::Value *NumElements,
399                                              const CXXNewExpr *expr,
400                                              QualType ElementType);
401
402   /// Reads the array cookie associated with the given pointer,
403   /// if it has one.
404   ///
405   /// \param Ptr - a pointer to the first element in the array
406   /// \param ElementType - the base element type of elements of the array
407   /// \param NumElements - an out parameter which will be initialized
408   ///   with the number of elements allocated, or zero if there is no
409   ///   cookie
410   /// \param AllocPtr - an out parameter which will be initialized
411   ///   with a char* pointing to the address returned by the allocation
412   ///   function
413   /// \param CookieSize - an out parameter which will be initialized
414   ///   with the size of the cookie, or zero if there is no cookie
415   virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
416                                const CXXDeleteExpr *expr,
417                                QualType ElementType, llvm::Value *&NumElements,
418                                llvm::Value *&AllocPtr, CharUnits &CookieSize);
419
420   /// Return whether the given global decl needs a VTT parameter.
421   virtual bool NeedsVTTParameter(GlobalDecl GD);
422
423 protected:
424   /// Returns the extra size required in order to store the array
425   /// cookie for the given type.  Assumes that an array cookie is
426   /// required.
427   virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
428
429   /// Reads the array cookie for an allocation which is known to have one.
430   /// This is called by the standard implementation of ReadArrayCookie.
431   ///
432   /// \param ptr - a pointer to the allocation made for an array, as a char*
433   /// \param cookieSize - the computed cookie size of an array
434   ///
435   /// Other parameters are as above.
436   ///
437   /// \return a size_t
438   virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
439                                            llvm::Value *ptr,
440                                            CharUnits cookieSize);
441
442 public:
443
444   /*************************** Static local guards ****************************/
445
446   /// Emits the guarded initializer and destructor setup for the given
447   /// variable, given that it couldn't be emitted as a constant.
448   /// If \p PerformInit is false, the initialization has been folded to a
449   /// constant and should not be performed.
450   ///
451   /// The variable may be:
452   ///   - a static local variable
453   ///   - a static data member of a class template instantiation
454   virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
455                                llvm::GlobalVariable *DeclPtr,
456                                bool PerformInit) = 0;
457
458   /// Emit code to force the execution of a destructor during global
459   /// teardown.  The default implementation of this uses atexit.
460   ///
461   /// \param dtor - a function taking a single pointer argument
462   /// \param addr - a pointer to pass to the destructor function.
463   virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
464                                   llvm::Constant *dtor, llvm::Constant *addr);
465
466   /*************************** thread_local initialization ********************/
467
468   /// Emits ABI-required functions necessary to initialize thread_local
469   /// variables in this translation unit.
470   ///
471   /// \param Decls The thread_local declarations in this translation unit.
472   /// \param InitFunc If this translation unit contains any non-constant
473   ///        initialization or non-trivial destruction for thread_local
474   ///        variables, a function to perform the initialization. Otherwise, 0.
475   virtual void EmitThreadLocalInitFuncs(
476       llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
477       llvm::Function *InitFunc);
478
479   /// Emit a reference to a non-local thread_local variable (including
480   /// triggering the initialization of all thread_local variables in its
481   /// translation unit).
482   virtual LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
483                                             const DeclRefExpr *DRE);
484 };
485
486 // Create an instance of a C++ ABI class:
487
488 /// Creates an Itanium-family ABI.
489 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
490
491 /// Creates a Microsoft-family ABI.
492 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
493
494 }
495 }
496
497 #endif