blob: de13116b875315690cb5dd8d59bdcce6c7632461 [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"
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davisc3926642010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis071cc7d2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davisc3926642010-06-09 23:25:41 +000032public:
Peter Collingbourne14110472011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall4c40d982010-08-31 07:33:07 +000034
Stephen Lin3b50e8d2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanoved23bdf2013-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 Kleckner9b601952013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos285baac2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikie2eb9a952012-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 Matos285baac2012-07-17 17:10:11 +000052
John McCallecd03b42012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerb0f533e2013-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 McCall4c40d982010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000066
Reid Kleckner90633022013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000069
Timur Iskhodzhanov5bd0d442013-10-09 18:16:58 +000070 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
71 const CXXRecordDecl *RD);
72
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +000073 void EmitCXXConstructors(const CXXConstructorDecl *D);
74
Reid Klecknera4130ba2013-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 McCall4c40d982010-08-31 07:33:07 +0000108 CXXDtorType Type,
109 CanQualType &ResTy,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000110 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +0000111
Reid Klecknera4130ba2013-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 Iskhodzhanov8f189a92013-08-21 06:25:03 +0000120 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
121 MD = MD->getCanonicalDecl();
122 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
123 MicrosoftVFTableContext::MethodVFTableLocation ML =
124 CGM.getVFTableContext().getMethodVFTableLocation(MD);
125 // 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 McCall4c40d982010-08-31 07:33:07 +0000141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +0000143 FunctionArgList &Params);
John McCall4c40d982010-08-31 07:33:07 +0000144
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000145 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
147
John McCallbd315742012-09-25 08:00:39 +0000148 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCallfd708262011-01-27 02:46:02 +0000149
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000150 void EmitConstructorCall(CodeGenFunction &CGF,
151 const CXXConstructorDecl *D, CXXCtorType Type,
152 bool ForVirtualBase, bool Delegating,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000153 llvm::Value *This,
154 CallExpr::const_arg_iterator ArgBeg,
155 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000156
Timur Iskhodzhanova53d7a02013-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 Iskhodzhanov8f189a92013-08-21 06:25:03 +0000171 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
172 llvm::Value *This, llvm::Type *Ty);
173
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000174 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
175 const CXXDestructorDecl *Dtor,
176 CXXDtorType DtorType, SourceLocation CallLoc,
177 llvm::Value *This);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000178
Timur Iskhodzhanov2cb17a02013-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 Iskhodzhanova53d7a02013-09-27 14:48:01 +0000187 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner90633022013-06-19 15:20:38 +0000188
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000189 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
190 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
191 }
192
Timur Iskhodzhanovc70cc5d2013-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 McCall20bb1752012-05-01 06:13:13 +0000199 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
200 llvm::GlobalVariable *DeclPtr,
201 bool PerformInit);
202
John McCallfd708262011-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 McCalle2b45e22012-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 Klecknera8a0f762013-03-22 19:02:54 +0000237
238private:
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000239 MicrosoftMangleContext &getMangleContext() {
240 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
241 }
242
Reid Klecknera3609b02013-04-11 18:13:19 +0000243 llvm::Constant *getZeroInt() {
244 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000245 }
246
Reid Klecknera3609b02013-04-11 18:13:19 +0000247 llvm::Constant *getAllOnesInt() {
248 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000249 }
250
Reid Klecknerf6327302013-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 Klecknera3609b02013-04-11 18:13:19 +0000259 void
260 GetNullMemberPointerFields(const MemberPointerType *MPT,
261 llvm::SmallVectorImpl<llvm::Constant *> &fields);
262
Reid Klecknerb0f533e2013-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 Iskhodzhanovc70cc5d2013-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 Klecknerb0f533e2013-05-29 18:02:47 +0000287 /// \brief Performs a full virtual base adjustment. Used to dereference
288 /// pointers to members of virtual bases.
Reid Klecknera3609b02013-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 Kleckner79e02912013-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 Klecknerf6327302013-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 Kleckner79e02912013-05-03 01:15:11 +0000307
Reid Kleckner90633022013-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 Klecknera8a0f762013-03-22 19:02:54 +0000314public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000315 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
316
317 virtual bool isZeroInitializable(const MemberPointerType *MPT);
318
Reid Klecknera8a0f762013-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 Kleckner79e02912013-05-03 01:15:11 +0000323 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
324 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000325
Reid Kleckner3d2f0002013-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 Klecknera8a0f762013-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 Klecknerf6327302013-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 Klecknera3609b02013-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 Kleckner90633022013-06-19 15:20:38 +0000354private:
Timur Iskhodzhanova53d7a02013-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 Kleckner90633022013-06-19 15:20:38 +0000365 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Kleckner942f9fe2013-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 Davisc3926642010-06-09 23:25:41 +0000378};
379
380}
381
John McCallecd03b42012-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 Kleckner8c474322013-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 Klecknerb0f533e2013-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 Kleckner8c474322013-06-04 21:32:29 +0000412 RD = FindFirstNVBaseWithVBases(RD);
413 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerb0f533e2013-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 Klecknerb0f533e2013-05-29 18:02:47 +0000425 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner8c474322013-06-04 21:32:29 +0000426 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000427 llvm::Value *VBTableOffset =
428 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
429
430 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov0e4f5592013-10-27 17:10:27 +0000431 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000432 VBPtrToNewBase =
433 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
434 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
435}
436
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000437bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
438 return isa<CXXConstructorDecl>(GD.getDecl());
John McCallbd315742012-09-25 08:00:39 +0000439}
440
441void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
442 CXXCtorType Type,
443 CanQualType &ResTy,
444 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000445 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000446
447 const CXXRecordDecl *Class = Ctor->getParent();
448 if (Class->getNumVBases()) {
449 // Constructors of classes with virtual bases take an implicit parameter.
450 ArgTys.push_back(CGM.getContext().IntTy);
451 }
452}
453
Reid Kleckner90633022013-06-19 15:20:38 +0000454llvm::BasicBlock *
455MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
456 const CXXRecordDecl *RD) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000457 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
458 assert(IsMostDerivedClass &&
459 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner90633022013-06-19 15:20:38 +0000460 llvm::Value *IsCompleteObject =
461 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000462
463 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
464 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
465 CGF.Builder.CreateCondBr(IsCompleteObject,
466 CallVbaseCtorsBB, SkipVbaseCtorsBB);
467
468 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner90633022013-06-19 15:20:38 +0000469
470 // Fill in the vbtable pointers here.
471 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000472
473 // CGF will put the base ctor calls in this basic block for us later.
474
475 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000476}
477
Timur Iskhodzhanov5bd0d442013-10-09 18:16:58 +0000478void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
479 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
480 // In most cases, an override for a vbase virtual method can adjust
481 // the "this" parameter by applying a constant offset.
482 // However, this is not enough while a constructor or a destructor of some
483 // class X is being executed if all the following conditions are met:
484 // - X has virtual bases, (1)
485 // - X overrides a virtual method M of a vbase Y, (2)
486 // - X itself is a vbase of the most derived class.
487 //
488 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
489 // which holds the extra amount of "this" adjustment we must do when we use
490 // the X vftables (i.e. during X ctor or dtor).
491 // Outside the ctors and dtors, the values of vtorDisps are zero.
492
493 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
494 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
495 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
496 CGBuilderTy &Builder = CGF.Builder;
497
498 unsigned AS =
499 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
500 llvm::Value *Int8This = 0; // Initialize lazily.
501
502 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
503 I != E; ++I) {
504 if (!I->second.hasVtorDisp())
505 continue;
506
507 llvm::Value *VBaseOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
508 CGF, getThisValue(CGF), RD, I->first);
509 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
510 // just to Trunc back immediately.
511 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
512 uint64_t ConstantVBaseOffset =
513 Layout.getVBaseClassOffset(I->first).getQuantity();
514
515 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
516 llvm::Value *VtorDispValue = Builder.CreateSub(
517 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
518 "vtordisp.value");
519
520 if (!Int8This)
521 Int8This = Builder.CreateBitCast(getThisValue(CGF),
522 CGF.Int8Ty->getPointerTo(AS));
523 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
524 // vtorDisp is always the 32-bits before the vbase in the class layout.
525 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
526 VtorDispPtr = Builder.CreateBitCast(
527 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
528
529 Builder.CreateStore(VtorDispValue, VtorDispPtr);
530 }
531}
532
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +0000533void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
534 // There's only one constructor type in this ABI.
535 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
536}
537
Reid Kleckner90633022013-06-19 15:20:38 +0000538void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
539 const CXXRecordDecl *RD) {
540 llvm::Value *ThisInt8Ptr =
541 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
542
543 const VBTableVector &VBTables = EnumerateVBTables(RD);
544 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
545 I != E; ++I) {
546 const ASTRecordLayout &SubobjectLayout =
547 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
548 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
549 SubobjectLayout.getVBPtrOffset()).getQuantity();
550 llvm::Value *VBPtr =
551 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
552 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
553 "vbptr." + I->ReusingBase->getName());
554 CGF.Builder.CreateStore(I->GV, VBPtr);
555 }
556}
557
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000558void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
559 CXXDtorType Type,
560 CanQualType &ResTy,
561 SmallVectorImpl<CanQualType> &ArgTys) {
562 // 'this' is already in place
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000563
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000564 // TODO: 'for base' flag
565
566 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000567 // The scalar deleting destructor takes an implicit int parameter.
568 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000569 }
570}
571
Reid Klecknera4130ba2013-07-22 13:51:44 +0000572void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
573 // The TU defining a dtor is only guaranteed to emit a base destructor. All
574 // other destructor variants are delegating thunks.
575 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
576}
577
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000578llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
579 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
580 GD = GD.getCanonicalDecl();
581 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000582 // FIXME: consider splitting the vdtor vs regular method code into two
583 // functions.
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000584
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000585 GlobalDecl LookupGD = GD;
586 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
587 // Complete dtors take a pointer to the complete object,
588 // thus don't need adjustment.
589 if (GD.getDtorType() == Dtor_Complete)
590 return This;
591
592 // There's only Dtor_Deleting in vftable but it shares the this adjustment
593 // with the base one, so look up the deleting one instead.
594 LookupGD = GlobalDecl(DD, Dtor_Deleting);
595 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000596 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000597 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000598
599 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
600 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000601 CharUnits StaticOffset = ML.VFTableOffset;
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000602 if (ML.VBase) {
603 bool AvoidVirtualOffset = false;
604 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
605 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanova7c8b102013-10-17 09:11:45 +0000606 // same record type or another destructor of a more derived type;
607 // or a constructor of the same record type if an exception is thrown.
608 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
609 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000610 const CXXRecordDecl *CurRD =
Timur Iskhodzhanova7c8b102013-10-17 09:11:45 +0000611 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000612
613 if (MD->getParent() == CurRD) {
Timur Iskhodzhanova7c8b102013-10-17 09:11:45 +0000614 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
615 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
616 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
617 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
618 // We're calling the main base dtor from a complete structor,
619 // so we know the "this" offset statically.
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000620 AvoidVirtualOffset = true;
621 } else {
622 // Let's see if we try to call a destructor of a non-virtual base.
623 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
624 E = CurRD->bases_end(); I != E; ++I) {
625 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
626 continue;
627 // If we call a base destructor for a non-virtual base, we statically
628 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanova7c8b102013-10-17 09:11:45 +0000629 // The total offset should reflect the adjustment done by
630 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000631 AvoidVirtualOffset = true;
632 break;
633 }
634 }
635 }
636
637 if (AvoidVirtualOffset) {
638 const ASTRecordLayout &Layout =
639 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000640 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
641 } else {
642 This = CGF.Builder.CreateBitCast(This, charPtrTy);
643 llvm::Value *VBaseOffset = CGM.getCXXABI()
644 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
645 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
646 }
647 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000648 if (!StaticOffset.isZero()) {
649 assert(StaticOffset.isPositive());
650 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov6d87e652013-10-22 18:15:24 +0000651 if (ML.VBase) {
652 // Non-virtual adjustment might result in a pointer outside the allocated
653 // object, e.g. if the final overrider class is laid out after the virtual
654 // base that declares a method in the most derived class.
655 // FIXME: Update the code that emits this adjustment in thunks prologues.
656 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
657 } else {
658 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
659 StaticOffset.getQuantity());
660 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000661 }
662 return This;
663}
664
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000665static bool IsDeletingDtor(GlobalDecl GD) {
666 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
667 if (isa<CXXDestructorDecl>(MD)) {
668 return GD.getDtorType() == Dtor_Deleting;
669 }
670 return false;
671}
672
John McCallbd315742012-09-25 08:00:39 +0000673void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
674 QualType &ResTy,
675 FunctionArgList &Params) {
676 BuildThisParam(CGF, Params);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000677
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000678 ASTContext &Context = getContext();
679 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
680 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
681 ImplicitParamDecl *IsMostDerived
682 = ImplicitParamDecl::Create(Context, 0,
683 CGF.CurGD.getDecl()->getLocation(),
684 &Context.Idents.get("is_most_derived"),
685 Context.IntTy);
686 Params.push_back(IsMostDerived);
687 getStructorImplicitParamDecl(CGF) = IsMostDerived;
688 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000689 ImplicitParamDecl *ShouldDelete
690 = ImplicitParamDecl::Create(Context, 0,
691 CGF.CurGD.getDecl()->getLocation(),
692 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000693 Context.IntTy);
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000694 Params.push_back(ShouldDelete);
695 getStructorImplicitParamDecl(CGF) = ShouldDelete;
696 }
John McCallbd315742012-09-25 08:00:39 +0000697}
698
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000699llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
700 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
701 GD = GD.getCanonicalDecl();
702 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000703
704 GlobalDecl LookupGD = GD;
705 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
706 // Complete destructors take a pointer to the complete object as a
707 // parameter, thus don't need this adjustment.
708 if (GD.getDtorType() == Dtor_Complete)
709 return This;
710
711 // There's no Dtor_Base in vftable but it shares the this adjustment with
712 // the deleting one, so look it up instead.
713 LookupGD = GlobalDecl(DD, Dtor_Deleting);
714 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000715
716 // In this ABI, every virtual function takes a pointer to one of the
717 // subobjects that first defines it as the 'this' parameter, rather than a
718 // pointer to ther final overrider subobject. Thus, we need to adjust it back
719 // to the final overrider subobject before use.
720 // See comments in the MicrosoftVFTableContext implementation for the details.
721
722 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000723 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000724 CharUnits Adjustment = ML.VFTableOffset;
725 if (ML.VBase) {
726 const ASTRecordLayout &DerivedLayout =
727 CGF.getContext().getASTRecordLayout(MD->getParent());
728 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
729 }
730
731 if (Adjustment.isZero())
732 return This;
733
734 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
735 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
736 *thisTy = This->getType();
737
738 This = CGF.Builder.CreateBitCast(This, charPtrTy);
739 assert(Adjustment.isPositive());
Timur Iskhodzhanov6d87e652013-10-22 18:15:24 +0000740 This =
741 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000742 return CGF.Builder.CreateBitCast(This, thisTy);
743}
744
John McCallbd315742012-09-25 08:00:39 +0000745void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
746 EmitThisParam(CGF);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000747
748 /// If this is a function that the ABI specifies returns 'this', initialize
749 /// the return slot to 'this' at the start of the function.
750 ///
751 /// Unlike the setting of return types, this is done within the ABI
752 /// implementation instead of by clients of CGCXXABI because:
753 /// 1) getThisValue is currently protected
754 /// 2) in theory, an ABI could implement 'this' returns some other way;
755 /// HasThisReturn only specifies a contract, not the implementation
756 if (HasThisReturn(CGF.CurGD))
John McCallbd315742012-09-25 08:00:39 +0000757 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000758
759 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
760 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
761 assert(getStructorImplicitParamDecl(CGF) &&
762 "no implicit parameter for a constructor with virtual bases?");
763 getStructorImplicitParamValue(CGF)
764 = CGF.Builder.CreateLoad(
765 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
766 "is_most_derived");
767 }
768
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000769 if (IsDeletingDtor(CGF.CurGD)) {
770 assert(getStructorImplicitParamDecl(CGF) &&
771 "no implicit parameter for a deleting destructor?");
772 getStructorImplicitParamValue(CGF)
773 = CGF.Builder.CreateLoad(
774 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
775 "should_call_delete");
776 }
John McCallbd315742012-09-25 08:00:39 +0000777}
778
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000779void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000780 const CXXConstructorDecl *D,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000781 CXXCtorType Type,
782 bool ForVirtualBase,
Stephen Lin4444dbb2013-06-19 18:10:35 +0000783 bool Delegating,
784 llvm::Value *This,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000785 CallExpr::const_arg_iterator ArgBeg,
786 CallExpr::const_arg_iterator ArgEnd) {
787 assert(Type == Ctor_Complete || Type == Ctor_Base);
788 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
789
790 llvm::Value *ImplicitParam = 0;
791 QualType ImplicitParamTy;
792 if (D->getParent()->getNumVBases()) {
793 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
794 ImplicitParamTy = getContext().IntTy;
795 }
796
797 // FIXME: Provide a source location here.
Stephen Lin4444dbb2013-06-19 18:10:35 +0000798 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000799 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000800}
801
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000802void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
803 const CXXRecordDecl *RD) {
804 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
805 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
806 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
807
808 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
809 E = VFPtrs.end(); I != E; ++I) {
810 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
811 if (VTable->hasInitializer())
812 continue;
813
814 const VTableLayout &VTLayout =
815 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
816 llvm::Constant *Init = CGVT.CreateVTableInitializer(
817 RD, VTLayout.vtable_component_begin(),
818 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
819 VTLayout.getNumVTableThunks());
820 VTable->setInitializer(Init);
821
822 VTable->setLinkage(Linkage);
823 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
824 }
825}
826
827llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
828 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
829 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
830 NeedsVirtualOffset = (NearestVBase != 0);
831
832 llvm::Value *VTableAddressPoint =
833 getAddrOfVTable(VTableClass, Base.getBaseOffset());
834 if (!VTableAddressPoint) {
835 assert(Base.getBase()->getNumVBases() &&
836 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
837 }
838 return VTableAddressPoint;
839}
840
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000841static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
842 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
843 SmallString<256> &Name) {
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000844 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000845 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000846}
847
848llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
849 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
850 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
851 assert(VTable && "Couldn't find a vftable for the given base?");
852 return VTable;
853}
854
855llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
856 CharUnits VPtrOffset) {
857 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
858 // shouldn't be used in the given record type. We want to cache this result in
859 // VFTablesMap, thus a simple zero check is not sufficient.
860 VFTableIdTy ID(RD, VPtrOffset);
861 VFTablesMapTy::iterator I;
862 bool Inserted;
863 llvm::tie(I, Inserted) = VFTablesMap.insert(
864 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
865 if (!Inserted)
866 return I->second;
867
868 llvm::GlobalVariable *&VTable = I->second;
869
870 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
871 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
872 VFTContext.getVFPtrOffsets(RD);
873
874 if (DeferredVFTables.insert(RD)) {
875 // We haven't processed this record type before.
876 // Queue up this v-table for possible deferred emission.
877 CGM.addDeferredVTable(RD);
878
879#ifndef NDEBUG
880 // Create all the vftables at once in order to make sure each vftable has
881 // a unique mangled name.
882 llvm::StringSet<> ObservedMangledNames;
883 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
884 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000885 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000886 if (!ObservedMangledNames.insert(Name.str()))
887 llvm_unreachable("Already saw this mangling before?");
888 }
889#endif
890 }
891
892 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
893 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
894 continue;
895
896 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
897 CGM.Int8PtrTy,
898 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
899 .getNumVTableComponents());
900
901 SmallString<256> Name;
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000902 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000903 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
904 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
905 VTable->setUnnamedAddr(true);
906 break;
907 }
908
909 return VTable;
910}
911
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000912llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
913 GlobalDecl GD,
914 llvm::Value *This,
915 llvm::Type *Ty) {
916 GD = GD.getCanonicalDecl();
917 CGBuilderTy &Builder = CGF.Builder;
918
919 Ty = Ty->getPointerTo()->getPointerTo();
920 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
921 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
922
923 MicrosoftVFTableContext::MethodVFTableLocation ML =
924 CGM.getVFTableContext().getMethodVFTableLocation(GD);
925 llvm::Value *VFuncPtr =
926 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
927 return Builder.CreateLoad(VFuncPtr);
928}
929
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000930void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
931 const CXXDestructorDecl *Dtor,
932 CXXDtorType DtorType,
933 SourceLocation CallLoc,
934 llvm::Value *This) {
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000935 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
936
937 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000938 // by passing an implicit int parameter.
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000939 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000940 const CGFunctionInfo *FInfo =
941 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000942 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000943 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000944
945 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000946 llvm::Value *ImplicitParam =
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000947 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000948 DtorType == Dtor_Deleting);
949
Timur Iskhodzhanov82552742013-10-16 18:24:06 +0000950 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000951 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov1f71f392013-08-27 10:38:19 +0000952 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000953}
954
Reid Kleckner90633022013-06-19 15:20:38 +0000955const VBTableVector &
956MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
957 // At this layer, we can key the cache off of a single class, which is much
958 // easier than caching at the GlobalVariable layer.
959 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
960 bool added;
961 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
962 VBTableVector &VBTables = I->second;
963 if (!added)
964 return VBTables;
965
966 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
967
968 return VBTables;
969}
970
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000971void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner90633022013-06-19 15:20:38 +0000972 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000973 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
974
Reid Kleckner90633022013-06-19 15:20:38 +0000975 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
976 I != E; ++I) {
977 I->EmitVBTableDefinition(CGM, RD, Linkage);
978 }
979}
980
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000981llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
982 llvm::Value *This,
983 const ThisAdjustment &TA) {
984 if (TA.isEmpty())
985 return This;
986
987 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
988
989 assert(TA.VCallOffsetOffset == 0 &&
990 "VtorDisp adjustment is not supported yet");
991
992 if (TA.NonVirtual) {
993 // Non-virtual adjustment might result in a pointer outside the allocated
994 // object, e.g. if the final overrider class is laid out after the virtual
995 // base that declares a method in the most derived class.
996 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
997 }
998
999 // Don't need to bitcast back, the call CodeGen will handle this.
1000 return V;
1001}
1002
1003llvm::Value *
1004MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1005 const ReturnAdjustment &RA) {
1006 if (RA.isEmpty())
1007 return Ret;
1008
1009 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1010
1011 if (RA.Virtual.Microsoft.VBIndex) {
1012 assert(RA.Virtual.Microsoft.VBIndex > 0);
1013 int32_t IntSize =
1014 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1015 llvm::Value *VBPtr;
1016 llvm::Value *VBaseOffset =
1017 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1018 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1019 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1020 }
1021
1022 if (RA.NonVirtual)
1023 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1024
1025 // Cast back to the original type.
1026 return CGF.Builder.CreateBitCast(V, Ret->getType());
1027}
1028
John McCalle2b45e22012-05-01 05:23:51 +00001029bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1030 QualType elementType) {
1031 // Microsoft seems to completely ignore the possibility of a
1032 // two-argument usual deallocation function.
1033 return elementType.isDestructedType();
1034}
1035
1036bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1037 // Microsoft seems to completely ignore the possibility of a
1038 // two-argument usual deallocation function.
1039 return expr->getAllocatedType().isDestructedType();
1040}
1041
1042CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1043 // The array cookie is always a size_t; we then pad that out to the
1044 // alignment of the element type.
1045 ASTContext &Ctx = getContext();
1046 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1047 Ctx.getTypeAlignInChars(type));
1048}
1049
1050llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1051 llvm::Value *allocPtr,
1052 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +00001053 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001054 llvm::Value *numElementsPtr =
1055 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1056 return CGF.Builder.CreateLoad(numElementsPtr);
1057}
1058
1059llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1060 llvm::Value *newPtr,
1061 llvm::Value *numElements,
1062 const CXXNewExpr *expr,
1063 QualType elementType) {
1064 assert(requiresArrayCookie(expr));
1065
1066 // The size of the cookie.
1067 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1068
1069 // Compute an offset to the cookie.
1070 llvm::Value *cookiePtr = newPtr;
1071
1072 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +00001073 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +00001074 llvm::Value *numElementsPtr
1075 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1076 CGF.Builder.CreateStore(numElements, numElementsPtr);
1077
1078 // Finally, compute a pointer to the actual data buffer by skipping
1079 // over the cookie completely.
1080 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1081 cookieSize.getQuantity());
1082}
1083
John McCall20bb1752012-05-01 06:13:13 +00001084void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Kleckner942f9fe2013-09-10 20:14:30 +00001085 llvm::GlobalVariable *GV,
John McCall20bb1752012-05-01 06:13:13 +00001086 bool PerformInit) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00001087 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1088 // threadsafe. Since the user may be linking in inline functions compiled by
1089 // cl.exe, there's no reason to provide a false sense of security by using
1090 // critical sections here.
John McCall20bb1752012-05-01 06:13:13 +00001091
Richard Smith04e51762013-04-14 23:01:42 +00001092 if (D.getTLSKind())
1093 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1094
Reid Kleckner942f9fe2013-09-10 20:14:30 +00001095 CGBuilderTy &Builder = CGF.Builder;
1096 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1097 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1098
1099 // Get the guard variable for this function if we have one already.
1100 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1101
1102 unsigned BitIndex;
1103 if (D.isExternallyVisible()) {
1104 // Externally visible variables have to be numbered in Sema to properly
1105 // handle unreachable VarDecls.
1106 BitIndex = getContext().getManglingNumber(&D);
1107 assert(BitIndex > 0);
1108 BitIndex--;
1109 } else {
1110 // Non-externally visible variables are numbered here in CodeGen.
1111 BitIndex = GI.BitIndex++;
1112 }
1113
1114 if (BitIndex >= 32) {
1115 if (D.isExternallyVisible())
1116 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1117 BitIndex %= 32;
1118 GI.Guard = 0;
1119 }
1120
1121 // Lazily create the i32 bitfield for this function.
1122 if (!GI.Guard) {
1123 // Mangle the name for the guard.
1124 SmallString<256> GuardName;
1125 {
1126 llvm::raw_svector_ostream Out(GuardName);
1127 getMangleContext().mangleStaticGuardVariable(&D, Out);
1128 Out.flush();
1129 }
1130
1131 // Create the guard variable with a zero-initializer. Just absorb linkage
1132 // and visibility from the guarded variable.
1133 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1134 GV->getLinkage(), Zero, GuardName.str());
1135 GI.Guard->setVisibility(GV->getVisibility());
1136 } else {
1137 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1138 "static local from the same function had different linkage");
1139 }
1140
1141 // Pseudo code for the test:
1142 // if (!(GuardVar & MyGuardBit)) {
1143 // GuardVar |= MyGuardBit;
1144 // ... initialize the object ...;
1145 // }
1146
1147 // Test our bit from the guard variable.
1148 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1149 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1150 llvm::Value *IsInitialized =
1151 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1152 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1153 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1154 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1155
1156 // Set our bit in the guard variable and emit the initializer and add a global
1157 // destructor if appropriate.
1158 CGF.EmitBlock(InitBlock);
1159 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1160 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1161 Builder.CreateBr(EndBlock);
1162
1163 // Continue.
1164 CGF.EmitBlock(EndBlock);
John McCall20bb1752012-05-01 06:13:13 +00001165}
1166
Reid Klecknera3609b02013-04-11 18:13:19 +00001167// Member pointer helpers.
1168static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1169 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001170}
1171
Reid Klecknerf6327302013-05-09 21:01:17 +00001172static bool hasOnlyOneField(bool IsMemberFunction,
1173 MSInheritanceModel Inheritance) {
1174 return Inheritance <= MSIM_SinglePolymorphic ||
1175 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001176}
1177
Reid Klecknera3609b02013-04-11 18:13:19 +00001178// Only member pointers to functions need a this adjustment, since it can be
1179// combined with the field offset for data pointers.
Reid Kleckner79e02912013-05-03 01:15:11 +00001180static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Klecknera3609b02013-04-11 18:13:19 +00001181 MSInheritanceModel Inheritance) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001182 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Klecknera3609b02013-04-11 18:13:19 +00001183}
1184
1185static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1186 return Inheritance >= MSIM_Virtual;
1187}
1188
1189// Use zero for the field offset of a null data member pointer if we can
1190// guarantee that zero is not a valid field offset, or if the member pointer has
1191// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1192// use zero for null. If there are multiple fields, we can use zero even if it
1193// is a valid field offset because null-ness testing will check the other
1194// fields.
1195static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1196 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1197}
1198
1199bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1200 // Null-ness for function memptrs only depends on the first field, which is
1201 // the function pointer. The rest don't matter, so we can zero initialize.
1202 if (MPT->isMemberFunctionPointer())
1203 return true;
1204
1205 // The virtual base adjustment field is always -1 for null, so if we have one
1206 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1207 // valid field offset.
1208 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1209 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1210 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1211 nullFieldOffsetIsZero(Inheritance));
1212}
1213
1214llvm::Type *
1215MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1216 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1217 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1218 llvm::SmallVector<llvm::Type *, 4> fields;
1219 if (MPT->isMemberFunctionPointer())
1220 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1221 else
1222 fields.push_back(CGM.IntTy); // FieldOffset
1223
Reid Kleckner79e02912013-05-03 01:15:11 +00001224 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1225 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001226 fields.push_back(CGM.IntTy);
Reid Kleckner79e02912013-05-03 01:15:11 +00001227 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001228 fields.push_back(CGM.IntTy);
1229 if (hasVirtualBaseAdjustmentField(Inheritance))
1230 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1231
1232 if (fields.size() == 1)
1233 return fields[0];
1234 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1235}
1236
1237void MicrosoftCXXABI::
1238GetNullMemberPointerFields(const MemberPointerType *MPT,
1239 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1240 assert(fields.empty());
1241 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1242 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1243 if (MPT->isMemberFunctionPointer()) {
1244 // FunctionPointerOrVirtualThunk
1245 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1246 } else {
1247 if (nullFieldOffsetIsZero(Inheritance))
1248 fields.push_back(getZeroInt()); // FieldOffset
1249 else
1250 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +00001251 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001252
Reid Kleckner79e02912013-05-03 01:15:11 +00001253 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1254 Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001255 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001256 if (hasVBPtrOffsetField(Inheritance))
Reid Klecknera3609b02013-04-11 18:13:19 +00001257 fields.push_back(getZeroInt());
1258 if (hasVirtualBaseAdjustmentField(Inheritance))
1259 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001260}
1261
1262llvm::Constant *
1263MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001264 llvm::SmallVector<llvm::Constant *, 4> fields;
1265 GetNullMemberPointerFields(MPT, fields);
1266 if (fields.size() == 1)
1267 return fields[0];
1268 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1269 assert(Res->getType() == ConvertMemberPointerType(MPT));
1270 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001271}
1272
1273llvm::Constant *
Reid Kleckner79e02912013-05-03 01:15:11 +00001274MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1275 bool IsMemberFunction,
Reid Klecknerf6327302013-05-09 21:01:17 +00001276 const CXXRecordDecl *RD,
1277 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner79e02912013-05-03 01:15:11 +00001278{
Reid Klecknera3609b02013-04-11 18:13:19 +00001279 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner79e02912013-05-03 01:15:11 +00001280
1281 // Single inheritance class member pointer are represented as scalars instead
1282 // of aggregates.
Reid Klecknerf6327302013-05-09 21:01:17 +00001283 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner79e02912013-05-03 01:15:11 +00001284 return FirstField;
1285
Reid Klecknera3609b02013-04-11 18:13:19 +00001286 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner79e02912013-05-03 01:15:11 +00001287 fields.push_back(FirstField);
1288
1289 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Klecknerf6327302013-05-09 21:01:17 +00001290 fields.push_back(llvm::ConstantInt::get(
1291 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner79e02912013-05-03 01:15:11 +00001292
Reid Klecknera3609b02013-04-11 18:13:19 +00001293 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckner42090d62013-10-15 01:18:02 +00001294 CharUnits Offs = CharUnits::Zero();
1295 if (RD->getNumVBases())
1296 Offs = GetVBPtrOffsetFromBases(RD);
1297 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Klecknera3609b02013-04-11 18:13:19 +00001298 }
Reid Kleckner79e02912013-05-03 01:15:11 +00001299
1300 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Klecknera3609b02013-04-11 18:13:19 +00001301 if (hasVirtualBaseAdjustmentField(Inheritance))
1302 fields.push_back(getZeroInt());
Reid Kleckner79e02912013-05-03 01:15:11 +00001303
Reid Klecknera3609b02013-04-11 18:13:19 +00001304 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001305}
1306
Reid Kleckner79e02912013-05-03 01:15:11 +00001307llvm::Constant *
1308MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1309 CharUnits offset) {
1310 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1311 llvm::Constant *FirstField =
1312 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Klecknerf6327302013-05-09 21:01:17 +00001313 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1314 CharUnits::Zero());
1315}
1316
1317llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1318 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1319}
1320
1321llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1322 QualType MPType) {
1323 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1324 const ValueDecl *MPD = MP.getMemberPointerDecl();
1325 if (!MPD)
1326 return EmitNullMemberPointer(MPT);
1327
1328 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1329
1330 // FIXME PR15713: Support virtual inheritance paths.
1331
1332 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1333 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1334 MD, ThisAdjustment);
1335
1336 CharUnits FieldOffset =
1337 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1338 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner79e02912013-05-03 01:15:11 +00001339}
1340
1341llvm::Constant *
Reid Klecknerf6327302013-05-09 21:01:17 +00001342MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1343 const CXXMethodDecl *MD,
1344 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner79e02912013-05-03 01:15:11 +00001345 assert(MD->isInstance() && "Member function must not be static!");
1346 MD = MD->getCanonicalDecl();
Reid Kleckner79e02912013-05-03 01:15:11 +00001347 CodeGenTypes &Types = CGM.getTypes();
1348
1349 llvm::Constant *FirstField;
1350 if (MD->isVirtual()) {
1351 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1352 // the right offset.
Reid Klecknerfa2264a2013-10-17 21:30:27 +00001353 CGM.ErrorUnsupported(MD, "pointer to virtual member function");
Reid Kleckner79e02912013-05-03 01:15:11 +00001354 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1355 } else {
1356 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1357 llvm::Type *Ty;
1358 // Check whether the function has a computable LLVM signature.
1359 if (Types.isFuncTypeConvertible(FPT)) {
1360 // The function has a computable LLVM signature; use the correct type.
1361 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1362 } else {
1363 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1364 // function type is incomplete.
1365 Ty = CGM.PtrDiffTy;
1366 }
1367 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1368 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1369 }
1370
1371 // The rest of the fields are common with data member pointers.
Reid Klecknerf6327302013-05-09 21:01:17 +00001372 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1373 NonVirtualBaseAdjustment);
Reid Kleckner79e02912013-05-03 01:15:11 +00001374}
1375
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001376/// Member pointers are the same if they're either bitwise identical *or* both
1377/// null. Null-ness for function members is determined by the first field,
1378/// while for data member pointers we must compare all fields.
1379llvm::Value *
1380MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1381 llvm::Value *L,
1382 llvm::Value *R,
1383 const MemberPointerType *MPT,
1384 bool Inequality) {
1385 CGBuilderTy &Builder = CGF.Builder;
1386
1387 // Handle != comparisons by switching the sense of all boolean operations.
1388 llvm::ICmpInst::Predicate Eq;
1389 llvm::Instruction::BinaryOps And, Or;
1390 if (Inequality) {
1391 Eq = llvm::ICmpInst::ICMP_NE;
1392 And = llvm::Instruction::Or;
1393 Or = llvm::Instruction::And;
1394 } else {
1395 Eq = llvm::ICmpInst::ICMP_EQ;
1396 And = llvm::Instruction::And;
1397 Or = llvm::Instruction::Or;
1398 }
1399
1400 // If this is a single field member pointer (single inheritance), this is a
1401 // single icmp.
1402 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1403 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknerf6327302013-05-09 21:01:17 +00001404 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner3d2f0002013-04-30 20:15:14 +00001405 return Builder.CreateICmp(Eq, L, R);
1406
1407 // Compare the first field.
1408 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1409 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1410 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1411
1412 // Compare everything other than the first field.
1413 llvm::Value *Res = 0;
1414 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1415 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1416 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1417 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1418 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1419 if (Res)
1420 Res = Builder.CreateBinOp(And, Res, Cmp);
1421 else
1422 Res = Cmp;
1423 }
1424
1425 // Check if the first field is 0 if this is a function pointer.
1426 if (MPT->isMemberFunctionPointer()) {
1427 // (l1 == r1 && ...) || l0 == 0
1428 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1429 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1430 Res = Builder.CreateBinOp(Or, Res, IsZero);
1431 }
1432
1433 // Combine the comparison of the first field, which must always be true for
1434 // this comparison to succeeed.
1435 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1436}
1437
Reid Klecknera8a0f762013-03-22 19:02:54 +00001438llvm::Value *
1439MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1440 llvm::Value *MemPtr,
1441 const MemberPointerType *MPT) {
1442 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001443 llvm::SmallVector<llvm::Constant *, 4> fields;
1444 // We only need one field for member functions.
1445 if (MPT->isMemberFunctionPointer())
1446 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1447 else
1448 GetNullMemberPointerFields(MPT, fields);
1449 assert(!fields.empty());
1450 llvm::Value *FirstField = MemPtr;
1451 if (MemPtr->getType()->isStructTy())
1452 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1453 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001454
Reid Klecknera3609b02013-04-11 18:13:19 +00001455 // For function member pointers, we only need to test the function pointer
1456 // field. The other fields if any can be garbage.
1457 if (MPT->isMemberFunctionPointer())
1458 return Res;
1459
1460 // Otherwise, emit a series of compares and combine the results.
1461 for (int I = 1, E = fields.size(); I < E; ++I) {
1462 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1463 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1464 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1465 }
1466 return Res;
1467}
1468
Reid Klecknerf6327302013-05-09 21:01:17 +00001469bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1470 llvm::Constant *Val) {
1471 // Function pointers are null if the pointer in the first field is null.
1472 if (MPT->isMemberFunctionPointer()) {
1473 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1474 Val->getAggregateElement(0U) : Val;
1475 return FirstField->isNullValue();
1476 }
1477
1478 // If it's not a function pointer and it's zero initializable, we can easily
1479 // check zero.
1480 if (isZeroInitializable(MPT) && Val->isNullValue())
1481 return true;
1482
1483 // Otherwise, break down all the fields for comparison. Hopefully these
1484 // little Constants are reused, while a big null struct might not be.
1485 llvm::SmallVector<llvm::Constant *, 4> Fields;
1486 GetNullMemberPointerFields(MPT, Fields);
1487 if (Fields.size() == 1) {
1488 assert(Val->getType()->isIntegerTy());
1489 return Val == Fields[0];
1490 }
1491
1492 unsigned I, E;
1493 for (I = 0, E = Fields.size(); I != E; ++I) {
1494 if (Val->getAggregateElement(I) != Fields[I])
1495 break;
1496 }
1497 return I == E;
1498}
1499
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001500llvm::Value *
1501MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1502 llvm::Value *This,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001503 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov0e4f5592013-10-27 17:10:27 +00001504 llvm::Value *VBTableOffset,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001505 llvm::Value **VBPtrOut) {
1506 CGBuilderTy &Builder = CGF.Builder;
1507 // Load the vbtable pointer from the vbptr in the instance.
1508 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1509 llvm::Value *VBPtr =
1510 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1511 if (VBPtrOut) *VBPtrOut = VBPtr;
1512 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1513 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1514
1515 // Load an i32 offset from the vb-table.
1516 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1517 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1518 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1519}
1520
Reid Klecknera3609b02013-04-11 18:13:19 +00001521// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1522// it.
1523llvm::Value *
1524MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1525 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001526 llvm::Value *VBTableOffset,
Reid Klecknera3609b02013-04-11 18:13:19 +00001527 llvm::Value *VBPtrOffset) {
1528 CGBuilderTy &Builder = CGF.Builder;
1529 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1530 llvm::BasicBlock *OriginalBB = 0;
1531 llvm::BasicBlock *SkipAdjustBB = 0;
1532 llvm::BasicBlock *VBaseAdjustBB = 0;
1533
1534 // In the unspecified inheritance model, there might not be a vbtable at all,
1535 // in which case we need to skip the virtual base lookup. If there is a
1536 // vbtable, the first entry is a no-op entry that gives back the original
1537 // base, so look for a virtual base adjustment offset of zero.
1538 if (VBPtrOffset) {
1539 OriginalBB = Builder.GetInsertBlock();
1540 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1541 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1542 llvm::Value *IsVirtual =
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001543 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Klecknera3609b02013-04-11 18:13:19 +00001544 "memptr.is_vbase");
1545 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1546 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001547 }
1548
Reid Klecknera3609b02013-04-11 18:13:19 +00001549 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1550 // know the vbptr offset.
1551 if (!VBPtrOffset) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001552 CharUnits offs = CharUnits::Zero();
1553 if (RD->getNumVBases()) {
1554 offs = GetVBPtrOffsetFromBases(RD);
1555 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001556 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1557 }
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001558 llvm::Value *VBPtr = 0;
Reid Klecknera3609b02013-04-11 18:13:19 +00001559 llvm::Value *VBaseOffs =
Timur Iskhodzhanov0e4f5592013-10-27 17:10:27 +00001560 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Klecknera3609b02013-04-11 18:13:19 +00001561 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1562
1563 // Merge control flow with the case where we didn't have to adjust.
1564 if (VBaseAdjustBB) {
1565 Builder.CreateBr(SkipAdjustBB);
1566 CGF.EmitBlock(SkipAdjustBB);
1567 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1568 Phi->addIncoming(Base, OriginalBB);
1569 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1570 return Phi;
1571 }
1572 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +00001573}
1574
1575llvm::Value *
1576MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1577 llvm::Value *Base,
1578 llvm::Value *MemPtr,
1579 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +00001580 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +00001581 unsigned AS = Base->getType()->getPointerAddressSpace();
1582 llvm::Type *PType =
1583 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1584 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +00001585 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1586 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +00001587
Reid Klecknera3609b02013-04-11 18:13:19 +00001588 // Extract the fields we need, regardless of model. We'll apply them if we
1589 // have them.
1590 llvm::Value *FieldOffset = MemPtr;
1591 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1592 llvm::Value *VBPtrOffset = 0;
1593 if (MemPtr->getType()->isStructTy()) {
1594 // We need to extract values.
1595 unsigned I = 0;
1596 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1597 if (hasVBPtrOffsetField(Inheritance))
1598 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1599 if (hasVirtualBaseAdjustmentField(Inheritance))
1600 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001601 }
1602
Reid Klecknera3609b02013-04-11 18:13:19 +00001603 if (VirtualBaseAdjustmentOffset) {
1604 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1605 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +00001606 }
Reid Klecknera3609b02013-04-11 18:13:19 +00001607 llvm::Value *Addr =
1608 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +00001609
1610 // Cast the address to the appropriate pointer type, adopting the address
1611 // space of the base pointer.
1612 return Builder.CreateBitCast(Addr, PType);
1613}
1614
Reid Klecknerf6327302013-05-09 21:01:17 +00001615static MSInheritanceModel
1616getInheritanceFromMemptr(const MemberPointerType *MPT) {
1617 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1618}
1619
1620llvm::Value *
1621MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1622 const CastExpr *E,
1623 llvm::Value *Src) {
1624 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1625 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1626 E->getCastKind() == CK_ReinterpretMemberPointer);
1627
1628 // Use constant emission if we can.
1629 if (isa<llvm::Constant>(Src))
1630 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1631
1632 // We may be adding or dropping fields from the member pointer, so we need
1633 // both types and the inheritance models of both records.
1634 const MemberPointerType *SrcTy =
1635 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1636 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1637 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1638 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1639 bool IsFunc = SrcTy->isMemberFunctionPointer();
1640
1641 // If the classes use the same null representation, reinterpret_cast is a nop.
1642 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1643 if (IsReinterpret && (IsFunc ||
1644 nullFieldOffsetIsZero(SrcInheritance) ==
1645 nullFieldOffsetIsZero(DstInheritance)))
1646 return Src;
1647
1648 CGBuilderTy &Builder = CGF.Builder;
1649
1650 // Branch past the conversion if Src is null.
1651 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1652 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1653
1654 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1655 // pointer value of the destination type.
1656 if (IsReinterpret) {
1657 // For reinterpret casts, sema ensures that src and dst are both functions
1658 // or data and have the same size, which means the LLVM types should match.
1659 assert(Src->getType() == DstNull->getType());
1660 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1661 }
1662
1663 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1664 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1665 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1666 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1667 CGF.EmitBlock(ConvertBB);
1668
1669 // Decompose src.
1670 llvm::Value *FirstField = Src;
1671 llvm::Value *NonVirtualBaseAdjustment = 0;
1672 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1673 llvm::Value *VBPtrOffset = 0;
1674 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1675 // We need to extract values.
1676 unsigned I = 0;
1677 FirstField = Builder.CreateExtractValue(Src, I++);
1678 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1679 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1680 if (hasVBPtrOffsetField(SrcInheritance))
1681 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1682 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1683 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1684 }
1685
1686 // For data pointers, we adjust the field offset directly. For functions, we
1687 // have a separate field.
1688 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1689 if (Adj) {
1690 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1691 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1692 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1693 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1694 NVAdjustField = getZeroInt();
1695 if (isDerivedToBase)
1696 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1697 else
1698 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1699 }
1700
1701 // FIXME PR15713: Support conversions through virtually derived classes.
1702
1703 // Recompose dst from the null struct and the adjusted fields from src.
1704 llvm::Value *Dst;
1705 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1706 Dst = FirstField;
1707 } else {
1708 Dst = llvm::UndefValue::get(DstNull->getType());
1709 unsigned Idx = 0;
1710 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1711 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1712 Dst = Builder.CreateInsertValue(
1713 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1714 if (hasVBPtrOffsetField(DstInheritance))
1715 Dst = Builder.CreateInsertValue(
1716 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1717 if (hasVirtualBaseAdjustmentField(DstInheritance))
1718 Dst = Builder.CreateInsertValue(
1719 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1720 }
1721 Builder.CreateBr(ContinueBB);
1722
1723 // In the continuation, choose between DstNull and Dst.
1724 CGF.EmitBlock(ContinueBB);
1725 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1726 Phi->addIncoming(DstNull, OriginalBB);
1727 Phi->addIncoming(Dst, ConvertBB);
1728 return Phi;
1729}
1730
1731llvm::Constant *
1732MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1733 llvm::Constant *Src) {
1734 const MemberPointerType *SrcTy =
1735 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1736 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1737
1738 // If src is null, emit a new null for dst. We can't return src because dst
1739 // might have a new representation.
1740 if (MemberPointerConstantIsNull(SrcTy, Src))
1741 return EmitNullMemberPointer(DstTy);
1742
1743 // We don't need to do anything for reinterpret_casts of non-null member
1744 // pointers. We should only get here when the two type representations have
1745 // the same size.
1746 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1747 return Src;
1748
1749 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1750 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1751
1752 // Decompose src.
1753 llvm::Constant *FirstField = Src;
1754 llvm::Constant *NonVirtualBaseAdjustment = 0;
1755 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1756 llvm::Constant *VBPtrOffset = 0;
1757 bool IsFunc = SrcTy->isMemberFunctionPointer();
1758 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1759 // We need to extract values.
1760 unsigned I = 0;
1761 FirstField = Src->getAggregateElement(I++);
1762 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1763 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1764 if (hasVBPtrOffsetField(SrcInheritance))
1765 VBPtrOffset = Src->getAggregateElement(I++);
1766 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1767 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1768 }
1769
1770 // For data pointers, we adjust the field offset directly. For functions, we
1771 // have a separate field.
1772 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1773 if (Adj) {
1774 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1775 llvm::Constant *&NVAdjustField =
1776 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1777 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1778 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1779 NVAdjustField = getZeroInt();
1780 if (IsDerivedToBase)
1781 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1782 else
1783 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1784 }
1785
1786 // FIXME PR15713: Support conversions through virtually derived classes.
1787
1788 // Recompose dst from the null struct and the adjusted fields from src.
1789 if (hasOnlyOneField(IsFunc, DstInheritance))
1790 return FirstField;
1791
1792 llvm::SmallVector<llvm::Constant *, 4> Fields;
1793 Fields.push_back(FirstField);
1794 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1795 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1796 if (hasVBPtrOffsetField(DstInheritance))
1797 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1798 if (hasVirtualBaseAdjustmentField(DstInheritance))
1799 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1800 return llvm::ConstantStruct::getAnon(Fields);
1801}
1802
Reid Klecknera3609b02013-04-11 18:13:19 +00001803llvm::Value *
1804MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1805 llvm::Value *&This,
1806 llvm::Value *MemPtr,
1807 const MemberPointerType *MPT) {
1808 assert(MPT->isMemberFunctionPointer());
1809 const FunctionProtoType *FPT =
1810 MPT->getPointeeType()->castAs<FunctionProtoType>();
1811 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1812 llvm::FunctionType *FTy =
1813 CGM.getTypes().GetFunctionType(
1814 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1815 CGBuilderTy &Builder = CGF.Builder;
1816
1817 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1818
1819 // Extract the fields we need, regardless of model. We'll apply them if we
1820 // have them.
1821 llvm::Value *FunctionPointer = MemPtr;
1822 llvm::Value *NonVirtualBaseAdjustment = NULL;
1823 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1824 llvm::Value *VBPtrOffset = NULL;
1825 if (MemPtr->getType()->isStructTy()) {
1826 // We need to extract values.
1827 unsigned I = 0;
1828 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001829 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1830 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner79e02912013-05-03 01:15:11 +00001831 if (hasVBPtrOffsetField(Inheritance))
1832 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera3609b02013-04-11 18:13:19 +00001833 if (hasVirtualBaseAdjustmentField(Inheritance))
1834 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1835 }
1836
1837 if (VirtualBaseAdjustmentOffset) {
1838 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1839 VBPtrOffset);
1840 }
1841
1842 if (NonVirtualBaseAdjustment) {
1843 // Apply the adjustment and cast back to the original struct type.
1844 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1845 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1846 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1847 }
1848
1849 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1850}
1851
Charles Davis071cc7d2010-08-16 03:33:14 +00001852CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +00001853 return new MicrosoftCXXABI(CGM);
1854}
1855