blob: 7e3a47d9131ed0540f71b45300797a0f37900e0d [file] [log] [blame]
Charles Davis74ce8592010-06-09 23:25:41 +00001//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
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//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davis74ce8592010-06-09 23:25:41 +000011// The class in this file generates structures that follow the Microsoft
12// Visual C++ ABI, which is actually not very well documented at all outside
13// of Microsoft.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGCXXABI.h"
18#include "CodeGenModule.h"
Reid Kleckner7810af02013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davis74ce8592010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis53c59df2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000032public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000034
Stephen Lin9dc6eef2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000037 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
38 // Structures that are not C++03 PODs are always indirect.
39 return !RD->isPOD();
40 }
41
42 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos2ce88ef2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000049 // No known support for deleted functions in MSVC yet, so this choice is
50 // arbitrary.
51 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000052
John McCall82fb8922012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000057 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
58 llvm::Value *This,
59 const CXXRecordDecl *ClassDecl,
60 const CXXRecordDecl *BaseClassDecl);
61
John McCall5d865c322010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000066
Reid Kleckner7810af02013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000069
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000070 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
71 const CXXRecordDecl *RD);
72
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000073 void EmitCXXConstructors(const CXXConstructorDecl *D);
74
Reid Klecknere7de47e2013-07-22 13:51:44 +000075 // Background on MSVC destructors
76 // ==============================
77 //
78 // Both Itanium and MSVC ABIs have destructor variants. The variant names
79 // roughly correspond in the following way:
80 // Itanium Microsoft
81 // Base -> no name, just ~Class
82 // Complete -> vbase destructor
83 // Deleting -> scalar deleting destructor
84 // vector deleting destructor
85 //
86 // The base and complete destructors are the same as in Itanium, although the
87 // complete destructor does not accept a VTT parameter when there are virtual
88 // bases. A separate mechanism involving vtordisps is used to ensure that
89 // virtual methods of destroyed subobjects are not called.
90 //
91 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
92 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
93 // pointer points to an array. The scalar deleting destructor assumes that
94 // bit 2 is zero, and therefore does not contain a loop.
95 //
96 // For virtual destructors, only one entry is reserved in the vftable, and it
97 // always points to the vector deleting destructor. The vector deleting
98 // destructor is the most general, so it can be used to destroy objects in
99 // place, delete single heap objects, or delete arrays.
100 //
101 // A TU defining a non-inline destructor is only guaranteed to emit a base
102 // destructor, and all of the other variants are emitted on an as-needed basis
103 // in COMDATs. Because a non-base destructor can be emitted in a TU that
104 // lacks a definition for the destructor, non-base destructors must always
105 // delegate to or alias the base destructor.
106
107 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000108 CXXDtorType Type,
109 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000110 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000111
Reid Klecknere7de47e2013-07-22 13:51:44 +0000112 /// Non-base dtors should be emitted as delegating thunks in this ABI.
113 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
114 CXXDtorType DT) const {
115 return DT != Dtor_Base;
116 }
117
118 void EmitCXXDestructors(const CXXDestructorDecl *D);
119
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000120 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
121 MD = MD->getCanonicalDecl();
122 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000123 MicrosoftVTableContext::MethodVFTableLocation ML =
124 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000125 // The vbases might be ordered differently in the final overrider object
126 // and the complete object, so the "this" argument may sometimes point to
127 // memory that has no particular type (e.g. past the complete object).
128 // In this case, we just use a generic pointer type.
129 // FIXME: might want to have a more precise type in the non-virtual
130 // multiple inheritance case.
131 if (ML.VBase || !ML.VFTableOffset.isZero())
132 return 0;
133 }
134 return MD->getParent();
135 }
136
137 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
138 GlobalDecl GD,
139 llvm::Value *This);
140
John McCall5d865c322010-08-31 07:33:07 +0000141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +0000143 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000144
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000145 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
147
John McCall0f999f32012-09-25 08:00:39 +0000148 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000149
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000150 void EmitConstructorCall(CodeGenFunction &CGF,
151 const CXXConstructorDecl *D, CXXCtorType Type,
152 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000153 llvm::Value *This,
154 CallExpr::const_arg_iterator ArgBeg,
155 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000156
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000157 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
158
159 llvm::Value *getVTableAddressPointInStructor(
160 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
161 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
162 bool &NeedsVirtualOffset);
163
164 llvm::Constant *
165 getVTableAddressPointForConstExpr(BaseSubobject Base,
166 const CXXRecordDecl *VTableClass);
167
168 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
169 CharUnits VPtrOffset);
170
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
172 llvm::Value *This, llvm::Type *Ty);
173
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000174 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
175 const CXXDestructorDecl *Dtor,
176 CXXDtorType DtorType, SourceLocation CallLoc,
177 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000178
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000179 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
180 CallArgList &CallArgs) {
181 assert(GD.getDtorType() == Dtor_Deleting &&
182 "Only deleting destructor thunks are available in this ABI");
183 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
184 CGM.getContext().IntTy);
185 }
186
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000188
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000189 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
190 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
191 }
192
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000193 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
194 const ThisAdjustment &TA);
195
196 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
197 const ReturnAdjustment &RA);
198
John McCallc84ed6a2012-05-01 06:13:13 +0000199 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
200 llvm::GlobalVariable *DeclPtr,
201 bool PerformInit);
202
John McCall29036752011-01-27 02:46:02 +0000203 // ==== Notes on array cookies =========
204 //
205 // MSVC seems to only use cookies when the class has a destructor; a
206 // two-argument usual array deallocation function isn't sufficient.
207 //
208 // For example, this code prints "100" and "1":
209 // struct A {
210 // char x;
211 // void *operator new[](size_t sz) {
212 // printf("%u\n", sz);
213 // return malloc(sz);
214 // }
215 // void operator delete[](void *p, size_t sz) {
216 // printf("%u\n", sz);
217 // free(p);
218 // }
219 // };
220 // int main() {
221 // A *p = new A[100];
222 // delete[] p;
223 // }
224 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000225
226 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
227 bool requiresArrayCookie(const CXXNewExpr *expr);
228 CharUnits getArrayCookieSizeImpl(QualType type);
229 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
230 llvm::Value *NewPtr,
231 llvm::Value *NumElements,
232 const CXXNewExpr *expr,
233 QualType ElementType);
234 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
235 llvm::Value *allocPtr,
236 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000237
238private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000239 MicrosoftMangleContext &getMangleContext() {
240 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
241 }
242
Reid Kleckner2341ae32013-04-11 18:13:19 +0000243 llvm::Constant *getZeroInt() {
244 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000245 }
246
Reid Kleckner2341ae32013-04-11 18:13:19 +0000247 llvm::Constant *getAllOnesInt() {
248 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000249 }
250
Reid Kleckner452abac2013-05-09 21:01:17 +0000251 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
252 return C ? C : getZeroInt();
253 }
254
255 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
256 return C ? C : getZeroInt();
257 }
258
Reid Kleckner2341ae32013-04-11 18:13:19 +0000259 void
260 GetNullMemberPointerFields(const MemberPointerType *MPT,
261 llvm::SmallVectorImpl<llvm::Constant *> &fields);
262
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000263 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
264 /// it is reusing a vbptr from a non-virtual base. RD must have morally
265 /// virtual bases.
266 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
267
268 /// \brief Shared code for virtual base adjustment. Returns the offset from
269 /// the vbptr to the virtual base. Optionally returns the address of the
270 /// vbptr itself.
271 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
272 llvm::Value *Base,
273 llvm::Value *VBPtrOffset,
274 llvm::Value *VBTableOffset,
275 llvm::Value **VBPtr = 0);
276
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000277 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
278 llvm::Value *Base,
279 int32_t VBPtrOffset,
280 int32_t VBTableOffset,
281 llvm::Value **VBPtr = 0) {
282 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
283 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
284 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
285 }
286
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000287 /// \brief Performs a full virtual base adjustment. Used to dereference
288 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000289 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
290 llvm::Value *Base,
291 llvm::Value *VirtualBaseAdjustmentOffset,
292 llvm::Value *VBPtrOffset /* optional */);
293
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000294 /// \brief Emits a full member pointer with the fields common to data and
295 /// function member pointers.
296 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
297 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000298 const CXXRecordDecl *RD,
299 CharUnits NonVirtualBaseAdjustment);
300
301 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
302 const CXXMethodDecl *MD,
303 CharUnits NonVirtualBaseAdjustment);
304
305 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
306 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000307
Reid Kleckner7810af02013-06-19 15:20:38 +0000308 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
309 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
310
311 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
312 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
313
Reid Kleckner407e8b62013-03-22 19:02:54 +0000314public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000315 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
316
317 virtual bool isZeroInitializable(const MemberPointerType *MPT);
318
Reid Kleckner407e8b62013-03-22 19:02:54 +0000319 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
320
321 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
322 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000323 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
324 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000325
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000326 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
327 llvm::Value *L,
328 llvm::Value *R,
329 const MemberPointerType *MPT,
330 bool Inequality);
331
Reid Kleckner407e8b62013-03-22 19:02:54 +0000332 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
333 llvm::Value *MemPtr,
334 const MemberPointerType *MPT);
335
336 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
337 llvm::Value *Base,
338 llvm::Value *MemPtr,
339 const MemberPointerType *MPT);
340
Reid Kleckner452abac2013-05-09 21:01:17 +0000341 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
342 const CastExpr *E,
343 llvm::Value *Src);
344
345 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
346 llvm::Constant *Src);
347
Reid Kleckner2341ae32013-04-11 18:13:19 +0000348 virtual llvm::Value *
349 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
350 llvm::Value *&This,
351 llvm::Value *MemPtr,
352 const MemberPointerType *MPT);
353
Reid Kleckner7810af02013-06-19 15:20:38 +0000354private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000355 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
356 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
357 /// \brief All the vftables that have been referenced.
358 VFTablesMapTy VFTablesMap;
359
360 /// \brief This set holds the record decls we've deferred vtable emission for.
361 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
362
363
364 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000365 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000366
367 /// Info on the global variable used to guard initialization of static locals.
368 /// The BitIndex field is only used for externally invisible declarations.
369 struct GuardInfo {
370 GuardInfo() : Guard(0), BitIndex(0) {}
371 llvm::GlobalVariable *Guard;
372 unsigned BitIndex;
373 };
374
375 /// Map from DeclContext to the current guard variable. We assume that the
376 /// AST is visited in source code order.
377 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000378};
379
380}
381
John McCall82fb8922012-09-25 10:10:39 +0000382llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
383 llvm::Value *ptr,
384 QualType type) {
385 // FIXME: implement
386 return ptr;
387}
388
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000389/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
390/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
391static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
392 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
393 E = RD->bases_end(); I != E; ++I) {
394 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
395 if (!I->isVirtual() && Base->getNumVBases() > 0)
396 return Base;
397 }
398 llvm_unreachable("RD must have an nv base with vbases");
399}
400
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000401CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
402 assert(RD->getNumVBases());
403 CharUnits Total = CharUnits::Zero();
404 while (RD) {
405 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
406 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
407 // -1 is the sentinel for no vbptr.
408 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
409 Total += VBPtrOffset;
410 break;
411 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000412 RD = FindFirstNVBaseWithVBases(RD);
413 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000414 }
415 return Total;
416}
417
418llvm::Value *
419MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
420 llvm::Value *This,
421 const CXXRecordDecl *ClassDecl,
422 const CXXRecordDecl *BaseClassDecl) {
423 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
424 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000425 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000426 CharUnits VBTableChars =
427 IntSize *
428 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000429 llvm::Value *VBTableOffset =
430 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
431
432 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000433 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000434 VBPtrToNewBase =
435 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
436 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
437}
438
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000439bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
440 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000441}
442
443void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
444 CXXCtorType Type,
445 CanQualType &ResTy,
446 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000447 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000448
449 const CXXRecordDecl *Class = Ctor->getParent();
450 if (Class->getNumVBases()) {
451 // Constructors of classes with virtual bases take an implicit parameter.
452 ArgTys.push_back(CGM.getContext().IntTy);
453 }
454}
455
Reid Kleckner7810af02013-06-19 15:20:38 +0000456llvm::BasicBlock *
457MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
458 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000459 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
460 assert(IsMostDerivedClass &&
461 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000462 llvm::Value *IsCompleteObject =
463 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000464
465 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
466 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
467 CGF.Builder.CreateCondBr(IsCompleteObject,
468 CallVbaseCtorsBB, SkipVbaseCtorsBB);
469
470 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000471
472 // Fill in the vbtable pointers here.
473 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000474
475 // CGF will put the base ctor calls in this basic block for us later.
476
477 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000478}
479
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000480void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
481 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
482 // In most cases, an override for a vbase virtual method can adjust
483 // the "this" parameter by applying a constant offset.
484 // However, this is not enough while a constructor or a destructor of some
485 // class X is being executed if all the following conditions are met:
486 // - X has virtual bases, (1)
487 // - X overrides a virtual method M of a vbase Y, (2)
488 // - X itself is a vbase of the most derived class.
489 //
490 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
491 // which holds the extra amount of "this" adjustment we must do when we use
492 // the X vftables (i.e. during X ctor or dtor).
493 // Outside the ctors and dtors, the values of vtorDisps are zero.
494
495 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
496 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
497 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
498 CGBuilderTy &Builder = CGF.Builder;
499
500 unsigned AS =
501 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
502 llvm::Value *Int8This = 0; // Initialize lazily.
503
504 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
505 I != E; ++I) {
506 if (!I->second.hasVtorDisp())
507 continue;
508
509 llvm::Value *VBaseOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
510 CGF, getThisValue(CGF), RD, I->first);
511 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
512 // just to Trunc back immediately.
513 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
514 uint64_t ConstantVBaseOffset =
515 Layout.getVBaseClassOffset(I->first).getQuantity();
516
517 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
518 llvm::Value *VtorDispValue = Builder.CreateSub(
519 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
520 "vtordisp.value");
521
522 if (!Int8This)
523 Int8This = Builder.CreateBitCast(getThisValue(CGF),
524 CGF.Int8Ty->getPointerTo(AS));
525 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
526 // vtorDisp is always the 32-bits before the vbase in the class layout.
527 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
528 VtorDispPtr = Builder.CreateBitCast(
529 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
530
531 Builder.CreateStore(VtorDispValue, VtorDispPtr);
532 }
533}
534
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000535void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
536 // There's only one constructor type in this ABI.
537 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
538}
539
Reid Kleckner7810af02013-06-19 15:20:38 +0000540void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
541 const CXXRecordDecl *RD) {
542 llvm::Value *ThisInt8Ptr =
543 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
544
545 const VBTableVector &VBTables = EnumerateVBTables(RD);
546 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
547 I != E; ++I) {
548 const ASTRecordLayout &SubobjectLayout =
549 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
550 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
551 SubobjectLayout.getVBPtrOffset()).getQuantity();
552 llvm::Value *VBPtr =
553 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
554 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
555 "vbptr." + I->ReusingBase->getName());
556 CGF.Builder.CreateStore(I->GV, VBPtr);
557 }
558}
559
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000560void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
561 CXXDtorType Type,
562 CanQualType &ResTy,
563 SmallVectorImpl<CanQualType> &ArgTys) {
564 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000565
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000566 // TODO: 'for base' flag
567
568 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000569 // The scalar deleting destructor takes an implicit int parameter.
570 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000571 }
572}
573
Reid Klecknere7de47e2013-07-22 13:51:44 +0000574void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
575 // The TU defining a dtor is only guaranteed to emit a base destructor. All
576 // other destructor variants are delegating thunks.
577 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
578}
579
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000580llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
581 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
582 GD = GD.getCanonicalDecl();
583 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000584 // FIXME: consider splitting the vdtor vs regular method code into two
585 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000586
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000587 GlobalDecl LookupGD = GD;
588 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
589 // Complete dtors take a pointer to the complete object,
590 // thus don't need adjustment.
591 if (GD.getDtorType() == Dtor_Complete)
592 return This;
593
594 // There's only Dtor_Deleting in vftable but it shares the this adjustment
595 // with the base one, so look up the deleting one instead.
596 LookupGD = GlobalDecl(DD, Dtor_Deleting);
597 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000598 MicrosoftVTableContext::MethodVFTableLocation ML =
599 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000600
601 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
602 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000603 CharUnits StaticOffset = ML.VFTableOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000604 if (ML.VBase) {
605 bool AvoidVirtualOffset = false;
606 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
607 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000608 // same record type or another destructor of a more derived type;
609 // or a constructor of the same record type if an exception is thrown.
610 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
611 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000612 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000613 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000614
615 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000616 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
617 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
618 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
619 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
620 // We're calling the main base dtor from a complete structor,
621 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000622 AvoidVirtualOffset = true;
623 } else {
624 // Let's see if we try to call a destructor of a non-virtual base.
625 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
626 E = CurRD->bases_end(); I != E; ++I) {
627 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
628 continue;
629 // If we call a base destructor for a non-virtual base, we statically
630 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000631 // The total offset should reflect the adjustment done by
632 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000633 AvoidVirtualOffset = true;
634 break;
635 }
636 }
637 }
638
639 if (AvoidVirtualOffset) {
640 const ASTRecordLayout &Layout =
641 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000642 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
643 } else {
644 This = CGF.Builder.CreateBitCast(This, charPtrTy);
645 llvm::Value *VBaseOffset = CGM.getCXXABI()
646 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
647 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
648 }
649 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000650 if (!StaticOffset.isZero()) {
651 assert(StaticOffset.isPositive());
652 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000653 if (ML.VBase) {
654 // Non-virtual adjustment might result in a pointer outside the allocated
655 // object, e.g. if the final overrider class is laid out after the virtual
656 // base that declares a method in the most derived class.
657 // FIXME: Update the code that emits this adjustment in thunks prologues.
658 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
659 } else {
660 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
661 StaticOffset.getQuantity());
662 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000663 }
664 return This;
665}
666
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000667static bool IsDeletingDtor(GlobalDecl GD) {
668 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
669 if (isa<CXXDestructorDecl>(MD)) {
670 return GD.getDtorType() == Dtor_Deleting;
671 }
672 return false;
673}
674
John McCall0f999f32012-09-25 08:00:39 +0000675void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
676 QualType &ResTy,
677 FunctionArgList &Params) {
678 BuildThisParam(CGF, Params);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000679
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000680 ASTContext &Context = getContext();
681 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
682 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
683 ImplicitParamDecl *IsMostDerived
684 = ImplicitParamDecl::Create(Context, 0,
685 CGF.CurGD.getDecl()->getLocation(),
686 &Context.Idents.get("is_most_derived"),
687 Context.IntTy);
688 Params.push_back(IsMostDerived);
689 getStructorImplicitParamDecl(CGF) = IsMostDerived;
690 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000691 ImplicitParamDecl *ShouldDelete
692 = ImplicitParamDecl::Create(Context, 0,
693 CGF.CurGD.getDecl()->getLocation(),
694 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000695 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000696 Params.push_back(ShouldDelete);
697 getStructorImplicitParamDecl(CGF) = ShouldDelete;
698 }
John McCall0f999f32012-09-25 08:00:39 +0000699}
700
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000701llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
702 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
703 GD = GD.getCanonicalDecl();
704 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000705
706 GlobalDecl LookupGD = GD;
707 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
708 // Complete destructors take a pointer to the complete object as a
709 // parameter, thus don't need this adjustment.
710 if (GD.getDtorType() == Dtor_Complete)
711 return This;
712
713 // There's no Dtor_Base in vftable but it shares the this adjustment with
714 // the deleting one, so look it up instead.
715 LookupGD = GlobalDecl(DD, Dtor_Deleting);
716 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000717
718 // In this ABI, every virtual function takes a pointer to one of the
719 // subobjects that first defines it as the 'this' parameter, rather than a
720 // pointer to ther final overrider subobject. Thus, we need to adjust it back
721 // to the final overrider subobject before use.
722 // See comments in the MicrosoftVFTableContext implementation for the details.
723
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000724 MicrosoftVTableContext::MethodVFTableLocation ML =
725 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000726 CharUnits Adjustment = ML.VFTableOffset;
727 if (ML.VBase) {
728 const ASTRecordLayout &DerivedLayout =
729 CGF.getContext().getASTRecordLayout(MD->getParent());
730 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
731 }
732
733 if (Adjustment.isZero())
734 return This;
735
736 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
737 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
738 *thisTy = This->getType();
739
740 This = CGF.Builder.CreateBitCast(This, charPtrTy);
741 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000742 This =
743 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000744 return CGF.Builder.CreateBitCast(This, thisTy);
745}
746
John McCall0f999f32012-09-25 08:00:39 +0000747void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
748 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000749
750 /// If this is a function that the ABI specifies returns 'this', initialize
751 /// the return slot to 'this' at the start of the function.
752 ///
753 /// Unlike the setting of return types, this is done within the ABI
754 /// implementation instead of by clients of CGCXXABI because:
755 /// 1) getThisValue is currently protected
756 /// 2) in theory, an ABI could implement 'this' returns some other way;
757 /// HasThisReturn only specifies a contract, not the implementation
758 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000759 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000760
761 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
762 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
763 assert(getStructorImplicitParamDecl(CGF) &&
764 "no implicit parameter for a constructor with virtual bases?");
765 getStructorImplicitParamValue(CGF)
766 = CGF.Builder.CreateLoad(
767 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
768 "is_most_derived");
769 }
770
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000771 if (IsDeletingDtor(CGF.CurGD)) {
772 assert(getStructorImplicitParamDecl(CGF) &&
773 "no implicit parameter for a deleting destructor?");
774 getStructorImplicitParamValue(CGF)
775 = CGF.Builder.CreateLoad(
776 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
777 "should_call_delete");
778 }
John McCall0f999f32012-09-25 08:00:39 +0000779}
780
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000781void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Linc467c872013-06-19 18:10:35 +0000782 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000783 CXXCtorType Type,
784 bool ForVirtualBase,
Stephen Linc467c872013-06-19 18:10:35 +0000785 bool Delegating,
786 llvm::Value *This,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000787 CallExpr::const_arg_iterator ArgBeg,
788 CallExpr::const_arg_iterator ArgEnd) {
789 assert(Type == Ctor_Complete || Type == Ctor_Base);
790 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
791
792 llvm::Value *ImplicitParam = 0;
793 QualType ImplicitParamTy;
794 if (D->getParent()->getNumVBases()) {
795 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
796 ImplicitParamTy = getContext().IntTy;
797 }
798
799 // FIXME: Provide a source location here.
Stephen Linc467c872013-06-19 18:10:35 +0000800 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000801 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000802}
803
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000804void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
805 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000806 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
807 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000808 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
809
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000810 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000811 E = VFPtrs.end(); I != E; ++I) {
812 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
813 if (VTable->hasInitializer())
814 continue;
815
816 const VTableLayout &VTLayout =
817 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
818 llvm::Constant *Init = CGVT.CreateVTableInitializer(
819 RD, VTLayout.vtable_component_begin(),
820 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
821 VTLayout.getNumVTableThunks());
822 VTable->setInitializer(Init);
823
824 VTable->setLinkage(Linkage);
825 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
826 }
827}
828
829llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
830 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
831 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
832 NeedsVirtualOffset = (NearestVBase != 0);
833
834 llvm::Value *VTableAddressPoint =
835 getAddrOfVTable(VTableClass, Base.getBaseOffset());
836 if (!VTableAddressPoint) {
837 assert(Base.getBase()->getNumVBases() &&
838 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
839 }
840 return VTableAddressPoint;
841}
842
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000843static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
844 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
845 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000846 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000847 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000848}
849
850llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
851 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
852 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
853 assert(VTable && "Couldn't find a vftable for the given base?");
854 return VTable;
855}
856
857llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
858 CharUnits VPtrOffset) {
859 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
860 // shouldn't be used in the given record type. We want to cache this result in
861 // VFTablesMap, thus a simple zero check is not sufficient.
862 VFTableIdTy ID(RD, VPtrOffset);
863 VFTablesMapTy::iterator I;
864 bool Inserted;
865 llvm::tie(I, Inserted) = VFTablesMap.insert(
866 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
867 if (!Inserted)
868 return I->second;
869
870 llvm::GlobalVariable *&VTable = I->second;
871
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000872 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
873 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
874 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000875
876 if (DeferredVFTables.insert(RD)) {
877 // We haven't processed this record type before.
878 // Queue up this v-table for possible deferred emission.
879 CGM.addDeferredVTable(RD);
880
881#ifndef NDEBUG
882 // Create all the vftables at once in order to make sure each vftable has
883 // a unique mangled name.
884 llvm::StringSet<> ObservedMangledNames;
885 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
886 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000887 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000888 if (!ObservedMangledNames.insert(Name.str()))
889 llvm_unreachable("Already saw this mangling before?");
890 }
891#endif
892 }
893
894 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
895 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
896 continue;
897
898 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
899 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000900 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000901 .getNumVTableComponents());
902
903 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000904 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000905 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
906 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
907 VTable->setUnnamedAddr(true);
908 break;
909 }
910
911 return VTable;
912}
913
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000914llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
915 GlobalDecl GD,
916 llvm::Value *This,
917 llvm::Type *Ty) {
918 GD = GD.getCanonicalDecl();
919 CGBuilderTy &Builder = CGF.Builder;
920
921 Ty = Ty->getPointerTo()->getPointerTo();
922 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
923 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
924
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000925 MicrosoftVTableContext::MethodVFTableLocation ML =
926 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000927 llvm::Value *VFuncPtr =
928 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
929 return Builder.CreateLoad(VFuncPtr);
930}
931
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000932void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
933 const CXXDestructorDecl *Dtor,
934 CXXDtorType DtorType,
935 SourceLocation CallLoc,
936 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000937 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
938
939 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000940 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000941 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000942 const CGFunctionInfo *FInfo =
943 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000944 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000945 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000946
947 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000948 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000949 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000950 DtorType == Dtor_Deleting);
951
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000952 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000953 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000954 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000955}
956
Reid Kleckner7810af02013-06-19 15:20:38 +0000957const VBTableVector &
958MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
959 // At this layer, we can key the cache off of a single class, which is much
960 // easier than caching at the GlobalVariable layer.
961 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
962 bool added;
963 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
964 VBTableVector &VBTables = I->second;
965 if (!added)
966 return VBTables;
967
968 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
969
970 return VBTables;
971}
972
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000973void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +0000974 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000975 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
976
Reid Kleckner7810af02013-06-19 15:20:38 +0000977 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
978 I != E; ++I) {
979 I->EmitVBTableDefinition(CGM, RD, Linkage);
980 }
981}
982
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000983llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
984 llvm::Value *This,
985 const ThisAdjustment &TA) {
986 if (TA.isEmpty())
987 return This;
988
989 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
990
991 assert(TA.VCallOffsetOffset == 0 &&
992 "VtorDisp adjustment is not supported yet");
993
994 if (TA.NonVirtual) {
995 // Non-virtual adjustment might result in a pointer outside the allocated
996 // object, e.g. if the final overrider class is laid out after the virtual
997 // base that declares a method in the most derived class.
998 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
999 }
1000
1001 // Don't need to bitcast back, the call CodeGen will handle this.
1002 return V;
1003}
1004
1005llvm::Value *
1006MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1007 const ReturnAdjustment &RA) {
1008 if (RA.isEmpty())
1009 return Ret;
1010
1011 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1012
1013 if (RA.Virtual.Microsoft.VBIndex) {
1014 assert(RA.Virtual.Microsoft.VBIndex > 0);
1015 int32_t IntSize =
1016 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1017 llvm::Value *VBPtr;
1018 llvm::Value *VBaseOffset =
1019 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1020 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1021 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1022 }
1023
1024 if (RA.NonVirtual)
1025 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1026
1027 // Cast back to the original type.
1028 return CGF.Builder.CreateBitCast(V, Ret->getType());
1029}
1030
John McCallb91cd662012-05-01 05:23:51 +00001031bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1032 QualType elementType) {
1033 // Microsoft seems to completely ignore the possibility of a
1034 // two-argument usual deallocation function.
1035 return elementType.isDestructedType();
1036}
1037
1038bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1039 // Microsoft seems to completely ignore the possibility of a
1040 // two-argument usual deallocation function.
1041 return expr->getAllocatedType().isDestructedType();
1042}
1043
1044CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1045 // The array cookie is always a size_t; we then pad that out to the
1046 // alignment of the element type.
1047 ASTContext &Ctx = getContext();
1048 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1049 Ctx.getTypeAlignInChars(type));
1050}
1051
1052llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1053 llvm::Value *allocPtr,
1054 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001055 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001056 llvm::Value *numElementsPtr =
1057 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1058 return CGF.Builder.CreateLoad(numElementsPtr);
1059}
1060
1061llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1062 llvm::Value *newPtr,
1063 llvm::Value *numElements,
1064 const CXXNewExpr *expr,
1065 QualType elementType) {
1066 assert(requiresArrayCookie(expr));
1067
1068 // The size of the cookie.
1069 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1070
1071 // Compute an offset to the cookie.
1072 llvm::Value *cookiePtr = newPtr;
1073
1074 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001075 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001076 llvm::Value *numElementsPtr
1077 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1078 CGF.Builder.CreateStore(numElements, numElementsPtr);
1079
1080 // Finally, compute a pointer to the actual data buffer by skipping
1081 // over the cookie completely.
1082 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1083 cookieSize.getQuantity());
1084}
1085
John McCallc84ed6a2012-05-01 06:13:13 +00001086void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001087 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001088 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001089 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1090 // threadsafe. Since the user may be linking in inline functions compiled by
1091 // cl.exe, there's no reason to provide a false sense of security by using
1092 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001093
Richard Smithdbf74ba2013-04-14 23:01:42 +00001094 if (D.getTLSKind())
1095 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1096
Reid Klecknerd8110b62013-09-10 20:14:30 +00001097 CGBuilderTy &Builder = CGF.Builder;
1098 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1099 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1100
1101 // Get the guard variable for this function if we have one already.
1102 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1103
1104 unsigned BitIndex;
1105 if (D.isExternallyVisible()) {
1106 // Externally visible variables have to be numbered in Sema to properly
1107 // handle unreachable VarDecls.
1108 BitIndex = getContext().getManglingNumber(&D);
1109 assert(BitIndex > 0);
1110 BitIndex--;
1111 } else {
1112 // Non-externally visible variables are numbered here in CodeGen.
1113 BitIndex = GI.BitIndex++;
1114 }
1115
1116 if (BitIndex >= 32) {
1117 if (D.isExternallyVisible())
1118 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1119 BitIndex %= 32;
1120 GI.Guard = 0;
1121 }
1122
1123 // Lazily create the i32 bitfield for this function.
1124 if (!GI.Guard) {
1125 // Mangle the name for the guard.
1126 SmallString<256> GuardName;
1127 {
1128 llvm::raw_svector_ostream Out(GuardName);
1129 getMangleContext().mangleStaticGuardVariable(&D, Out);
1130 Out.flush();
1131 }
1132
1133 // Create the guard variable with a zero-initializer. Just absorb linkage
1134 // and visibility from the guarded variable.
1135 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1136 GV->getLinkage(), Zero, GuardName.str());
1137 GI.Guard->setVisibility(GV->getVisibility());
1138 } else {
1139 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1140 "static local from the same function had different linkage");
1141 }
1142
1143 // Pseudo code for the test:
1144 // if (!(GuardVar & MyGuardBit)) {
1145 // GuardVar |= MyGuardBit;
1146 // ... initialize the object ...;
1147 // }
1148
1149 // Test our bit from the guard variable.
1150 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1151 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1152 llvm::Value *IsInitialized =
1153 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1154 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1155 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1156 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1157
1158 // Set our bit in the guard variable and emit the initializer and add a global
1159 // destructor if appropriate.
1160 CGF.EmitBlock(InitBlock);
1161 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1162 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1163 Builder.CreateBr(EndBlock);
1164
1165 // Continue.
1166 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001167}
1168
Reid Kleckner2341ae32013-04-11 18:13:19 +00001169// Member pointer helpers.
1170static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1171 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001172}
1173
Reid Kleckner452abac2013-05-09 21:01:17 +00001174static bool hasOnlyOneField(bool IsMemberFunction,
1175 MSInheritanceModel Inheritance) {
1176 return Inheritance <= MSIM_SinglePolymorphic ||
1177 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001178}
1179
Reid Kleckner2341ae32013-04-11 18:13:19 +00001180// Only member pointers to functions need a this adjustment, since it can be
1181// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001182static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001183 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001184 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001185}
1186
1187static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1188 return Inheritance >= MSIM_Virtual;
1189}
1190
1191// Use zero for the field offset of a null data member pointer if we can
1192// guarantee that zero is not a valid field offset, or if the member pointer has
1193// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1194// use zero for null. If there are multiple fields, we can use zero even if it
1195// is a valid field offset because null-ness testing will check the other
1196// fields.
1197static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1198 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1199}
1200
1201bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1202 // Null-ness for function memptrs only depends on the first field, which is
1203 // the function pointer. The rest don't matter, so we can zero initialize.
1204 if (MPT->isMemberFunctionPointer())
1205 return true;
1206
1207 // The virtual base adjustment field is always -1 for null, so if we have one
1208 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1209 // valid field offset.
1210 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1211 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1212 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1213 nullFieldOffsetIsZero(Inheritance));
1214}
1215
1216llvm::Type *
1217MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1218 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1219 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1220 llvm::SmallVector<llvm::Type *, 4> fields;
1221 if (MPT->isMemberFunctionPointer())
1222 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1223 else
1224 fields.push_back(CGM.IntTy); // FieldOffset
1225
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001226 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1227 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001228 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001229 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001230 fields.push_back(CGM.IntTy);
1231 if (hasVirtualBaseAdjustmentField(Inheritance))
1232 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1233
1234 if (fields.size() == 1)
1235 return fields[0];
1236 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1237}
1238
1239void MicrosoftCXXABI::
1240GetNullMemberPointerFields(const MemberPointerType *MPT,
1241 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1242 assert(fields.empty());
1243 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1244 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1245 if (MPT->isMemberFunctionPointer()) {
1246 // FunctionPointerOrVirtualThunk
1247 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1248 } else {
1249 if (nullFieldOffsetIsZero(Inheritance))
1250 fields.push_back(getZeroInt()); // FieldOffset
1251 else
1252 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001253 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001254
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001255 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1256 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001257 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001258 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001259 fields.push_back(getZeroInt());
1260 if (hasVirtualBaseAdjustmentField(Inheritance))
1261 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001262}
1263
1264llvm::Constant *
1265MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001266 llvm::SmallVector<llvm::Constant *, 4> fields;
1267 GetNullMemberPointerFields(MPT, fields);
1268 if (fields.size() == 1)
1269 return fields[0];
1270 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1271 assert(Res->getType() == ConvertMemberPointerType(MPT));
1272 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001273}
1274
1275llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001276MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1277 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001278 const CXXRecordDecl *RD,
1279 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001280{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001281 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001282
1283 // Single inheritance class member pointer are represented as scalars instead
1284 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001285 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001286 return FirstField;
1287
Reid Kleckner2341ae32013-04-11 18:13:19 +00001288 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001289 fields.push_back(FirstField);
1290
1291 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001292 fields.push_back(llvm::ConstantInt::get(
1293 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001294
Reid Kleckner2341ae32013-04-11 18:13:19 +00001295 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001296 CharUnits Offs = CharUnits::Zero();
1297 if (RD->getNumVBases())
1298 Offs = GetVBPtrOffsetFromBases(RD);
1299 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001300 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001301
1302 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001303 if (hasVirtualBaseAdjustmentField(Inheritance))
1304 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001305
Reid Kleckner2341ae32013-04-11 18:13:19 +00001306 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001307}
1308
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001309llvm::Constant *
1310MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1311 CharUnits offset) {
1312 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1313 llvm::Constant *FirstField =
1314 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001315 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1316 CharUnits::Zero());
1317}
1318
1319llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1320 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1321}
1322
1323llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1324 QualType MPType) {
1325 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1326 const ValueDecl *MPD = MP.getMemberPointerDecl();
1327 if (!MPD)
1328 return EmitNullMemberPointer(MPT);
1329
1330 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1331
1332 // FIXME PR15713: Support virtual inheritance paths.
1333
1334 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1335 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1336 MD, ThisAdjustment);
1337
1338 CharUnits FieldOffset =
1339 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1340 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001341}
1342
1343llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001344MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1345 const CXXMethodDecl *MD,
1346 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001347 assert(MD->isInstance() && "Member function must not be static!");
1348 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001349 CodeGenTypes &Types = CGM.getTypes();
1350
1351 llvm::Constant *FirstField;
1352 if (MD->isVirtual()) {
1353 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1354 // the right offset.
Reid Kleckner5a823d52013-10-17 21:30:27 +00001355 CGM.ErrorUnsupported(MD, "pointer to virtual member function");
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001356 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1357 } else {
1358 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1359 llvm::Type *Ty;
1360 // Check whether the function has a computable LLVM signature.
1361 if (Types.isFuncTypeConvertible(FPT)) {
1362 // The function has a computable LLVM signature; use the correct type.
1363 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1364 } else {
1365 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1366 // function type is incomplete.
1367 Ty = CGM.PtrDiffTy;
1368 }
1369 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1370 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1371 }
1372
1373 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001374 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1375 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001376}
1377
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001378/// Member pointers are the same if they're either bitwise identical *or* both
1379/// null. Null-ness for function members is determined by the first field,
1380/// while for data member pointers we must compare all fields.
1381llvm::Value *
1382MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1383 llvm::Value *L,
1384 llvm::Value *R,
1385 const MemberPointerType *MPT,
1386 bool Inequality) {
1387 CGBuilderTy &Builder = CGF.Builder;
1388
1389 // Handle != comparisons by switching the sense of all boolean operations.
1390 llvm::ICmpInst::Predicate Eq;
1391 llvm::Instruction::BinaryOps And, Or;
1392 if (Inequality) {
1393 Eq = llvm::ICmpInst::ICMP_NE;
1394 And = llvm::Instruction::Or;
1395 Or = llvm::Instruction::And;
1396 } else {
1397 Eq = llvm::ICmpInst::ICMP_EQ;
1398 And = llvm::Instruction::And;
1399 Or = llvm::Instruction::Or;
1400 }
1401
1402 // If this is a single field member pointer (single inheritance), this is a
1403 // single icmp.
1404 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1405 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001406 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001407 return Builder.CreateICmp(Eq, L, R);
1408
1409 // Compare the first field.
1410 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1411 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1412 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1413
1414 // Compare everything other than the first field.
1415 llvm::Value *Res = 0;
1416 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1417 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1418 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1419 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1420 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1421 if (Res)
1422 Res = Builder.CreateBinOp(And, Res, Cmp);
1423 else
1424 Res = Cmp;
1425 }
1426
1427 // Check if the first field is 0 if this is a function pointer.
1428 if (MPT->isMemberFunctionPointer()) {
1429 // (l1 == r1 && ...) || l0 == 0
1430 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1431 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1432 Res = Builder.CreateBinOp(Or, Res, IsZero);
1433 }
1434
1435 // Combine the comparison of the first field, which must always be true for
1436 // this comparison to succeeed.
1437 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1438}
1439
Reid Kleckner407e8b62013-03-22 19:02:54 +00001440llvm::Value *
1441MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1442 llvm::Value *MemPtr,
1443 const MemberPointerType *MPT) {
1444 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001445 llvm::SmallVector<llvm::Constant *, 4> fields;
1446 // We only need one field for member functions.
1447 if (MPT->isMemberFunctionPointer())
1448 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1449 else
1450 GetNullMemberPointerFields(MPT, fields);
1451 assert(!fields.empty());
1452 llvm::Value *FirstField = MemPtr;
1453 if (MemPtr->getType()->isStructTy())
1454 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1455 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001456
Reid Kleckner2341ae32013-04-11 18:13:19 +00001457 // For function member pointers, we only need to test the function pointer
1458 // field. The other fields if any can be garbage.
1459 if (MPT->isMemberFunctionPointer())
1460 return Res;
1461
1462 // Otherwise, emit a series of compares and combine the results.
1463 for (int I = 1, E = fields.size(); I < E; ++I) {
1464 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1465 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1466 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1467 }
1468 return Res;
1469}
1470
Reid Kleckner452abac2013-05-09 21:01:17 +00001471bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1472 llvm::Constant *Val) {
1473 // Function pointers are null if the pointer in the first field is null.
1474 if (MPT->isMemberFunctionPointer()) {
1475 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1476 Val->getAggregateElement(0U) : Val;
1477 return FirstField->isNullValue();
1478 }
1479
1480 // If it's not a function pointer and it's zero initializable, we can easily
1481 // check zero.
1482 if (isZeroInitializable(MPT) && Val->isNullValue())
1483 return true;
1484
1485 // Otherwise, break down all the fields for comparison. Hopefully these
1486 // little Constants are reused, while a big null struct might not be.
1487 llvm::SmallVector<llvm::Constant *, 4> Fields;
1488 GetNullMemberPointerFields(MPT, Fields);
1489 if (Fields.size() == 1) {
1490 assert(Val->getType()->isIntegerTy());
1491 return Val == Fields[0];
1492 }
1493
1494 unsigned I, E;
1495 for (I = 0, E = Fields.size(); I != E; ++I) {
1496 if (Val->getAggregateElement(I) != Fields[I])
1497 break;
1498 }
1499 return I == E;
1500}
1501
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001502llvm::Value *
1503MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1504 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001505 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001506 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001507 llvm::Value **VBPtrOut) {
1508 CGBuilderTy &Builder = CGF.Builder;
1509 // Load the vbtable pointer from the vbptr in the instance.
1510 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1511 llvm::Value *VBPtr =
1512 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1513 if (VBPtrOut) *VBPtrOut = VBPtr;
1514 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1515 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1516
1517 // Load an i32 offset from the vb-table.
1518 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1519 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1520 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1521}
1522
Reid Kleckner2341ae32013-04-11 18:13:19 +00001523// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1524// it.
1525llvm::Value *
1526MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1527 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001528 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001529 llvm::Value *VBPtrOffset) {
1530 CGBuilderTy &Builder = CGF.Builder;
1531 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1532 llvm::BasicBlock *OriginalBB = 0;
1533 llvm::BasicBlock *SkipAdjustBB = 0;
1534 llvm::BasicBlock *VBaseAdjustBB = 0;
1535
1536 // In the unspecified inheritance model, there might not be a vbtable at all,
1537 // in which case we need to skip the virtual base lookup. If there is a
1538 // vbtable, the first entry is a no-op entry that gives back the original
1539 // base, so look for a virtual base adjustment offset of zero.
1540 if (VBPtrOffset) {
1541 OriginalBB = Builder.GetInsertBlock();
1542 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1543 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1544 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001545 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001546 "memptr.is_vbase");
1547 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1548 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001549 }
1550
Reid Kleckner2341ae32013-04-11 18:13:19 +00001551 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1552 // know the vbptr offset.
1553 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001554 CharUnits offs = CharUnits::Zero();
1555 if (RD->getNumVBases()) {
1556 offs = GetVBPtrOffsetFromBases(RD);
1557 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001558 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1559 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001560 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001561 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001562 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001563 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1564
1565 // Merge control flow with the case where we didn't have to adjust.
1566 if (VBaseAdjustBB) {
1567 Builder.CreateBr(SkipAdjustBB);
1568 CGF.EmitBlock(SkipAdjustBB);
1569 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1570 Phi->addIncoming(Base, OriginalBB);
1571 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1572 return Phi;
1573 }
1574 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001575}
1576
1577llvm::Value *
1578MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1579 llvm::Value *Base,
1580 llvm::Value *MemPtr,
1581 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001582 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001583 unsigned AS = Base->getType()->getPointerAddressSpace();
1584 llvm::Type *PType =
1585 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1586 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001587 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1588 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001589
Reid Kleckner2341ae32013-04-11 18:13:19 +00001590 // Extract the fields we need, regardless of model. We'll apply them if we
1591 // have them.
1592 llvm::Value *FieldOffset = MemPtr;
1593 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1594 llvm::Value *VBPtrOffset = 0;
1595 if (MemPtr->getType()->isStructTy()) {
1596 // We need to extract values.
1597 unsigned I = 0;
1598 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1599 if (hasVBPtrOffsetField(Inheritance))
1600 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1601 if (hasVirtualBaseAdjustmentField(Inheritance))
1602 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001603 }
1604
Reid Kleckner2341ae32013-04-11 18:13:19 +00001605 if (VirtualBaseAdjustmentOffset) {
1606 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1607 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001608 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001609 llvm::Value *Addr =
1610 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001611
1612 // Cast the address to the appropriate pointer type, adopting the address
1613 // space of the base pointer.
1614 return Builder.CreateBitCast(Addr, PType);
1615}
1616
Reid Kleckner452abac2013-05-09 21:01:17 +00001617static MSInheritanceModel
1618getInheritanceFromMemptr(const MemberPointerType *MPT) {
1619 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1620}
1621
1622llvm::Value *
1623MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1624 const CastExpr *E,
1625 llvm::Value *Src) {
1626 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1627 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1628 E->getCastKind() == CK_ReinterpretMemberPointer);
1629
1630 // Use constant emission if we can.
1631 if (isa<llvm::Constant>(Src))
1632 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1633
1634 // We may be adding or dropping fields from the member pointer, so we need
1635 // both types and the inheritance models of both records.
1636 const MemberPointerType *SrcTy =
1637 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1638 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1639 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1640 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1641 bool IsFunc = SrcTy->isMemberFunctionPointer();
1642
1643 // If the classes use the same null representation, reinterpret_cast is a nop.
1644 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1645 if (IsReinterpret && (IsFunc ||
1646 nullFieldOffsetIsZero(SrcInheritance) ==
1647 nullFieldOffsetIsZero(DstInheritance)))
1648 return Src;
1649
1650 CGBuilderTy &Builder = CGF.Builder;
1651
1652 // Branch past the conversion if Src is null.
1653 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1654 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1655
1656 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1657 // pointer value of the destination type.
1658 if (IsReinterpret) {
1659 // For reinterpret casts, sema ensures that src and dst are both functions
1660 // or data and have the same size, which means the LLVM types should match.
1661 assert(Src->getType() == DstNull->getType());
1662 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1663 }
1664
1665 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1666 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1667 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1668 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1669 CGF.EmitBlock(ConvertBB);
1670
1671 // Decompose src.
1672 llvm::Value *FirstField = Src;
1673 llvm::Value *NonVirtualBaseAdjustment = 0;
1674 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1675 llvm::Value *VBPtrOffset = 0;
1676 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1677 // We need to extract values.
1678 unsigned I = 0;
1679 FirstField = Builder.CreateExtractValue(Src, I++);
1680 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1681 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1682 if (hasVBPtrOffsetField(SrcInheritance))
1683 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1684 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1685 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1686 }
1687
1688 // For data pointers, we adjust the field offset directly. For functions, we
1689 // have a separate field.
1690 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1691 if (Adj) {
1692 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1693 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1694 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1695 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1696 NVAdjustField = getZeroInt();
1697 if (isDerivedToBase)
1698 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1699 else
1700 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1701 }
1702
1703 // FIXME PR15713: Support conversions through virtually derived classes.
1704
1705 // Recompose dst from the null struct and the adjusted fields from src.
1706 llvm::Value *Dst;
1707 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1708 Dst = FirstField;
1709 } else {
1710 Dst = llvm::UndefValue::get(DstNull->getType());
1711 unsigned Idx = 0;
1712 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1713 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1714 Dst = Builder.CreateInsertValue(
1715 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1716 if (hasVBPtrOffsetField(DstInheritance))
1717 Dst = Builder.CreateInsertValue(
1718 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1719 if (hasVirtualBaseAdjustmentField(DstInheritance))
1720 Dst = Builder.CreateInsertValue(
1721 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1722 }
1723 Builder.CreateBr(ContinueBB);
1724
1725 // In the continuation, choose between DstNull and Dst.
1726 CGF.EmitBlock(ContinueBB);
1727 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1728 Phi->addIncoming(DstNull, OriginalBB);
1729 Phi->addIncoming(Dst, ConvertBB);
1730 return Phi;
1731}
1732
1733llvm::Constant *
1734MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1735 llvm::Constant *Src) {
1736 const MemberPointerType *SrcTy =
1737 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1738 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1739
1740 // If src is null, emit a new null for dst. We can't return src because dst
1741 // might have a new representation.
1742 if (MemberPointerConstantIsNull(SrcTy, Src))
1743 return EmitNullMemberPointer(DstTy);
1744
1745 // We don't need to do anything for reinterpret_casts of non-null member
1746 // pointers. We should only get here when the two type representations have
1747 // the same size.
1748 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1749 return Src;
1750
1751 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1752 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1753
1754 // Decompose src.
1755 llvm::Constant *FirstField = Src;
1756 llvm::Constant *NonVirtualBaseAdjustment = 0;
1757 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1758 llvm::Constant *VBPtrOffset = 0;
1759 bool IsFunc = SrcTy->isMemberFunctionPointer();
1760 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1761 // We need to extract values.
1762 unsigned I = 0;
1763 FirstField = Src->getAggregateElement(I++);
1764 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1765 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1766 if (hasVBPtrOffsetField(SrcInheritance))
1767 VBPtrOffset = Src->getAggregateElement(I++);
1768 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1769 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1770 }
1771
1772 // For data pointers, we adjust the field offset directly. For functions, we
1773 // have a separate field.
1774 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1775 if (Adj) {
1776 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1777 llvm::Constant *&NVAdjustField =
1778 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1779 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1780 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1781 NVAdjustField = getZeroInt();
1782 if (IsDerivedToBase)
1783 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1784 else
1785 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1786 }
1787
1788 // FIXME PR15713: Support conversions through virtually derived classes.
1789
1790 // Recompose dst from the null struct and the adjusted fields from src.
1791 if (hasOnlyOneField(IsFunc, DstInheritance))
1792 return FirstField;
1793
1794 llvm::SmallVector<llvm::Constant *, 4> Fields;
1795 Fields.push_back(FirstField);
1796 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1797 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1798 if (hasVBPtrOffsetField(DstInheritance))
1799 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1800 if (hasVirtualBaseAdjustmentField(DstInheritance))
1801 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1802 return llvm::ConstantStruct::getAnon(Fields);
1803}
1804
Reid Kleckner2341ae32013-04-11 18:13:19 +00001805llvm::Value *
1806MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1807 llvm::Value *&This,
1808 llvm::Value *MemPtr,
1809 const MemberPointerType *MPT) {
1810 assert(MPT->isMemberFunctionPointer());
1811 const FunctionProtoType *FPT =
1812 MPT->getPointeeType()->castAs<FunctionProtoType>();
1813 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1814 llvm::FunctionType *FTy =
1815 CGM.getTypes().GetFunctionType(
1816 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1817 CGBuilderTy &Builder = CGF.Builder;
1818
1819 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1820
1821 // Extract the fields we need, regardless of model. We'll apply them if we
1822 // have them.
1823 llvm::Value *FunctionPointer = MemPtr;
1824 llvm::Value *NonVirtualBaseAdjustment = NULL;
1825 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1826 llvm::Value *VBPtrOffset = NULL;
1827 if (MemPtr->getType()->isStructTy()) {
1828 // We need to extract values.
1829 unsigned I = 0;
1830 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001831 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1832 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001833 if (hasVBPtrOffsetField(Inheritance))
1834 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001835 if (hasVirtualBaseAdjustmentField(Inheritance))
1836 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1837 }
1838
1839 if (VirtualBaseAdjustmentOffset) {
1840 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1841 VBPtrOffset);
1842 }
1843
1844 if (NonVirtualBaseAdjustment) {
1845 // Apply the adjustment and cast back to the original struct type.
1846 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1847 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1848 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1849 }
1850
1851 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1852}
1853
Charles Davis53c59df2010-08-16 03:33:14 +00001854CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001855 return new MicrosoftCXXABI(CGM);
1856}
1857