1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides an abstract class for C++ code generation. Concrete subclasses
10// of this implement code generation for specific C++ ABIs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LIB_CIR_CIRGENCXXABI_H
15#define LLVM_CLANG_LIB_CIR_CIRGENCXXABI_H
16
17#include "CIRGenCall.h"
18#include "CIRGenCleanup.h"
19#include "CIRGenFunction.h"
20#include "CIRGenModule.h"
21
22#include "clang/AST/Mangle.h"
23
24namespace clang::CIRGen {
25
26/// Implements C++ ABI-specific code generation functions.
27class CIRGenCXXABI {
28protected:
29 CIRGenModule &cgm;
30 std::unique_ptr<clang::MangleContext> mangleContext;
31
32 virtual bool requiresArrayCookie(const CXXNewExpr *e);
33
34 virtual bool constructorsAndDestructorsReturnThis() const {
35 return cgm.getCodeGenOpts().CtorDtorReturnThis;
36 }
37
38public:
39 // TODO(cir): make this protected when target-specific CIRGenCXXABIs are
40 // implemented.
41 CIRGenCXXABI(CIRGenModule &cgm)
42 : cgm(cgm), mangleContext(cgm.getASTContext().createMangleContext()) {}
43 virtual ~CIRGenCXXABI();
44
45 void setCXXABIThisValue(CIRGenFunction &cgf, mlir::Value thisPtr);
46
47 /// Emit the code to initialize hidden members required to handle virtual
48 /// inheritance, if needed by the ABI.
49 virtual void
50 initializeHiddenVirtualInheritanceMembers(CIRGenFunction &cgf,
51 const CXXRecordDecl *rd) {}
52
53 /// Emit a single constructor/destructor with the gen type from a C++
54 /// constructor/destructor Decl.
55 virtual void emitCXXStructor(clang::GlobalDecl gd) = 0;
56
57 virtual mlir::Value
58 getVirtualBaseClassOffset(mlir::Location loc, CIRGenFunction &cgf,
59 Address thisAddr, const CXXRecordDecl *classDecl,
60 const CXXRecordDecl *baseClassDecl) = 0;
61
62 virtual mlir::Value emitDynamicCast(CIRGenFunction &cgf, mlir::Location loc,
63 QualType srcRecordTy,
64 QualType destRecordTy,
65 cir::PointerType destCIRTy,
66 bool isRefCast, Address src) = 0;
67
68 virtual cir::MethodAttr buildVirtualMethodAttr(cir::MethodType methodTy,
69 const CXXMethodDecl *md) = 0;
70
71public:
72 /// Similar to AddedStructorArgs, but only notes the number of additional
73 /// arguments.
74 struct AddedStructorArgCounts {
75 unsigned prefix = 0;
76 unsigned suffix = 0;
77 AddedStructorArgCounts() = default;
78 AddedStructorArgCounts(unsigned p, unsigned s) : prefix(p), suffix(s) {}
79 static AddedStructorArgCounts withPrefix(unsigned n) { return {n, 0}; }
80 static AddedStructorArgCounts withSuffix(unsigned n) { return {0, n}; }
81 };
82
83 /// Additional implicit arguments to add to the beginning (Prefix) and end
84 /// (Suffix) of a constructor / destructor arg list.
85 ///
86 /// Note that Prefix should actually be inserted *after* the first existing
87 /// arg; `this` arguments always come first.
88 struct AddedStructorArgs {
89 struct Arg {
90 mlir::Value value;
91 QualType type;
92 };
93 llvm::SmallVector<Arg, 1> prefix;
94 llvm::SmallVector<Arg, 1> suffix;
95 AddedStructorArgs() = default;
96 AddedStructorArgs(llvm::SmallVector<Arg, 1> p, llvm::SmallVector<Arg, 1> s)
97 : prefix(std::move(p)), suffix(std::move(s)) {}
98 static AddedStructorArgs withPrefix(llvm::SmallVector<Arg, 1> args) {
99 return {std::move(args), {}};
100 }
101 static AddedStructorArgs withSuffix(llvm::SmallVector<Arg, 1> args) {
102 return {{}, std::move(args)};
103 }
104 };
105
106 /// Build the signature of the given constructor or destructor vairant by
107 /// adding any required parameters. For convenience, ArgTys has been
108 /// initialized with the type of 'this'.
109 virtual AddedStructorArgCounts
110 buildStructorSignature(GlobalDecl gd,
111 llvm::SmallVectorImpl<CanQualType> &argTys) = 0;
112
113 AddedStructorArgCounts
114 addImplicitConstructorArgs(CIRGenFunction &cgf, const CXXConstructorDecl *d,
115 CXXCtorType type, bool forVirtualBase,
116 bool delegating, CallArgList &args);
117
118 clang::ImplicitParamDecl *getThisDecl(CIRGenFunction &cgf) {
119 return cgf.cxxabiThisDecl;
120 }
121
122 virtual AddedStructorArgs
123 getImplicitConstructorArgs(CIRGenFunction &cgf, const CXXConstructorDecl *d,
124 CXXCtorType type, bool forVirtualBase,
125 bool delegating) = 0;
126
127 /// Emit the ABI-specific prolog for the function
128 virtual void emitInstanceFunctionProlog(SourceLocation loc,
129 CIRGenFunction &cgf) = 0;
130
131 virtual void emitRethrow(CIRGenFunction &cgf, bool isNoReturn) = 0;
132 virtual void emitThrow(CIRGenFunction &cgf, const CXXThrowExpr *e) = 0;
133
134 /// Determine whether it's possible to emit a vtable for \p RD, even
135 /// though we do not know that the vtable has been marked as used by semantic
136 /// analysis.
137 virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const = 0;
138
139 virtual void emitBadCastCall(CIRGenFunction &cgf, mlir::Location loc) = 0;
140
141 virtual mlir::Attribute getAddrOfRTTIDescriptor(mlir::Location loc,
142 QualType ty) = 0;
143
144 /// Get the type of the implicit "this" parameter used by a method. May return
145 /// zero if no specific type is applicable, e.g. if the ABI expects the "this"
146 /// parameter to point to some artificial offset in a complete object due to
147 /// vbases being reordered.
148 virtual const clang::CXXRecordDecl *
149 getThisArgumentTypeForMethod(const clang::CXXMethodDecl *md) {
150 return md->getParent();
151 }
152
153 /// Return whether the given global decl needs a VTT (virtual table table)
154 /// parameter.
155 virtual bool needsVTTParameter(clang::GlobalDecl gd) { return false; }
156
157 /// Perform ABI-specific "this" argument adjustment required prior to
158 /// a call of a virtual function.
159 /// The "VirtualCall" argument is true iff the call itself is virtual.
160 virtual Address adjustThisArgumentForVirtualFunctionCall(CIRGenFunction &cgf,
161 clang::GlobalDecl gd,
162 Address thisPtr,
163 bool virtualCall) {
164 return thisPtr;
165 }
166
167 /// Build a parameter variable suitable for 'this'.
168 void buildThisParam(CIRGenFunction &cgf, FunctionArgList &params);
169
170 /// Loads the incoming C++ this pointer as it was passed by the caller.
171 mlir::Value loadIncomingCXXThis(CIRGenFunction &cgf);
172
173 virtual CatchTypeInfo
174 getAddrOfCXXCatchHandlerType(mlir::Location loc, QualType ty,
175 QualType catchHandlerType) = 0;
176 virtual CatchTypeInfo getCatchAllTypeInfo();
177 virtual bool shouldTypeidBeNullChecked(QualType srcTy) = 0;
178 virtual mlir::Value emitTypeid(CIRGenFunction &cgf, QualType srcTy,
179 Address thisPtr, mlir::Type typeInfoPtrTy) = 0;
180 virtual void emitBadTypeidCall(CIRGenFunction &cgf, mlir::Location loc) = 0;
181
182 /// Get the implicit (second) parameter that comes after the "this" pointer,
183 /// or nullptr if there is isn't one.
184 virtual mlir::Value getCXXDestructorImplicitParam(CIRGenFunction &cgf,
185 const CXXDestructorDecl *dd,
186 CXXDtorType type,
187 bool forVirtualBase,
188 bool delegating) = 0;
189
190 /// Emit constructor variants required by this ABI.
191 virtual void emitCXXConstructors(const clang::CXXConstructorDecl *d) = 0;
192
193 /// Emit dtor variants required by this ABI.
194 virtual void emitCXXDestructors(const clang::CXXDestructorDecl *d) = 0;
195
196 virtual void emitDestructorCall(CIRGenFunction &cgf,
197 const CXXDestructorDecl *dd, CXXDtorType type,
198 bool forVirtualBase, bool delegating,
199 Address thisAddr, QualType thisTy) = 0;
200
201 /// Emit code to force the execution of a destructor during global
202 /// teardown. The default implementation of this uses atexit.
203 ///
204 /// \param dtor - a function taking a single pointer argument
205 /// \param addr - a pointer to pass to the destructor function.
206 virtual void registerGlobalDtor(const VarDecl *vd, cir::FuncOp dtor,
207 mlir::Value addr) = 0;
208
209 virtual void emitVirtualObjectDelete(CIRGenFunction &cgf,
210 const CXXDeleteExpr *de, Address ptr,
211 QualType elementType,
212 const CXXDestructorDecl *dtor) = 0;
213
214 virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
215 FunctionArgList &args) const = 0;
216
217 /// Checks if ABI requires extra virtual offset for vtable field.
218 virtual bool
219 isVirtualOffsetNeededForVTableField(CIRGenFunction &cgf,
220 CIRGenFunction::VPtr vptr) = 0;
221
222 /// Emits the VTable definitions required for the given record type.
223 virtual void emitVTableDefinitions(CIRGenVTables &cgvt,
224 const CXXRecordDecl *rd) = 0;
225
226 using DeleteOrMemberCallExpr =
227 llvm::PointerUnion<const CXXDeleteExpr *, const CXXMemberCallExpr *>;
228
229 virtual mlir::Value emitVirtualDestructorCall(CIRGenFunction &cgf,
230 const CXXDestructorDecl *dtor,
231 CXXDtorType dtorType,
232 Address thisAddr,
233 DeleteOrMemberCallExpr e) = 0;
234
235 /// Emit any tables needed to implement virtual inheritance. For Itanium,
236 /// this emits virtual table tables.
237 virtual void emitVirtualInheritanceTables(const CXXRecordDecl *rd) = 0;
238
239 /// Returns true if the thunk should be exported.
240 virtual bool exportThunk() = 0;
241
242 /// Set the linkage and visibility of a thunk function.
243 virtual void setThunkLinkage(cir::FuncOp thunk, bool forVTable, GlobalDecl gd,
244 bool returnAdjustment) = 0;
245
246 /// Perform adjustment on the 'this' pointer for a thunk.
247 /// Returns the adjusted 'this' pointer value.
248 virtual mlir::Value
249 performThisAdjustment(CIRGenFunction &cgf, Address thisAddr,
250 const CXXRecordDecl *unadjustedClass,
251 const ThunkInfo &ti) = 0;
252
253 /// Perform adjustment on a return pointer for a thunk (covariant returns).
254 /// Returns the adjusted return pointer value.
255 virtual mlir::Value
256 performReturnAdjustment(CIRGenFunction &cgf, Address ret,
257 const CXXRecordDecl *unadjustedClass,
258 const ReturnAdjustment &ra) = 0;
259
260 /// Adjust call arguments for a destructor thunk.
261 virtual void adjustCallArgsForDestructorThunk(CIRGenFunction &cgf,
262 GlobalDecl globalDecl,
263 CallArgList &callArgs) {}
264
265 /// Emit a return from a thunk.
266 virtual void emitReturnFromThunk(CIRGenFunction &cgf, RValue rv,
267 QualType resultType);
268
269 /// Returns true if the given destructor type should be emitted as a linkonce
270 /// delegating thunk, regardless of whether the dtor is defined in this TU or
271 /// not.
272 virtual bool useThunkForDtorVariant(const CXXDestructorDecl *dtor,
273 CXXDtorType dt) const = 0;
274
275 virtual cir::GlobalLinkageKind
276 getCXXDestructorLinkage(GVALinkage linkage, const CXXDestructorDecl *dtor,
277 CXXDtorType dt) const;
278
279 /// Get the address of the vtable for the given record decl which should be
280 /// used for the vptr at the given offset in RD.
281 virtual cir::GlobalOp getAddrOfVTable(const CXXRecordDecl *rd,
282 CharUnits vptrOffset) = 0;
283
284 /// Build a virtual function pointer in the ABI-specific way.
285 virtual CIRGenCallee getVirtualFunctionPointer(CIRGenFunction &cgf,
286 clang::GlobalDecl gd,
287 Address thisAddr,
288 mlir::Type ty,
289 SourceLocation loc) = 0;
290
291 /// Get the address point of the vtable for the given base subobject.
292 virtual mlir::Value
293 getVTableAddressPoint(BaseSubobject base,
294 const CXXRecordDecl *vtableClass) = 0;
295
296 /// Get the address point of the vtable for the given base subobject as a
297 /// constant suitable for a global initializer.
298 virtual cir::GlobalViewAttr
299 getVTableAddressPointAttr(BaseSubobject base,
300 const CXXRecordDecl *vtableClass) = 0;
301
302 /// Get the address point of the vtable for the given base subobject while
303 /// building a constructor or a destructor.
304 virtual mlir::Value getVTableAddressPointInStructor(
305 CIRGenFunction &cgf, const CXXRecordDecl *vtableClass, BaseSubobject base,
306 const CXXRecordDecl *nearestVBase) = 0;
307
308 virtual llvm::StringRef getPureVirtualCallName() = 0;
309 virtual llvm::StringRef getDeletedVirtualCallName() = 0;
310
311 /// Insert any ABI-specific implicit parameters into the parameter list for a
312 /// function. This generally involves extra data for constructors and
313 /// destructors.
314 ///
315 /// ABIs may also choose to override the return type, which has been
316 /// initialized with the type of 'this' if HasThisReturn(CGF.CurGD) is true or
317 /// the formal return type of the function otherwise.
318 virtual void addImplicitStructorParams(CIRGenFunction &cgf,
319 clang::QualType &resTy,
320 FunctionArgList &params) = 0;
321
322 /// Checks if ABI requires to initialize vptrs for given dynamic class.
323 virtual bool
324 doStructorsInitializeVPtrs(const clang::CXXRecordDecl *vtableClass) = 0;
325
326 /// Returns true if the given constructor or destructor is one of the kinds
327 /// that the ABI says returns 'this' (only applies when called non-virtually
328 /// for destructors).
329 ///
330 /// There currently is no way to indicate if a destructor returns 'this' when
331 /// called virtually, and CIR generation does not support this case.
332 virtual bool hasThisReturn(clang::GlobalDecl gd) const {
333 if (isa<CXXConstructorDecl>(Val: gd.getDecl()) ||
334 (isa<CXXDestructorDecl>(Val: gd.getDecl()) &&
335 gd.getDtorType() != Dtor_Deleting))
336 return constructorsAndDestructorsReturnThis();
337 return false;
338 }
339
340 virtual bool hasMostDerivedReturn(clang::GlobalDecl gd) const {
341 return false;
342 }
343
344 /// Returns true if the target allows calling a function through a pointer
345 /// with a different signature than the actual function (or equivalently,
346 /// bitcasting a function or function pointer to a different function type).
347 /// In principle in the most general case this could depend on the target, the
348 /// calling convention, and the actual types of the arguments and return
349 /// value. Here it just means whether the signature mismatch could *ever* be
350 /// allowed; in other words, does the target do strict checking of signatures
351 /// for all calls.
352 virtual bool canCallMismatchedFunctionType() const { return true; }
353
354 /// Gets the mangle context.
355 clang::MangleContext &getMangleContext() { return *mangleContext; }
356
357 clang::ImplicitParamDecl *&getStructorImplicitParamDecl(CIRGenFunction &cgf) {
358 return cgf.cxxStructorImplicitParamDecl;
359 }
360
361 mlir::Value getStructorImplicitParamValue(CIRGenFunction &cgf) {
362 return cgf.cxxStructorImplicitParamValue;
363 }
364
365 void setStructorImplicitParamValue(CIRGenFunction &cgf, mlir::Value val) {
366 cgf.cxxStructorImplicitParamValue = val;
367 }
368
369 /**************************** Array cookies ******************************/
370
371 /// Returns the extra size required in order to store the array
372 /// cookie for the given new-expression. May return 0 to indicate that no
373 /// array cookie is required.
374 ///
375 /// Several cases are filtered out before this method is called:
376 /// - non-array allocations never need a cookie
377 /// - calls to \::operator new(size_t, void*) never need a cookie
378 ///
379 /// \param e - the new-expression being allocated.
380 virtual CharUnits getArrayCookieSize(const CXXNewExpr *e);
381
382 /// Initialize the array cookie for the given allocation.
383 ///
384 /// \param newPtr - a char* which is the presumed-non-null
385 /// return value of the allocation function
386 /// \param numElements - the computed number of elements,
387 /// potentially collapsed from the multidimensional array case;
388 /// always a size_t
389 /// \param elementType - the base element allocated type,
390 /// i.e. the allocated type after stripping all array types
391 virtual Address initializeArrayCookie(CIRGenFunction &cgf, Address newPtr,
392 mlir::Value numElements,
393 const CXXNewExpr *e,
394 QualType elementType) = 0;
395
396 /// Return true if the given member pointer can be zero-initialized
397 /// (in the C++ sense).
398 virtual bool isZeroInitializable(const MemberPointerType *mpt) = 0;
399
400protected:
401 /// Returns the extra size required in order to store the array
402 /// cookie for the given type. Assumes that an array cookie is
403 /// required.
404 virtual CharUnits getArrayCookieSizeImpl(QualType elementType) = 0;
405};
406
407/// Creates and Itanium-family ABI
408CIRGenCXXABI *CreateCIRGenItaniumCXXABI(CIRGenModule &cgm);
409
410/// Creates Microsoft ABI
411CIRGenCXXABI *CreateCIRGenMicrosoftCXXABI(CIRGenModule &cgm);
412
413} // namespace clang::CIRGen
414
415#endif
416