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