]> granicus.if.org Git - clang/blob - lib/CodeGen/CGCXXABI.h
Push record return type classification into CGCXXABI
[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   /// 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 how an argument of the given record type should be passed.
116   virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
117
118   /// Returns true if the implicit 'sret' parameter comes after the implicit
119   /// 'this' parameter of C++ instance methods.
120   virtual bool isSRetParameterAfterThis() const { return false; }
121
122   /// Find the LLVM type used to represent the given member pointer
123   /// type.
124   virtual llvm::Type *
125   ConvertMemberPointerType(const MemberPointerType *MPT);
126
127   /// Load a member function from an object and a member function
128   /// pointer.  Apply the this-adjustment and set 'This' to the
129   /// adjusted value.
130   virtual llvm::Value *EmitLoadOfMemberFunctionPointer(
131       CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
132       llvm::Value *MemPtr, const MemberPointerType *MPT);
133
134   /// Calculate an l-value from an object and a data member pointer.
135   virtual llvm::Value *
136   EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
137                                llvm::Value *Base, llvm::Value *MemPtr,
138                                const MemberPointerType *MPT);
139
140   /// Perform a derived-to-base, base-to-derived, or bitcast member
141   /// pointer conversion.
142   virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
143                                                    const CastExpr *E,
144                                                    llvm::Value *Src);
145
146   /// Perform a derived-to-base, base-to-derived, or bitcast member
147   /// pointer conversion on a constant value.
148   virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
149                                                       llvm::Constant *Src);
150
151   /// Return true if the given member pointer can be zero-initialized
152   /// (in the C++ sense) with an LLVM zeroinitializer.
153   virtual bool isZeroInitializable(const MemberPointerType *MPT);
154
155   /// Create a null member pointer of the given type.
156   virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
157
158   /// Create a member pointer for the given method.
159   virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
160
161   /// Create a member pointer for the given field.
162   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
163                                                 CharUnits offset);
164
165   /// Create a member pointer for the given member pointer constant.
166   virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
167
168   /// Emit a comparison between two member pointers.  Returns an i1.
169   virtual llvm::Value *
170   EmitMemberPointerComparison(CodeGenFunction &CGF,
171                               llvm::Value *L,
172                               llvm::Value *R,
173                               const MemberPointerType *MPT,
174                               bool Inequality);
175
176   /// Determine if a member pointer is non-null.  Returns an i1.
177   virtual llvm::Value *
178   EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
179                              llvm::Value *MemPtr,
180                              const MemberPointerType *MPT);
181
182 protected:
183   /// A utility method for computing the offset required for the given
184   /// base-to-derived or derived-to-base member-pointer conversion.
185   /// Does not handle virtual conversions (in case we ever fully
186   /// support an ABI that allows this).  Returns null if no adjustment
187   /// is required.
188   llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
189
190   /// \brief Computes the non-virtual adjustment needed for a member pointer
191   /// conversion along an inheritance path stored in an APValue.  Unlike
192   /// getMemberPointerAdjustment(), the adjustment can be negative if the path
193   /// is from a derived type to a base type.
194   CharUnits getMemberPointerPathAdjustment(const APValue &MP);
195
196 public:
197   /// Adjust the given non-null pointer to an object of polymorphic
198   /// type to point to the complete object.
199   ///
200   /// The IR type of the result should be a pointer but is otherwise
201   /// irrelevant.
202   virtual llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
203                                               llvm::Value *ptr,
204                                               QualType type) = 0;
205
206   virtual llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
207                                                  llvm::Value *This,
208                                                  const CXXRecordDecl *ClassDecl,
209                                         const CXXRecordDecl *BaseClassDecl) = 0;
210
211   /// Build the signature of the given constructor variant by adding
212   /// any required parameters.  For convenience, ArgTys has been initialized
213   /// with the type of 'this' and ResTy has been initialized with the type of
214   /// 'this' if HasThisReturn(GlobalDecl(Ctor, T)) is true or 'void' otherwise
215   /// (although both may be changed by the ABI).
216   ///
217   /// If there are ever any ABIs where the implicit parameters are
218   /// intermixed with the formal parameters, we can address those
219   /// then.
220   virtual void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
221                                          CXXCtorType T,
222                                          CanQualType &ResTy,
223                                SmallVectorImpl<CanQualType> &ArgTys) = 0;
224
225   virtual llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
226                                                           const CXXRecordDecl *RD);
227
228   /// Emit the code to initialize hidden members required
229   /// to handle virtual inheritance, if needed by the ABI.
230   virtual void
231   initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
232                                             const CXXRecordDecl *RD) {}
233
234   /// Emit constructor variants required by this ABI.
235   virtual void EmitCXXConstructors(const CXXConstructorDecl *D) = 0;
236
237   /// Build the signature of the given destructor variant by adding
238   /// any required parameters.  For convenience, ArgTys has been initialized
239   /// with the type of 'this' and ResTy has been initialized with the type of
240   /// 'this' if HasThisReturn(GlobalDecl(Dtor, T)) is true or 'void' otherwise
241   /// (although both may be changed by the ABI).
242   virtual void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
243                                         CXXDtorType T,
244                                         CanQualType &ResTy,
245                                SmallVectorImpl<CanQualType> &ArgTys) = 0;
246
247   /// Returns true if the given destructor type should be emitted as a linkonce
248   /// delegating thunk, regardless of whether the dtor is defined in this TU or
249   /// not.
250   virtual bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
251                                       CXXDtorType DT) const = 0;
252
253   /// Emit destructor variants required by this ABI.
254   virtual void EmitCXXDestructors(const CXXDestructorDecl *D) = 0;
255
256   /// Get the type of the implicit "this" parameter used by a method. May return
257   /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
258   /// parameter to point to some artificial offset in a complete object due to
259   /// vbases being reordered.
260   virtual const CXXRecordDecl *
261   getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
262     return MD->getParent();
263   }
264
265   /// Perform ABI-specific "this" argument adjustment required prior to
266   /// a call of a virtual function.
267   /// The "VirtualCall" argument is true iff the call itself is virtual.
268   virtual llvm::Value *
269   adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
270                                            llvm::Value *This,
271                                            bool VirtualCall) {
272     return This;
273   }
274
275   /// Build a parameter variable suitable for 'this'.
276   void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params);
277
278   /// Insert any ABI-specific implicit parameters into the parameter list for a
279   /// function.  This generally involves extra data for constructors and
280   /// destructors.
281   ///
282   /// ABIs may also choose to override the return type, which has been
283   /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
284   /// the formal return type of the function otherwise.
285   virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
286                                          FunctionArgList &Params) = 0;
287
288   /// Perform ABI-specific "this" parameter adjustment in a virtual function
289   /// prologue.
290   virtual llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
291       CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
292     return This;
293   }
294
295   /// Emit the ABI-specific prolog for the function.
296   virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF) = 0;
297
298   /// Add any ABI-specific implicit arguments needed to call a constructor.
299   ///
300   /// \return The number of args added to the call, which is typically zero or
301   /// one.
302   virtual unsigned
303   addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
304                              CXXCtorType Type, bool ForVirtualBase,
305                              bool Delegating, CallArgList &Args) = 0;
306
307   /// Emit the destructor call.
308   virtual void EmitDestructorCall(CodeGenFunction &CGF,
309                                   const CXXDestructorDecl *DD, CXXDtorType Type,
310                                   bool ForVirtualBase, bool Delegating,
311                                   llvm::Value *This) = 0;
312
313   /// Emits the VTable definitions required for the given record type.
314   virtual void emitVTableDefinitions(CodeGenVTables &CGVT,
315                                      const CXXRecordDecl *RD) = 0;
316
317   /// Get the address point of the vtable for the given base subobject while
318   /// building a constructor or a destructor. On return, NeedsVirtualOffset
319   /// tells if a virtual base adjustment is needed in order to get the offset
320   /// of the base subobject.
321   virtual llvm::Value *getVTableAddressPointInStructor(
322       CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base,
323       const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) = 0;
324
325   /// Get the address point of the vtable for the given base subobject while
326   /// building a constexpr.
327   virtual llvm::Constant *
328   getVTableAddressPointForConstExpr(BaseSubobject Base,
329                                     const CXXRecordDecl *VTableClass) = 0;
330
331   /// Get the address of the vtable for the given record decl which should be
332   /// used for the vptr at the given offset in RD.
333   virtual llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
334                                                 CharUnits VPtrOffset) = 0;
335
336   /// Build a virtual function pointer in the ABI-specific way.
337   virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF,
338                                                  GlobalDecl GD,
339                                                  llvm::Value *This,
340                                                  llvm::Type *Ty) = 0;
341
342   /// Emit the ABI-specific virtual destructor call.
343   virtual void EmitVirtualDestructorCall(CodeGenFunction &CGF,
344                                          const CXXDestructorDecl *Dtor,
345                                          CXXDtorType DtorType,
346                                          SourceLocation CallLoc,
347                                          llvm::Value *This) = 0;
348
349   virtual void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF,
350                                                 GlobalDecl GD,
351                                                 CallArgList &CallArgs) {}
352
353   /// Emit any tables needed to implement virtual inheritance.  For Itanium,
354   /// this emits virtual table tables.  For the MSVC++ ABI, this emits virtual
355   /// base tables.
356   virtual void emitVirtualInheritanceTables(const CXXRecordDecl *RD) = 0;
357
358   virtual void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) = 0;
359
360   virtual llvm::Value *performThisAdjustment(CodeGenFunction &CGF,
361                                              llvm::Value *This,
362                                              const ThisAdjustment &TA) = 0;
363
364   virtual llvm::Value *performReturnAdjustment(CodeGenFunction &CGF,
365                                                llvm::Value *Ret,
366                                                const ReturnAdjustment &RA) = 0;
367
368   virtual void EmitReturnFromThunk(CodeGenFunction &CGF,
369                                    RValue RV, QualType ResultType);
370
371   /// Gets the pure virtual member call function.
372   virtual StringRef GetPureVirtualCallName() = 0;
373
374   /// Gets the deleted virtual member call name.
375   virtual StringRef GetDeletedVirtualCallName() = 0;
376
377   /// \brief Returns true iff static data members that are initialized in the
378   /// class definition should have linkonce linkage.
379   virtual bool isInlineInitializedStaticDataMemberLinkOnce() { return false; }
380
381   /**************************** Array cookies ******************************/
382
383   /// Returns the extra size required in order to store the array
384   /// cookie for the given new-expression.  May return 0 to indicate that no
385   /// array cookie is required.
386   ///
387   /// Several cases are filtered out before this method is called:
388   ///   - non-array allocations never need a cookie
389   ///   - calls to \::operator new(size_t, void*) never need a cookie
390   ///
391   /// \param expr - the new-expression being allocated.
392   virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr);
393
394   /// Initialize the array cookie for the given allocation.
395   ///
396   /// \param NewPtr - a char* which is the presumed-non-null
397   ///   return value of the allocation function
398   /// \param NumElements - the computed number of elements,
399   ///   potentially collapsed from the multidimensional array case;
400   ///   always a size_t
401   /// \param ElementType - the base element allocated type,
402   ///   i.e. the allocated type after stripping all array types
403   virtual llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
404                                              llvm::Value *NewPtr,
405                                              llvm::Value *NumElements,
406                                              const CXXNewExpr *expr,
407                                              QualType ElementType);
408
409   /// Reads the array cookie associated with the given pointer,
410   /// if it has one.
411   ///
412   /// \param Ptr - a pointer to the first element in the array
413   /// \param ElementType - the base element type of elements of the array
414   /// \param NumElements - an out parameter which will be initialized
415   ///   with the number of elements allocated, or zero if there is no
416   ///   cookie
417   /// \param AllocPtr - an out parameter which will be initialized
418   ///   with a char* pointing to the address returned by the allocation
419   ///   function
420   /// \param CookieSize - an out parameter which will be initialized
421   ///   with the size of the cookie, or zero if there is no cookie
422   virtual void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
423                                const CXXDeleteExpr *expr,
424                                QualType ElementType, llvm::Value *&NumElements,
425                                llvm::Value *&AllocPtr, CharUnits &CookieSize);
426
427   /// Return whether the given global decl needs a VTT parameter.
428   virtual bool NeedsVTTParameter(GlobalDecl GD);
429
430 protected:
431   /// Returns the extra size required in order to store the array
432   /// cookie for the given type.  Assumes that an array cookie is
433   /// required.
434   virtual CharUnits getArrayCookieSizeImpl(QualType elementType);
435
436   /// Reads the array cookie for an allocation which is known to have one.
437   /// This is called by the standard implementation of ReadArrayCookie.
438   ///
439   /// \param ptr - a pointer to the allocation made for an array, as a char*
440   /// \param cookieSize - the computed cookie size of an array
441   ///
442   /// Other parameters are as above.
443   ///
444   /// \return a size_t
445   virtual llvm::Value *readArrayCookieImpl(CodeGenFunction &IGF,
446                                            llvm::Value *ptr,
447                                            CharUnits cookieSize);
448
449 public:
450
451   /*************************** Static local guards ****************************/
452
453   /// Emits the guarded initializer and destructor setup for the given
454   /// variable, given that it couldn't be emitted as a constant.
455   /// If \p PerformInit is false, the initialization has been folded to a
456   /// constant and should not be performed.
457   ///
458   /// The variable may be:
459   ///   - a static local variable
460   ///   - a static data member of a class template instantiation
461   virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
462                                llvm::GlobalVariable *DeclPtr,
463                                bool PerformInit) = 0;
464
465   /// Emit code to force the execution of a destructor during global
466   /// teardown.  The default implementation of this uses atexit.
467   ///
468   /// \param dtor - a function taking a single pointer argument
469   /// \param addr - a pointer to pass to the destructor function.
470   virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
471                                   llvm::Constant *dtor, llvm::Constant *addr);
472
473   /*************************** thread_local initialization ********************/
474
475   /// Emits ABI-required functions necessary to initialize thread_local
476   /// variables in this translation unit.
477   ///
478   /// \param Decls The thread_local declarations in this translation unit.
479   /// \param InitFunc If this translation unit contains any non-constant
480   ///        initialization or non-trivial destruction for thread_local
481   ///        variables, a function to perform the initialization. Otherwise, 0.
482   virtual void EmitThreadLocalInitFuncs(
483       llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
484       llvm::Function *InitFunc);
485
486   /// Emit a reference to a non-local thread_local variable (including
487   /// triggering the initialization of all thread_local variables in its
488   /// translation unit).
489   virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
490                                               const VarDecl *VD,
491                                               QualType LValType);
492
493   /**************************** RTTI Uniqueness ******************************/
494
495 protected:
496   /// Returns true if the ABI requires RTTI type_info objects to be unique
497   /// across a program.
498   virtual bool shouldRTTIBeUnique() { return true; }
499
500 public:
501   /// What sort of unique-RTTI behavior should we use?
502   enum RTTIUniquenessKind {
503     /// We are guaranteeing, or need to guarantee, that the RTTI string
504     /// is unique.
505     RUK_Unique,
506
507     /// We are not guaranteeing uniqueness for the RTTI string, so we
508     /// can demote to hidden visibility but must use string comparisons.
509     RUK_NonUniqueHidden,
510
511     /// We are not guaranteeing uniqueness for the RTTI string, so we
512     /// have to use string comparisons, but we also have to emit it with
513     /// non-hidden visibility.
514     RUK_NonUniqueVisible
515   };
516
517   /// Return the required visibility status for the given type and linkage in
518   /// the current ABI.
519   RTTIUniquenessKind
520   classifyRTTIUniqueness(QualType CanTy,
521                          llvm::GlobalValue::LinkageTypes Linkage);
522 };
523
524 // Create an instance of a C++ ABI class:
525
526 /// Creates an Itanium-family ABI.
527 CGCXXABI *CreateItaniumCXXABI(CodeGenModule &CGM);
528
529 /// Creates a Microsoft-family ABI.
530 CGCXXABI *CreateMicrosoftCXXABI(CodeGenModule &CGM);
531
532 }
533 }
534
535 #endif