blob: 0e01d8bacfcbba67e16aeddba54f7ed7d8092771 [file] [log] [blame]
Charles Davisc3926642010-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davisc3926642010-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 Kleckner90633022013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davisc3926642010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Charles Davisc3926642010-06-09 23:25:41 +000023
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28
Charles Davis071cc7d2010-08-16 03:33:14 +000029class MicrosoftCXXABI : public CGCXXABI {
Charles Davisc3926642010-06-09 23:25:41 +000030public:
Peter Collingbourne14110472011-01-13 18:57:25 +000031 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall4c40d982010-08-31 07:33:07 +000032
Stephen Lin3b50e8d2013-06-30 20:40:16 +000033 bool HasThisReturn(GlobalDecl GD) const;
34
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000035 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
36 // Structures that are not C++03 PODs are always indirect.
37 return !RD->isPOD();
38 }
39
40 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner9b601952013-06-21 12:45:15 +000041 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000042 return RAA_DirectInMemory;
43 return RAA_Default;
44 }
45
Joao Matos285baac2012-07-17 17:10:11 +000046 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikie2eb9a952012-10-16 22:56:05 +000047 // No known support for deleted functions in MSVC yet, so this choice is
48 // arbitrary.
49 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos285baac2012-07-17 17:10:11 +000050
John McCallecd03b42012-09-25 10:10:39 +000051 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
52 llvm::Value *ptr,
53 QualType type);
54
Reid Klecknerb0f533e2013-05-29 18:02:47 +000055 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
56 llvm::Value *This,
57 const CXXRecordDecl *ClassDecl,
58 const CXXRecordDecl *BaseClassDecl);
59
John McCall4c40d982010-08-31 07:33:07 +000060 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
61 CXXCtorType Type,
62 CanQualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000063 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000064
Reid Kleckner90633022013-06-19 15:20:38 +000065 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
66 const CXXRecordDecl *RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000067
Reid Klecknera4130ba2013-07-22 13:51:44 +000068 // Background on MSVC destructors
69 // ==============================
70 //
71 // Both Itanium and MSVC ABIs have destructor variants. The variant names
72 // roughly correspond in the following way:
73 // Itanium Microsoft
74 // Base -> no name, just ~Class
75 // Complete -> vbase destructor
76 // Deleting -> scalar deleting destructor
77 // vector deleting destructor
78 //
79 // The base and complete destructors are the same as in Itanium, although the
80 // complete destructor does not accept a VTT parameter when there are virtual
81 // bases. A separate mechanism involving vtordisps is used to ensure that
82 // virtual methods of destroyed subobjects are not called.
83 //
84 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
85 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
86 // pointer points to an array. The scalar deleting destructor assumes that
87 // bit 2 is zero, and therefore does not contain a loop.
88 //
89 // For virtual destructors, only one entry is reserved in the vftable, and it
90 // always points to the vector deleting destructor. The vector deleting
91 // destructor is the most general, so it can be used to destroy objects in
92 // place, delete single heap objects, or delete arrays.
93 //
94 // A TU defining a non-inline destructor is only guaranteed to emit a base
95 // destructor, and all of the other variants are emitted on an as-needed basis
96 // in COMDATs. Because a non-base destructor can be emitted in a TU that
97 // lacks a definition for the destructor, non-base destructors must always
98 // delegate to or alias the base destructor.
99
100 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall4c40d982010-08-31 07:33:07 +0000101 CXXDtorType Type,
102 CanQualType &ResTy,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000103 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000104
Reid Klecknera4130ba2013-07-22 13:51:44 +0000105 /// Non-base dtors should be emitted as delegating thunks in this ABI.
106 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
107 CXXDtorType DT) const {
108 return DT != Dtor_Base;
109 }
110
111 void EmitCXXDestructors(const CXXDestructorDecl *D);
112
John McCall4c40d982010-08-31 07:33:07 +0000113 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
114 QualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +0000115 FunctionArgList &Params);
John McCall4c40d982010-08-31 07:33:07 +0000116
John McCallbd315742012-09-25 08:00:39 +0000117 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCallfd708262011-01-27 02:46:02 +0000118
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000119 void EmitConstructorCall(CodeGenFunction &CGF,
120 const CXXConstructorDecl *D, CXXCtorType Type,
121 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000122 llvm::Value *This,
123 CallExpr::const_arg_iterator ArgBeg,
124 CallExpr::const_arg_iterator ArgEnd);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000125
126 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
127 const CXXDestructorDecl *Dtor,
128 CXXDtorType DtorType, SourceLocation CallLoc,
129 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000130
Reid Kleckner90633022013-06-19 15:20:38 +0000131 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
132 const CXXRecordDecl *RD);
133
John McCall20bb1752012-05-01 06:13:13 +0000134 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
135 llvm::GlobalVariable *DeclPtr,
136 bool PerformInit);
137
John McCallfd708262011-01-27 02:46:02 +0000138 // ==== Notes on array cookies =========
139 //
140 // MSVC seems to only use cookies when the class has a destructor; a
141 // two-argument usual array deallocation function isn't sufficient.
142 //
143 // For example, this code prints "100" and "1":
144 // struct A {
145 // char x;
146 // void *operator new[](size_t sz) {
147 // printf("%u\n", sz);
148 // return malloc(sz);
149 // }
150 // void operator delete[](void *p, size_t sz) {
151 // printf("%u\n", sz);
152 // free(p);
153 // }
154 // };
155 // int main() {
156 // A *p = new A[100];
157 // delete[] p;
158 // }
159 // Whereas it prints "104" and "104" if you give A a destructor.
John McCalle2b45e22012-05-01 05:23:51 +0000160
161 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
162 bool requiresArrayCookie(const CXXNewExpr *expr);
163 CharUnits getArrayCookieSizeImpl(QualType type);
164 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
165 llvm::Value *NewPtr,
166 llvm::Value *NumElements,
167 const CXXNewExpr *expr,
168 QualType ElementType);
169 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
170 llvm::Value *allocPtr,
171 CharUnits cookieSize);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000172
173private:
Reid Klecknera3609b02013-04-11 18:13:19 +0000174 llvm::Constant *getZeroInt() {
175 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000176 }
177
Reid Klecknera3609b02013-04-11 18:13:19 +0000178 llvm::Constant *getAllOnesInt() {
179 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000180 }
181
Reid Klecknerf6327302013-05-09 21:01:17 +0000182 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
183 return C ? C : getZeroInt();
184 }
185
186 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
187 return C ? C : getZeroInt();
188 }
189
Reid Klecknera3609b02013-04-11 18:13:19 +0000190 void
191 GetNullMemberPointerFields(const MemberPointerType *MPT,
192 llvm::SmallVectorImpl<llvm::Constant *> &fields);
193
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000194 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
195 /// it is reusing a vbptr from a non-virtual base. RD must have morally
196 /// virtual bases.
197 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
198
199 /// \brief Shared code for virtual base adjustment. Returns the offset from
200 /// the vbptr to the virtual base. Optionally returns the address of the
201 /// vbptr itself.
202 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
203 llvm::Value *Base,
204 llvm::Value *VBPtrOffset,
205 llvm::Value *VBTableOffset,
206 llvm::Value **VBPtr = 0);
207
208 /// \brief Performs a full virtual base adjustment. Used to dereference
209 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-04-11 18:13:19 +0000210 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
211 llvm::Value *Base,
212 llvm::Value *VirtualBaseAdjustmentOffset,
213 llvm::Value *VBPtrOffset /* optional */);
214
Reid Kleckner79e02912013-05-03 01:15:11 +0000215 /// \brief Emits a full member pointer with the fields common to data and
216 /// function member pointers.
217 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
218 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000219 const CXXRecordDecl *RD,
220 CharUnits NonVirtualBaseAdjustment);
221
222 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
223 const CXXMethodDecl *MD,
224 CharUnits NonVirtualBaseAdjustment);
225
226 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
227 llvm::Constant *MP);
Reid Kleckner79e02912013-05-03 01:15:11 +0000228
Reid Kleckner90633022013-06-19 15:20:38 +0000229 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
230 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
231
232 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
233 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
234
Reid Klecknera8a0f762013-03-22 19:02:54 +0000235public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000236 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
237
238 virtual bool isZeroInitializable(const MemberPointerType *MPT);
239
Reid Klecknera8a0f762013-03-22 19:02:54 +0000240 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
241
242 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
243 CharUnits offset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000244 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
245 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000246
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000247 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
248 llvm::Value *L,
249 llvm::Value *R,
250 const MemberPointerType *MPT,
251 bool Inequality);
252
Reid Klecknera8a0f762013-03-22 19:02:54 +0000253 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
254 llvm::Value *MemPtr,
255 const MemberPointerType *MPT);
256
257 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
258 llvm::Value *Base,
259 llvm::Value *MemPtr,
260 const MemberPointerType *MPT);
261
Reid Klecknerf6327302013-05-09 21:01:17 +0000262 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
263 const CastExpr *E,
264 llvm::Value *Src);
265
266 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
267 llvm::Constant *Src);
268
Reid Klecknera3609b02013-04-11 18:13:19 +0000269 virtual llvm::Value *
270 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
271 llvm::Value *&This,
272 llvm::Value *MemPtr,
273 const MemberPointerType *MPT);
274
Reid Kleckner90633022013-06-19 15:20:38 +0000275private:
276 /// VBTables - All the vbtables which have been referenced.
277 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Charles Davisc3926642010-06-09 23:25:41 +0000278};
279
280}
281
John McCallecd03b42012-09-25 10:10:39 +0000282llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
283 llvm::Value *ptr,
284 QualType type) {
285 // FIXME: implement
286 return ptr;
287}
288
Reid Kleckner8c474322013-06-04 21:32:29 +0000289/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
290/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
291static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
292 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
293 E = RD->bases_end(); I != E; ++I) {
294 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
295 if (!I->isVirtual() && Base->getNumVBases() > 0)
296 return Base;
297 }
298 llvm_unreachable("RD must have an nv base with vbases");
299}
300
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000301CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
302 assert(RD->getNumVBases());
303 CharUnits Total = CharUnits::Zero();
304 while (RD) {
305 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
306 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
307 // -1 is the sentinel for no vbptr.
308 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
309 Total += VBPtrOffset;
310 break;
311 }
Reid Kleckner8c474322013-06-04 21:32:29 +0000312 RD = FindFirstNVBaseWithVBases(RD);
313 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000314 }
315 return Total;
316}
317
Reid Kleckner8c474322013-06-04 21:32:29 +0000318/// \brief Computes the index of BaseClassDecl in the vbtable of ClassDecl.
319/// BaseClassDecl must be a morally virtual base of ClassDecl. The vbtable is
320/// an array of i32 offsets. The first entry is a self entry, and the rest are
321/// offsets from the vbptr to virtual bases. The bases are ordered the same way
322/// our vbases are ordered: as they appear in a left-to-right depth-first search
323/// of the hierarchy.
324static unsigned GetVBTableIndex(const CXXRecordDecl *ClassDecl,
325 const CXXRecordDecl *BaseClassDecl) {
326 unsigned VBTableIndex = 1; // Start with one to skip the self entry.
327 for (CXXRecordDecl::base_class_const_iterator I = ClassDecl->vbases_begin(),
328 E = ClassDecl->vbases_end(); I != E; ++I) {
329 if (I->getType()->getAsCXXRecordDecl() == BaseClassDecl)
330 return VBTableIndex;
331 VBTableIndex++;
332 }
333 llvm_unreachable("BaseClassDecl must be a vbase of ClassDecl");
334}
335
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000336llvm::Value *
337MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
338 llvm::Value *This,
339 const CXXRecordDecl *ClassDecl,
340 const CXXRecordDecl *BaseClassDecl) {
341 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
342 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000343 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000344 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000345 llvm::Value *VBTableOffset =
346 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
347
348 llvm::Value *VBPtrToNewBase =
349 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
350 VBPtrToNewBase =
351 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
352 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
353}
354
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000355bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
356 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000357}
358
359void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
360 CXXCtorType Type,
361 CanQualType &ResTy,
362 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000363 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000364
365 const CXXRecordDecl *Class = Ctor->getParent();
366 if (Class->getNumVBases()) {
367 // Constructors of classes with virtual bases take an implicit parameter.
368 ArgTys.push_back(CGM.getContext().IntTy);
369 }
370}
371
Reid Kleckner90633022013-06-19 15:20:38 +0000372llvm::BasicBlock *
373MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
374 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000375 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
376 assert(IsMostDerivedClass &&
377 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000378 llvm::Value *IsCompleteObject =
379 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000380
381 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
382 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
383 CGF.Builder.CreateCondBr(IsCompleteObject,
384 CallVbaseCtorsBB, SkipVbaseCtorsBB);
385
386 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000387
388 // Fill in the vbtable pointers here.
389 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000390
391 // CGF will put the base ctor calls in this basic block for us later.
392
393 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000394}
395
Reid Kleckner90633022013-06-19 15:20:38 +0000396void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
397 const CXXRecordDecl *RD) {
398 llvm::Value *ThisInt8Ptr =
399 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
400
401 const VBTableVector &VBTables = EnumerateVBTables(RD);
402 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
403 I != E; ++I) {
404 const ASTRecordLayout &SubobjectLayout =
405 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
406 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
407 SubobjectLayout.getVBPtrOffset()).getQuantity();
408 llvm::Value *VBPtr =
409 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
410 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
411 "vbptr." + I->ReusingBase->getName());
412 CGF.Builder.CreateStore(I->GV, VBPtr);
413 }
414}
415
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000416void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
417 CXXDtorType Type,
418 CanQualType &ResTy,
419 SmallVectorImpl<CanQualType> &ArgTys) {
420 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000421
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000422 // TODO: 'for base' flag
423
424 if (Type == Dtor_Deleting) {
425 // The scalar deleting destructor takes an implicit bool parameter.
426 ArgTys.push_back(CGM.getContext().BoolTy);
427 }
428}
429
Reid Klecknera4130ba2013-07-22 13:51:44 +0000430void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
431 // The TU defining a dtor is only guaranteed to emit a base destructor. All
432 // other destructor variants are delegating thunks.
433 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
434}
435
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000436static bool IsDeletingDtor(GlobalDecl GD) {
437 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
438 if (isa<CXXDestructorDecl>(MD)) {
439 return GD.getDtorType() == Dtor_Deleting;
440 }
441 return false;
442}
443
John McCallbd315742012-09-25 08:00:39 +0000444void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
445 QualType &ResTy,
446 FunctionArgList &Params) {
447 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000448
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000449 ASTContext &Context = getContext();
450 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
451 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
452 ImplicitParamDecl *IsMostDerived
453 = ImplicitParamDecl::Create(Context, 0,
454 CGF.CurGD.getDecl()->getLocation(),
455 &Context.Idents.get("is_most_derived"),
456 Context.IntTy);
457 Params.push_back(IsMostDerived);
458 getStructorImplicitParamDecl(CGF) = IsMostDerived;
459 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000460 ImplicitParamDecl *ShouldDelete
461 = ImplicitParamDecl::Create(Context, 0,
462 CGF.CurGD.getDecl()->getLocation(),
463 &Context.Idents.get("should_call_delete"),
464 Context.BoolTy);
465 Params.push_back(ShouldDelete);
466 getStructorImplicitParamDecl(CGF) = ShouldDelete;
467 }
John McCallbd315742012-09-25 08:00:39 +0000468}
469
470void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
471 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000472
473 /// If this is a function that the ABI specifies returns 'this', initialize
474 /// the return slot to 'this' at the start of the function.
475 ///
476 /// Unlike the setting of return types, this is done within the ABI
477 /// implementation instead of by clients of CGCXXABI because:
478 /// 1) getThisValue is currently protected
479 /// 2) in theory, an ABI could implement 'this' returns some other way;
480 /// HasThisReturn only specifies a contract, not the implementation
481 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000482 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000483
484 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
485 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
486 assert(getStructorImplicitParamDecl(CGF) &&
487 "no implicit parameter for a constructor with virtual bases?");
488 getStructorImplicitParamValue(CGF)
489 = CGF.Builder.CreateLoad(
490 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
491 "is_most_derived");
492 }
493
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000494 if (IsDeletingDtor(CGF.CurGD)) {
495 assert(getStructorImplicitParamDecl(CGF) &&
496 "no implicit parameter for a deleting destructor?");
497 getStructorImplicitParamValue(CGF)
498 = CGF.Builder.CreateLoad(
499 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
500 "should_call_delete");
501 }
John McCallbd315742012-09-25 08:00:39 +0000502}
503
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000504void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000505 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000506 CXXCtorType Type,
507 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000508 bool Delegating,
509 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000510 CallExpr::const_arg_iterator ArgBeg,
511 CallExpr::const_arg_iterator ArgEnd) {
512 assert(Type == Ctor_Complete || Type == Ctor_Base);
513 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
514
515 llvm::Value *ImplicitParam = 0;
516 QualType ImplicitParamTy;
517 if (D->getParent()->getNumVBases()) {
518 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
519 ImplicitParamTy = getContext().IntTy;
520 }
521
522 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000523 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000524 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000525}
526
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000527void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
528 const CXXDestructorDecl *Dtor,
529 CXXDtorType DtorType,
530 SourceLocation CallLoc,
531 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000532 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
533
534 // We have only one destructor in the vftable but can get both behaviors
535 // by passing an implicit bool parameter.
536 const CGFunctionInfo *FInfo
537 = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
538 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov6e007f92013-07-19 08:14:45 +0000539 llvm::Value *Callee
540 = CGF.BuildVirtualCall(GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000541
542 ASTContext &Context = CGF.getContext();
543 llvm::Value *ImplicitParam
544 = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()),
545 DtorType == Dtor_Deleting);
546
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000547 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
548 ImplicitParam, Context.BoolTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000549}
550
Reid Kleckner90633022013-06-19 15:20:38 +0000551const VBTableVector &
552MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
553 // At this layer, we can key the cache off of a single class, which is much
554 // easier than caching at the GlobalVariable layer.
555 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
556 bool added;
557 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
558 VBTableVector &VBTables = I->second;
559 if (!added)
560 return VBTables;
561
562 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
563
564 return VBTables;
565}
566
567void MicrosoftCXXABI::EmitVirtualInheritanceTables(
568 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
569 const VBTableVector &VBTables = EnumerateVBTables(RD);
570 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
571 I != E; ++I) {
572 I->EmitVBTableDefinition(CGM, RD, Linkage);
573 }
574}
575
John McCalle2b45e22012-05-01 05:23:51 +0000576bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
577 QualType elementType) {
578 // Microsoft seems to completely ignore the possibility of a
579 // two-argument usual deallocation function.
580 return elementType.isDestructedType();
581}
582
583bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
584 // Microsoft seems to completely ignore the possibility of a
585 // two-argument usual deallocation function.
586 return expr->getAllocatedType().isDestructedType();
587}
588
589CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
590 // The array cookie is always a size_t; we then pad that out to the
591 // alignment of the element type.
592 ASTContext &Ctx = getContext();
593 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
594 Ctx.getTypeAlignInChars(type));
595}
596
597llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
598 llvm::Value *allocPtr,
599 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000600 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000601 llvm::Value *numElementsPtr =
602 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
603 return CGF.Builder.CreateLoad(numElementsPtr);
604}
605
606llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
607 llvm::Value *newPtr,
608 llvm::Value *numElements,
609 const CXXNewExpr *expr,
610 QualType elementType) {
611 assert(requiresArrayCookie(expr));
612
613 // The size of the cookie.
614 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
615
616 // Compute an offset to the cookie.
617 llvm::Value *cookiePtr = newPtr;
618
619 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000620 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000621 llvm::Value *numElementsPtr
622 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
623 CGF.Builder.CreateStore(numElements, numElementsPtr);
624
625 // Finally, compute a pointer to the actual data buffer by skipping
626 // over the cookie completely.
627 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
628 cookieSize.getQuantity());
629}
630
John McCall20bb1752012-05-01 06:13:13 +0000631void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
632 llvm::GlobalVariable *DeclPtr,
633 bool PerformInit) {
634 // FIXME: this code was only tested for global initialization.
635 // Not sure whether we want thread-safe static local variables as VS
636 // doesn't make them thread-safe.
637
Richard Smith04e51762013-04-14 23:01:42 +0000638 if (D.getTLSKind())
639 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
640
John McCall20bb1752012-05-01 06:13:13 +0000641 // Emit the initializer and add a global destructor if appropriate.
642 CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
643}
644
Reid Klecknera3609b02013-04-11 18:13:19 +0000645// Member pointer helpers.
646static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
647 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000648}
649
Reid Klecknerf6327302013-05-09 21:01:17 +0000650static bool hasOnlyOneField(bool IsMemberFunction,
651 MSInheritanceModel Inheritance) {
652 return Inheritance <= MSIM_SinglePolymorphic ||
653 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000654}
655
Reid Klecknera3609b02013-04-11 18:13:19 +0000656// Only member pointers to functions need a this adjustment, since it can be
657// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +0000658static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +0000659 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000660 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +0000661}
662
663static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
664 return Inheritance >= MSIM_Virtual;
665}
666
667// Use zero for the field offset of a null data member pointer if we can
668// guarantee that zero is not a valid field offset, or if the member pointer has
669// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
670// use zero for null. If there are multiple fields, we can use zero even if it
671// is a valid field offset because null-ness testing will check the other
672// fields.
673static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
674 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
675}
676
677bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
678 // Null-ness for function memptrs only depends on the first field, which is
679 // the function pointer. The rest don't matter, so we can zero initialize.
680 if (MPT->isMemberFunctionPointer())
681 return true;
682
683 // The virtual base adjustment field is always -1 for null, so if we have one
684 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
685 // valid field offset.
686 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
687 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
688 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
689 nullFieldOffsetIsZero(Inheritance));
690}
691
692llvm::Type *
693MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
694 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
695 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
696 llvm::SmallVector<llvm::Type *, 4> fields;
697 if (MPT->isMemberFunctionPointer())
698 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
699 else
700 fields.push_back(CGM.IntTy); // FieldOffset
701
Reid Kleckner79e02912013-05-03 01:15:11 +0000702 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
703 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000704 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +0000705 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000706 fields.push_back(CGM.IntTy);
707 if (hasVirtualBaseAdjustmentField(Inheritance))
708 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
709
710 if (fields.size() == 1)
711 return fields[0];
712 return llvm::StructType::get(CGM.getLLVMContext(), fields);
713}
714
715void MicrosoftCXXABI::
716GetNullMemberPointerFields(const MemberPointerType *MPT,
717 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
718 assert(fields.empty());
719 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
720 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
721 if (MPT->isMemberFunctionPointer()) {
722 // FunctionPointerOrVirtualThunk
723 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
724 } else {
725 if (nullFieldOffsetIsZero(Inheritance))
726 fields.push_back(getZeroInt()); // FieldOffset
727 else
728 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +0000729 }
Reid Klecknera3609b02013-04-11 18:13:19 +0000730
Reid Kleckner79e02912013-05-03 01:15:11 +0000731 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
732 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000733 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +0000734 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +0000735 fields.push_back(getZeroInt());
736 if (hasVirtualBaseAdjustmentField(Inheritance))
737 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +0000738}
739
740llvm::Constant *
741MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +0000742 llvm::SmallVector<llvm::Constant *, 4> fields;
743 GetNullMemberPointerFields(MPT, fields);
744 if (fields.size() == 1)
745 return fields[0];
746 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
747 assert(Res->getType() == ConvertMemberPointerType(MPT));
748 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000749}
750
751llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +0000752MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
753 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +0000754 const CXXRecordDecl *RD,
755 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +0000756{
Reid Klecknera3609b02013-04-11 18:13:19 +0000757 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +0000758
759 // Single inheritance class member pointer are represented as scalars instead
760 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +0000761 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +0000762 return FirstField;
763
Reid Klecknera3609b02013-04-11 18:13:19 +0000764 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +0000765 fields.push_back(FirstField);
766
767 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +0000768 fields.push_back(llvm::ConstantInt::get(
769 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +0000770
Reid Klecknera3609b02013-04-11 18:13:19 +0000771 if (hasVBPtrOffsetField(Inheritance)) {
Reid Klecknera06d5852013-06-05 15:58:29 +0000772 fields.push_back(llvm::ConstantInt::get(
773 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +0000774 }
Reid Kleckner79e02912013-05-03 01:15:11 +0000775
776 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +0000777 if (hasVirtualBaseAdjustmentField(Inheritance))
778 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +0000779
Reid Klecknera3609b02013-04-11 18:13:19 +0000780 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000781}
782
Reid Kleckner79e02912013-05-03 01:15:11 +0000783llvm::Constant *
784MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
785 CharUnits offset) {
786 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
787 llvm::Constant *FirstField =
788 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +0000789 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
790 CharUnits::Zero());
791}
792
793llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
794 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
795}
796
797llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
798 QualType MPType) {
799 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
800 const ValueDecl *MPD = MP.getMemberPointerDecl();
801 if (!MPD)
802 return EmitNullMemberPointer(MPT);
803
804 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
805
806 // FIXME PR15713: Support virtual inheritance paths.
807
808 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
809 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
810 MD, ThisAdjustment);
811
812 CharUnits FieldOffset =
813 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
814 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +0000815}
816
817llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +0000818MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
819 const CXXMethodDecl *MD,
820 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +0000821 assert(MD->isInstance() && "Member function must not be static!");
822 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +0000823 CodeGenTypes &Types = CGM.getTypes();
824
825 llvm::Constant *FirstField;
826 if (MD->isVirtual()) {
827 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
828 // the right offset.
829 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
830 } else {
831 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
832 llvm::Type *Ty;
833 // Check whether the function has a computable LLVM signature.
834 if (Types.isFuncTypeConvertible(FPT)) {
835 // The function has a computable LLVM signature; use the correct type.
836 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
837 } else {
838 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
839 // function type is incomplete.
840 Ty = CGM.PtrDiffTy;
841 }
842 FirstField = CGM.GetAddrOfFunction(MD, Ty);
843 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
844 }
845
846 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +0000847 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
848 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +0000849}
850
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000851/// Member pointers are the same if they're either bitwise identical *or* both
852/// null. Null-ness for function members is determined by the first field,
853/// while for data member pointers we must compare all fields.
854llvm::Value *
855MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
856 llvm::Value *L,
857 llvm::Value *R,
858 const MemberPointerType *MPT,
859 bool Inequality) {
860 CGBuilderTy &Builder = CGF.Builder;
861
862 // Handle != comparisons by switching the sense of all boolean operations.
863 llvm::ICmpInst::Predicate Eq;
864 llvm::Instruction::BinaryOps And, Or;
865 if (Inequality) {
866 Eq = llvm::ICmpInst::ICMP_NE;
867 And = llvm::Instruction::Or;
868 Or = llvm::Instruction::And;
869 } else {
870 Eq = llvm::ICmpInst::ICMP_EQ;
871 And = llvm::Instruction::And;
872 Or = llvm::Instruction::Or;
873 }
874
875 // If this is a single field member pointer (single inheritance), this is a
876 // single icmp.
877 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
878 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +0000879 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +0000880 return Builder.CreateICmp(Eq, L, R);
881
882 // Compare the first field.
883 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
884 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
885 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
886
887 // Compare everything other than the first field.
888 llvm::Value *Res = 0;
889 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
890 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
891 llvm::Value *LF = Builder.CreateExtractValue(L, I);
892 llvm::Value *RF = Builder.CreateExtractValue(R, I);
893 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
894 if (Res)
895 Res = Builder.CreateBinOp(And, Res, Cmp);
896 else
897 Res = Cmp;
898 }
899
900 // Check if the first field is 0 if this is a function pointer.
901 if (MPT->isMemberFunctionPointer()) {
902 // (l1 == r1 && ...) || l0 == 0
903 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
904 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
905 Res = Builder.CreateBinOp(Or, Res, IsZero);
906 }
907
908 // Combine the comparison of the first field, which must always be true for
909 // this comparison to succeeed.
910 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
911}
912
Reid Klecknera8a0f762013-03-22 19:02:54 +0000913llvm::Value *
914MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
915 llvm::Value *MemPtr,
916 const MemberPointerType *MPT) {
917 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +0000918 llvm::SmallVector<llvm::Constant *, 4> fields;
919 // We only need one field for member functions.
920 if (MPT->isMemberFunctionPointer())
921 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
922 else
923 GetNullMemberPointerFields(MPT, fields);
924 assert(!fields.empty());
925 llvm::Value *FirstField = MemPtr;
926 if (MemPtr->getType()->isStructTy())
927 FirstField = Builder.CreateExtractValue(MemPtr, 0);
928 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +0000929
Reid Klecknera3609b02013-04-11 18:13:19 +0000930 // For function member pointers, we only need to test the function pointer
931 // field. The other fields if any can be garbage.
932 if (MPT->isMemberFunctionPointer())
933 return Res;
934
935 // Otherwise, emit a series of compares and combine the results.
936 for (int I = 1, E = fields.size(); I < E; ++I) {
937 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
938 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
939 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
940 }
941 return Res;
942}
943
Reid Klecknerf6327302013-05-09 21:01:17 +0000944bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
945 llvm::Constant *Val) {
946 // Function pointers are null if the pointer in the first field is null.
947 if (MPT->isMemberFunctionPointer()) {
948 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
949 Val->getAggregateElement(0U) : Val;
950 return FirstField->isNullValue();
951 }
952
953 // If it's not a function pointer and it's zero initializable, we can easily
954 // check zero.
955 if (isZeroInitializable(MPT) && Val->isNullValue())
956 return true;
957
958 // Otherwise, break down all the fields for comparison. Hopefully these
959 // little Constants are reused, while a big null struct might not be.
960 llvm::SmallVector<llvm::Constant *, 4> Fields;
961 GetNullMemberPointerFields(MPT, Fields);
962 if (Fields.size() == 1) {
963 assert(Val->getType()->isIntegerTy());
964 return Val == Fields[0];
965 }
966
967 unsigned I, E;
968 for (I = 0, E = Fields.size(); I != E; ++I) {
969 if (Val->getAggregateElement(I) != Fields[I])
970 break;
971 }
972 return I == E;
973}
974
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000975llvm::Value *
976MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
977 llvm::Value *This,
978 llvm::Value *VBTableOffset,
979 llvm::Value *VBPtrOffset,
980 llvm::Value **VBPtrOut) {
981 CGBuilderTy &Builder = CGF.Builder;
982 // Load the vbtable pointer from the vbptr in the instance.
983 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
984 llvm::Value *VBPtr =
985 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
986 if (VBPtrOut) *VBPtrOut = VBPtr;
987 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
988 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
989
990 // Load an i32 offset from the vb-table.
991 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
992 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
993 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
994}
995
Reid Klecknera3609b02013-04-11 18:13:19 +0000996// Returns an adjusted base cast to i8*, since we do more address arithmetic on
997// it.
998llvm::Value *
999MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1000 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001001 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001002 llvm::Value *VBPtrOffset) {
1003 CGBuilderTy &Builder = CGF.Builder;
1004 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1005 llvm::BasicBlock *OriginalBB = 0;
1006 llvm::BasicBlock *SkipAdjustBB = 0;
1007 llvm::BasicBlock *VBaseAdjustBB = 0;
1008
1009 // In the unspecified inheritance model, there might not be a vbtable at all,
1010 // in which case we need to skip the virtual base lookup. If there is a
1011 // vbtable, the first entry is a no-op entry that gives back the original
1012 // base, so look for a virtual base adjustment offset of zero.
1013 if (VBPtrOffset) {
1014 OriginalBB = Builder.GetInsertBlock();
1015 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1016 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1017 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001018 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001019 "memptr.is_vbase");
1020 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1021 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001022 }
1023
Reid Klecknera3609b02013-04-11 18:13:19 +00001024 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1025 // know the vbptr offset.
1026 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001027 CharUnits offs = CharUnits::Zero();
1028 if (RD->getNumVBases()) {
1029 offs = GetVBPtrOffsetFromBases(RD);
1030 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001031 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1032 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001033 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001034 llvm::Value *VBaseOffs =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001035 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001036 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1037
1038 // Merge control flow with the case where we didn't have to adjust.
1039 if (VBaseAdjustBB) {
1040 Builder.CreateBr(SkipAdjustBB);
1041 CGF.EmitBlock(SkipAdjustBB);
1042 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1043 Phi->addIncoming(Base, OriginalBB);
1044 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1045 return Phi;
1046 }
1047 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001048}
1049
1050llvm::Value *
1051MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1052 llvm::Value *Base,
1053 llvm::Value *MemPtr,
1054 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001055 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001056 unsigned AS = Base->getType()->getPointerAddressSpace();
1057 llvm::Type *PType =
1058 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1059 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001060 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1061 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001062
Reid Klecknera3609b02013-04-11 18:13:19 +00001063 // Extract the fields we need, regardless of model. We'll apply them if we
1064 // have them.
1065 llvm::Value *FieldOffset = MemPtr;
1066 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1067 llvm::Value *VBPtrOffset = 0;
1068 if (MemPtr->getType()->isStructTy()) {
1069 // We need to extract values.
1070 unsigned I = 0;
1071 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1072 if (hasVBPtrOffsetField(Inheritance))
1073 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1074 if (hasVirtualBaseAdjustmentField(Inheritance))
1075 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001076 }
1077
Reid Klecknera3609b02013-04-11 18:13:19 +00001078 if (VirtualBaseAdjustmentOffset) {
1079 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1080 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001081 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001082 llvm::Value *Addr =
1083 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001084
1085 // Cast the address to the appropriate pointer type, adopting the address
1086 // space of the base pointer.
1087 return Builder.CreateBitCast(Addr, PType);
1088}
1089
Reid Klecknerf6327302013-05-09 21:01:17 +00001090static MSInheritanceModel
1091getInheritanceFromMemptr(const MemberPointerType *MPT) {
1092 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1093}
1094
1095llvm::Value *
1096MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1097 const CastExpr *E,
1098 llvm::Value *Src) {
1099 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1100 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1101 E->getCastKind() == CK_ReinterpretMemberPointer);
1102
1103 // Use constant emission if we can.
1104 if (isa<llvm::Constant>(Src))
1105 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1106
1107 // We may be adding or dropping fields from the member pointer, so we need
1108 // both types and the inheritance models of both records.
1109 const MemberPointerType *SrcTy =
1110 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1111 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1112 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1113 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1114 bool IsFunc = SrcTy->isMemberFunctionPointer();
1115
1116 // If the classes use the same null representation, reinterpret_cast is a nop.
1117 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1118 if (IsReinterpret && (IsFunc ||
1119 nullFieldOffsetIsZero(SrcInheritance) ==
1120 nullFieldOffsetIsZero(DstInheritance)))
1121 return Src;
1122
1123 CGBuilderTy &Builder = CGF.Builder;
1124
1125 // Branch past the conversion if Src is null.
1126 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1127 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1128
1129 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1130 // pointer value of the destination type.
1131 if (IsReinterpret) {
1132 // For reinterpret casts, sema ensures that src and dst are both functions
1133 // or data and have the same size, which means the LLVM types should match.
1134 assert(Src->getType() == DstNull->getType());
1135 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1136 }
1137
1138 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1139 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1140 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1141 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1142 CGF.EmitBlock(ConvertBB);
1143
1144 // Decompose src.
1145 llvm::Value *FirstField = Src;
1146 llvm::Value *NonVirtualBaseAdjustment = 0;
1147 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1148 llvm::Value *VBPtrOffset = 0;
1149 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1150 // We need to extract values.
1151 unsigned I = 0;
1152 FirstField = Builder.CreateExtractValue(Src, I++);
1153 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1154 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1155 if (hasVBPtrOffsetField(SrcInheritance))
1156 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1157 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1158 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1159 }
1160
1161 // For data pointers, we adjust the field offset directly. For functions, we
1162 // have a separate field.
1163 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1164 if (Adj) {
1165 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1166 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1167 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1168 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1169 NVAdjustField = getZeroInt();
1170 if (isDerivedToBase)
1171 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1172 else
1173 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1174 }
1175
1176 // FIXME PR15713: Support conversions through virtually derived classes.
1177
1178 // Recompose dst from the null struct and the adjusted fields from src.
1179 llvm::Value *Dst;
1180 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1181 Dst = FirstField;
1182 } else {
1183 Dst = llvm::UndefValue::get(DstNull->getType());
1184 unsigned Idx = 0;
1185 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1186 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1187 Dst = Builder.CreateInsertValue(
1188 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1189 if (hasVBPtrOffsetField(DstInheritance))
1190 Dst = Builder.CreateInsertValue(
1191 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1192 if (hasVirtualBaseAdjustmentField(DstInheritance))
1193 Dst = Builder.CreateInsertValue(
1194 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1195 }
1196 Builder.CreateBr(ContinueBB);
1197
1198 // In the continuation, choose between DstNull and Dst.
1199 CGF.EmitBlock(ContinueBB);
1200 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1201 Phi->addIncoming(DstNull, OriginalBB);
1202 Phi->addIncoming(Dst, ConvertBB);
1203 return Phi;
1204}
1205
1206llvm::Constant *
1207MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1208 llvm::Constant *Src) {
1209 const MemberPointerType *SrcTy =
1210 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1211 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1212
1213 // If src is null, emit a new null for dst. We can't return src because dst
1214 // might have a new representation.
1215 if (MemberPointerConstantIsNull(SrcTy, Src))
1216 return EmitNullMemberPointer(DstTy);
1217
1218 // We don't need to do anything for reinterpret_casts of non-null member
1219 // pointers. We should only get here when the two type representations have
1220 // the same size.
1221 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1222 return Src;
1223
1224 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1225 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1226
1227 // Decompose src.
1228 llvm::Constant *FirstField = Src;
1229 llvm::Constant *NonVirtualBaseAdjustment = 0;
1230 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1231 llvm::Constant *VBPtrOffset = 0;
1232 bool IsFunc = SrcTy->isMemberFunctionPointer();
1233 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1234 // We need to extract values.
1235 unsigned I = 0;
1236 FirstField = Src->getAggregateElement(I++);
1237 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1238 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1239 if (hasVBPtrOffsetField(SrcInheritance))
1240 VBPtrOffset = Src->getAggregateElement(I++);
1241 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1242 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1243 }
1244
1245 // For data pointers, we adjust the field offset directly. For functions, we
1246 // have a separate field.
1247 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1248 if (Adj) {
1249 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1250 llvm::Constant *&NVAdjustField =
1251 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1252 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1253 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1254 NVAdjustField = getZeroInt();
1255 if (IsDerivedToBase)
1256 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1257 else
1258 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1259 }
1260
1261 // FIXME PR15713: Support conversions through virtually derived classes.
1262
1263 // Recompose dst from the null struct and the adjusted fields from src.
1264 if (hasOnlyOneField(IsFunc, DstInheritance))
1265 return FirstField;
1266
1267 llvm::SmallVector<llvm::Constant *, 4> Fields;
1268 Fields.push_back(FirstField);
1269 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1270 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1271 if (hasVBPtrOffsetField(DstInheritance))
1272 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1273 if (hasVirtualBaseAdjustmentField(DstInheritance))
1274 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1275 return llvm::ConstantStruct::getAnon(Fields);
1276}
1277
Reid Klecknera3609b02013-04-11 18:13:19 +00001278llvm::Value *
1279MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1280 llvm::Value *&This,
1281 llvm::Value *MemPtr,
1282 const MemberPointerType *MPT) {
1283 assert(MPT->isMemberFunctionPointer());
1284 const FunctionProtoType *FPT =
1285 MPT->getPointeeType()->castAs<FunctionProtoType>();
1286 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1287 llvm::FunctionType *FTy =
1288 CGM.getTypes().GetFunctionType(
1289 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1290 CGBuilderTy &Builder = CGF.Builder;
1291
1292 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1293
1294 // Extract the fields we need, regardless of model. We'll apply them if we
1295 // have them.
1296 llvm::Value *FunctionPointer = MemPtr;
1297 llvm::Value *NonVirtualBaseAdjustment = NULL;
1298 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1299 llvm::Value *VBPtrOffset = NULL;
1300 if (MemPtr->getType()->isStructTy()) {
1301 // We need to extract values.
1302 unsigned I = 0;
1303 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001304 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1305 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001306 if (hasVBPtrOffsetField(Inheritance))
1307 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001308 if (hasVirtualBaseAdjustmentField(Inheritance))
1309 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1310 }
1311
1312 if (VirtualBaseAdjustmentOffset) {
1313 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1314 VBPtrOffset);
1315 }
1316
1317 if (NonVirtualBaseAdjustment) {
1318 // Apply the adjustment and cast back to the original struct type.
1319 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1320 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1321 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1322 }
1323
1324 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1325}
1326
Charles Davis071cc7d2010-08-16 03:33:14 +00001327CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001328 return new MicrosoftCXXABI(CGM);
1329}
1330