blob: 48bf6844f7fc851a1d9e23fcd920f6e73ee22646 [file] [log] [blame]
Charles Davis74ce8592010-06-09 23:25:41 +00001//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davis74ce8592010-06-09 23:25:41 +000011// The class in this file generates structures that follow the Microsoft
12// Visual C++ ABI, which is actually not very well documented at all outside
13// of Microsoft.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGCXXABI.h"
18#include "CodeGenModule.h"
Reid Kleckner7810af02013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davis74ce8592010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis53c59df2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000032public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000034
Stephen Lin9dc6eef2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000037 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
38 // Structures that are not C++03 PODs are always indirect.
39 return !RD->isPOD();
40 }
41
42 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos2ce88ef2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000049 // No known support for deleted functions in MSVC yet, so this choice is
50 // arbitrary.
51 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000052
John McCall82fb8922012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000057 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
58 llvm::Value *This,
59 const CXXRecordDecl *ClassDecl,
60 const CXXRecordDecl *BaseClassDecl);
61
John McCall5d865c322010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000066
Reid Kleckner7810af02013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000069
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000070 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
71 const CXXRecordDecl *RD);
72
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000073 void EmitCXXConstructors(const CXXConstructorDecl *D);
74
Reid Klecknere7de47e2013-07-22 13:51:44 +000075 // Background on MSVC destructors
76 // ==============================
77 //
78 // Both Itanium and MSVC ABIs have destructor variants. The variant names
79 // roughly correspond in the following way:
80 // Itanium Microsoft
81 // Base -> no name, just ~Class
82 // Complete -> vbase destructor
83 // Deleting -> scalar deleting destructor
84 // vector deleting destructor
85 //
86 // The base and complete destructors are the same as in Itanium, although the
87 // complete destructor does not accept a VTT parameter when there are virtual
88 // bases. A separate mechanism involving vtordisps is used to ensure that
89 // virtual methods of destroyed subobjects are not called.
90 //
91 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
92 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
93 // pointer points to an array. The scalar deleting destructor assumes that
94 // bit 2 is zero, and therefore does not contain a loop.
95 //
96 // For virtual destructors, only one entry is reserved in the vftable, and it
97 // always points to the vector deleting destructor. The vector deleting
98 // destructor is the most general, so it can be used to destroy objects in
99 // place, delete single heap objects, or delete arrays.
100 //
101 // A TU defining a non-inline destructor is only guaranteed to emit a base
102 // destructor, and all of the other variants are emitted on an as-needed basis
103 // in COMDATs. Because a non-base destructor can be emitted in a TU that
104 // lacks a definition for the destructor, non-base destructors must always
105 // delegate to or alias the base destructor.
106
107 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000108 CXXDtorType Type,
109 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000110 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000111
Reid Klecknere7de47e2013-07-22 13:51:44 +0000112 /// Non-base dtors should be emitted as delegating thunks in this ABI.
113 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
114 CXXDtorType DT) const {
115 return DT != Dtor_Base;
116 }
117
118 void EmitCXXDestructors(const CXXDestructorDecl *D);
119
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000120 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
121 MD = MD->getCanonicalDecl();
122 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
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 McCall5d865c322010-08-31 07:33:07 +0000141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +0000143 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000144
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000145 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
147
John McCall0f999f32012-09-25 08:00:39 +0000148 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000149
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000150 void EmitConstructorCall(CodeGenFunction &CGF,
151 const CXXConstructorDecl *D, CXXCtorType Type,
152 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000153 llvm::Value *This,
154 CallExpr::const_arg_iterator ArgBeg,
155 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000156
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000157 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
158
159 llvm::Value *getVTableAddressPointInStructor(
160 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
161 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
162 bool &NeedsVirtualOffset);
163
164 llvm::Constant *
165 getVTableAddressPointForConstExpr(BaseSubobject Base,
166 const CXXRecordDecl *VTableClass);
167
168 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
169 CharUnits VPtrOffset);
170
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
172 llvm::Value *This, llvm::Type *Ty);
173
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000174 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
175 const CXXDestructorDecl *Dtor,
176 CXXDtorType DtorType, SourceLocation CallLoc,
177 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000178
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000179 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
180 CallArgList &CallArgs) {
181 assert(GD.getDtorType() == Dtor_Deleting &&
182 "Only deleting destructor thunks are available in this ABI");
183 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
184 CGM.getContext().IntTy);
185 }
186
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000188
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000189 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
190 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
191 }
192
John McCallc84ed6a2012-05-01 06:13:13 +0000193 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
194 llvm::GlobalVariable *DeclPtr,
195 bool PerformInit);
196
John McCall29036752011-01-27 02:46:02 +0000197 // ==== Notes on array cookies =========
198 //
199 // MSVC seems to only use cookies when the class has a destructor; a
200 // two-argument usual array deallocation function isn't sufficient.
201 //
202 // For example, this code prints "100" and "1":
203 // struct A {
204 // char x;
205 // void *operator new[](size_t sz) {
206 // printf("%u\n", sz);
207 // return malloc(sz);
208 // }
209 // void operator delete[](void *p, size_t sz) {
210 // printf("%u\n", sz);
211 // free(p);
212 // }
213 // };
214 // int main() {
215 // A *p = new A[100];
216 // delete[] p;
217 // }
218 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000219
220 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
221 bool requiresArrayCookie(const CXXNewExpr *expr);
222 CharUnits getArrayCookieSizeImpl(QualType type);
223 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
224 llvm::Value *NewPtr,
225 llvm::Value *NumElements,
226 const CXXNewExpr *expr,
227 QualType ElementType);
228 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
229 llvm::Value *allocPtr,
230 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000231
232private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000233 MicrosoftMangleContext &getMangleContext() {
234 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
235 }
236
Reid Kleckner2341ae32013-04-11 18:13:19 +0000237 llvm::Constant *getZeroInt() {
238 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000239 }
240
Reid Kleckner2341ae32013-04-11 18:13:19 +0000241 llvm::Constant *getAllOnesInt() {
242 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000243 }
244
Reid Kleckner452abac2013-05-09 21:01:17 +0000245 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
246 return C ? C : getZeroInt();
247 }
248
249 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
250 return C ? C : getZeroInt();
251 }
252
Reid Kleckner2341ae32013-04-11 18:13:19 +0000253 void
254 GetNullMemberPointerFields(const MemberPointerType *MPT,
255 llvm::SmallVectorImpl<llvm::Constant *> &fields);
256
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000257 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
258 /// it is reusing a vbptr from a non-virtual base. RD must have morally
259 /// virtual bases.
260 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
261
262 /// \brief Shared code for virtual base adjustment. Returns the offset from
263 /// the vbptr to the virtual base. Optionally returns the address of the
264 /// vbptr itself.
265 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
266 llvm::Value *Base,
267 llvm::Value *VBPtrOffset,
268 llvm::Value *VBTableOffset,
269 llvm::Value **VBPtr = 0);
270
271 /// \brief Performs a full virtual base adjustment. Used to dereference
272 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000273 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
274 llvm::Value *Base,
275 llvm::Value *VirtualBaseAdjustmentOffset,
276 llvm::Value *VBPtrOffset /* optional */);
277
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000278 /// \brief Emits a full member pointer with the fields common to data and
279 /// function member pointers.
280 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
281 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000282 const CXXRecordDecl *RD,
283 CharUnits NonVirtualBaseAdjustment);
284
285 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
286 const CXXMethodDecl *MD,
287 CharUnits NonVirtualBaseAdjustment);
288
289 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
290 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000291
Reid Kleckner7810af02013-06-19 15:20:38 +0000292 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
293 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
294
295 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
296 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
297
Reid Kleckner407e8b62013-03-22 19:02:54 +0000298public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000299 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
300
301 virtual bool isZeroInitializable(const MemberPointerType *MPT);
302
Reid Kleckner407e8b62013-03-22 19:02:54 +0000303 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
304
305 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
306 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000307 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
308 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000309
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000310 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
311 llvm::Value *L,
312 llvm::Value *R,
313 const MemberPointerType *MPT,
314 bool Inequality);
315
Reid Kleckner407e8b62013-03-22 19:02:54 +0000316 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
317 llvm::Value *MemPtr,
318 const MemberPointerType *MPT);
319
320 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
321 llvm::Value *Base,
322 llvm::Value *MemPtr,
323 const MemberPointerType *MPT);
324
Reid Kleckner452abac2013-05-09 21:01:17 +0000325 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
326 const CastExpr *E,
327 llvm::Value *Src);
328
329 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
330 llvm::Constant *Src);
331
Reid Kleckner2341ae32013-04-11 18:13:19 +0000332 virtual llvm::Value *
333 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
334 llvm::Value *&This,
335 llvm::Value *MemPtr,
336 const MemberPointerType *MPT);
337
Reid Kleckner7810af02013-06-19 15:20:38 +0000338private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000339 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
340 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
341 /// \brief All the vftables that have been referenced.
342 VFTablesMapTy VFTablesMap;
343
344 /// \brief This set holds the record decls we've deferred vtable emission for.
345 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
346
347
348 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000349 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000350
351 /// Info on the global variable used to guard initialization of static locals.
352 /// The BitIndex field is only used for externally invisible declarations.
353 struct GuardInfo {
354 GuardInfo() : Guard(0), BitIndex(0) {}
355 llvm::GlobalVariable *Guard;
356 unsigned BitIndex;
357 };
358
359 /// Map from DeclContext to the current guard variable. We assume that the
360 /// AST is visited in source code order.
361 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000362};
363
364}
365
John McCall82fb8922012-09-25 10:10:39 +0000366llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
367 llvm::Value *ptr,
368 QualType type) {
369 // FIXME: implement
370 return ptr;
371}
372
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000373/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
374/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
375static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
376 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
377 E = RD->bases_end(); I != E; ++I) {
378 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
379 if (!I->isVirtual() && Base->getNumVBases() > 0)
380 return Base;
381 }
382 llvm_unreachable("RD must have an nv base with vbases");
383}
384
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000385CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
386 assert(RD->getNumVBases());
387 CharUnits Total = CharUnits::Zero();
388 while (RD) {
389 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
390 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
391 // -1 is the sentinel for no vbptr.
392 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
393 Total += VBPtrOffset;
394 break;
395 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000396 RD = FindFirstNVBaseWithVBases(RD);
397 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000398 }
399 return Total;
400}
401
402llvm::Value *
403MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
404 llvm::Value *This,
405 const CXXRecordDecl *ClassDecl,
406 const CXXRecordDecl *BaseClassDecl) {
407 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
408 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000409 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000410 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000411 llvm::Value *VBTableOffset =
412 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
413
414 llvm::Value *VBPtrToNewBase =
415 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
416 VBPtrToNewBase =
417 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
418 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
419}
420
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000421bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
422 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000423}
424
425void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
426 CXXCtorType Type,
427 CanQualType &ResTy,
428 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000429 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000430
431 const CXXRecordDecl *Class = Ctor->getParent();
432 if (Class->getNumVBases()) {
433 // Constructors of classes with virtual bases take an implicit parameter.
434 ArgTys.push_back(CGM.getContext().IntTy);
435 }
436}
437
Reid Kleckner7810af02013-06-19 15:20:38 +0000438llvm::BasicBlock *
439MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
440 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000441 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
442 assert(IsMostDerivedClass &&
443 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000444 llvm::Value *IsCompleteObject =
445 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000446
447 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
448 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
449 CGF.Builder.CreateCondBr(IsCompleteObject,
450 CallVbaseCtorsBB, SkipVbaseCtorsBB);
451
452 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000453
454 // Fill in the vbtable pointers here.
455 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000456
457 // CGF will put the base ctor calls in this basic block for us later.
458
459 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000460}
461
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000462void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
463 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
464 // In most cases, an override for a vbase virtual method can adjust
465 // the "this" parameter by applying a constant offset.
466 // However, this is not enough while a constructor or a destructor of some
467 // class X is being executed if all the following conditions are met:
468 // - X has virtual bases, (1)
469 // - X overrides a virtual method M of a vbase Y, (2)
470 // - X itself is a vbase of the most derived class.
471 //
472 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
473 // which holds the extra amount of "this" adjustment we must do when we use
474 // the X vftables (i.e. during X ctor or dtor).
475 // Outside the ctors and dtors, the values of vtorDisps are zero.
476
477 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
478 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
479 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
480 CGBuilderTy &Builder = CGF.Builder;
481
482 unsigned AS =
483 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
484 llvm::Value *Int8This = 0; // Initialize lazily.
485
486 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
487 I != E; ++I) {
488 if (!I->second.hasVtorDisp())
489 continue;
490
491 llvm::Value *VBaseOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
492 CGF, getThisValue(CGF), RD, I->first);
493 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
494 // just to Trunc back immediately.
495 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
496 uint64_t ConstantVBaseOffset =
497 Layout.getVBaseClassOffset(I->first).getQuantity();
498
499 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
500 llvm::Value *VtorDispValue = Builder.CreateSub(
501 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
502 "vtordisp.value");
503
504 if (!Int8This)
505 Int8This = Builder.CreateBitCast(getThisValue(CGF),
506 CGF.Int8Ty->getPointerTo(AS));
507 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
508 // vtorDisp is always the 32-bits before the vbase in the class layout.
509 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
510 VtorDispPtr = Builder.CreateBitCast(
511 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
512
513 Builder.CreateStore(VtorDispValue, VtorDispPtr);
514 }
515}
516
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000517void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
518 // There's only one constructor type in this ABI.
519 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
520}
521
Reid Kleckner7810af02013-06-19 15:20:38 +0000522void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
523 const CXXRecordDecl *RD) {
524 llvm::Value *ThisInt8Ptr =
525 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
526
527 const VBTableVector &VBTables = EnumerateVBTables(RD);
528 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
529 I != E; ++I) {
530 const ASTRecordLayout &SubobjectLayout =
531 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
532 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
533 SubobjectLayout.getVBPtrOffset()).getQuantity();
534 llvm::Value *VBPtr =
535 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
536 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
537 "vbptr." + I->ReusingBase->getName());
538 CGF.Builder.CreateStore(I->GV, VBPtr);
539 }
540}
541
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000542void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
543 CXXDtorType Type,
544 CanQualType &ResTy,
545 SmallVectorImpl<CanQualType> &ArgTys) {
546 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000547
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000548 // TODO: 'for base' flag
549
550 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000551 // The scalar deleting destructor takes an implicit int parameter.
552 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000553 }
554}
555
Reid Klecknere7de47e2013-07-22 13:51:44 +0000556void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
557 // The TU defining a dtor is only guaranteed to emit a base destructor. All
558 // other destructor variants are delegating thunks.
559 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
560}
561
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000562llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
563 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
564 GD = GD.getCanonicalDecl();
565 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000566 // FIXME: consider splitting the vdtor vs regular method code into two
567 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000568
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000569 GlobalDecl LookupGD = GD;
570 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
571 // Complete dtors take a pointer to the complete object,
572 // thus don't need adjustment.
573 if (GD.getDtorType() == Dtor_Complete)
574 return This;
575
576 // There's only Dtor_Deleting in vftable but it shares the this adjustment
577 // with the base one, so look up the deleting one instead.
578 LookupGD = GlobalDecl(DD, Dtor_Deleting);
579 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000580 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000581 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000582
583 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
584 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000585 CharUnits StaticOffset = ML.VFTableOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000586 if (ML.VBase) {
587 bool AvoidVirtualOffset = false;
588 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
589 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000590 // same record type or another destructor of a more derived type;
591 // or a constructor of the same record type if an exception is thrown.
592 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
593 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000594 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000595 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000596
597 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000598 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
599 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
600 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
601 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
602 // We're calling the main base dtor from a complete structor,
603 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000604 AvoidVirtualOffset = true;
605 } else {
606 // Let's see if we try to call a destructor of a non-virtual base.
607 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
608 E = CurRD->bases_end(); I != E; ++I) {
609 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
610 continue;
611 // If we call a base destructor for a non-virtual base, we statically
612 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000613 // The total offset should reflect the adjustment done by
614 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000615 AvoidVirtualOffset = true;
616 break;
617 }
618 }
619 }
620
621 if (AvoidVirtualOffset) {
622 const ASTRecordLayout &Layout =
623 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000624 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
625 } else {
626 This = CGF.Builder.CreateBitCast(This, charPtrTy);
627 llvm::Value *VBaseOffset = CGM.getCXXABI()
628 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
629 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
630 }
631 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000632 if (!StaticOffset.isZero()) {
633 assert(StaticOffset.isPositive());
634 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000635 if (ML.VBase) {
636 // Non-virtual adjustment might result in a pointer outside the allocated
637 // object, e.g. if the final overrider class is laid out after the virtual
638 // base that declares a method in the most derived class.
639 // FIXME: Update the code that emits this adjustment in thunks prologues.
640 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
641 } else {
642 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
643 StaticOffset.getQuantity());
644 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000645 }
646 return This;
647}
648
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000649static bool IsDeletingDtor(GlobalDecl GD) {
650 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
651 if (isa<CXXDestructorDecl>(MD)) {
652 return GD.getDtorType() == Dtor_Deleting;
653 }
654 return false;
655}
656
John McCall0f999f32012-09-25 08:00:39 +0000657void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
658 QualType &ResTy,
659 FunctionArgList &Params) {
660 BuildThisParam(CGF, Params);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000661
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000662 ASTContext &Context = getContext();
663 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
664 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
665 ImplicitParamDecl *IsMostDerived
666 = ImplicitParamDecl::Create(Context, 0,
667 CGF.CurGD.getDecl()->getLocation(),
668 &Context.Idents.get("is_most_derived"),
669 Context.IntTy);
670 Params.push_back(IsMostDerived);
671 getStructorImplicitParamDecl(CGF) = IsMostDerived;
672 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000673 ImplicitParamDecl *ShouldDelete
674 = ImplicitParamDecl::Create(Context, 0,
675 CGF.CurGD.getDecl()->getLocation(),
676 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000677 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000678 Params.push_back(ShouldDelete);
679 getStructorImplicitParamDecl(CGF) = ShouldDelete;
680 }
John McCall0f999f32012-09-25 08:00:39 +0000681}
682
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000683llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
684 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
685 GD = GD.getCanonicalDecl();
686 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000687
688 GlobalDecl LookupGD = GD;
689 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
690 // Complete destructors take a pointer to the complete object as a
691 // parameter, thus don't need this adjustment.
692 if (GD.getDtorType() == Dtor_Complete)
693 return This;
694
695 // There's no Dtor_Base in vftable but it shares the this adjustment with
696 // the deleting one, so look it up instead.
697 LookupGD = GlobalDecl(DD, Dtor_Deleting);
698 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000699
700 // In this ABI, every virtual function takes a pointer to one of the
701 // subobjects that first defines it as the 'this' parameter, rather than a
702 // pointer to ther final overrider subobject. Thus, we need to adjust it back
703 // to the final overrider subobject before use.
704 // See comments in the MicrosoftVFTableContext implementation for the details.
705
706 MicrosoftVFTableContext::MethodVFTableLocation ML =
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000707 CGM.getVFTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000708 CharUnits Adjustment = ML.VFTableOffset;
709 if (ML.VBase) {
710 const ASTRecordLayout &DerivedLayout =
711 CGF.getContext().getASTRecordLayout(MD->getParent());
712 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
713 }
714
715 if (Adjustment.isZero())
716 return This;
717
718 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
719 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
720 *thisTy = This->getType();
721
722 This = CGF.Builder.CreateBitCast(This, charPtrTy);
723 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000724 This =
725 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000726 return CGF.Builder.CreateBitCast(This, thisTy);
727}
728
John McCall0f999f32012-09-25 08:00:39 +0000729void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
730 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000731
732 /// If this is a function that the ABI specifies returns 'this', initialize
733 /// the return slot to 'this' at the start of the function.
734 ///
735 /// Unlike the setting of return types, this is done within the ABI
736 /// implementation instead of by clients of CGCXXABI because:
737 /// 1) getThisValue is currently protected
738 /// 2) in theory, an ABI could implement 'this' returns some other way;
739 /// HasThisReturn only specifies a contract, not the implementation
740 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000741 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000742
743 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
744 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
745 assert(getStructorImplicitParamDecl(CGF) &&
746 "no implicit parameter for a constructor with virtual bases?");
747 getStructorImplicitParamValue(CGF)
748 = CGF.Builder.CreateLoad(
749 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
750 "is_most_derived");
751 }
752
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000753 if (IsDeletingDtor(CGF.CurGD)) {
754 assert(getStructorImplicitParamDecl(CGF) &&
755 "no implicit parameter for a deleting destructor?");
756 getStructorImplicitParamValue(CGF)
757 = CGF.Builder.CreateLoad(
758 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
759 "should_call_delete");
760 }
John McCall0f999f32012-09-25 08:00:39 +0000761}
762
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000763void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Linc467c872013-06-19 18:10:35 +0000764 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000765 CXXCtorType Type,
766 bool ForVirtualBase,
Stephen Linc467c872013-06-19 18:10:35 +0000767 bool Delegating,
768 llvm::Value *This,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000769 CallExpr::const_arg_iterator ArgBeg,
770 CallExpr::const_arg_iterator ArgEnd) {
771 assert(Type == Ctor_Complete || Type == Ctor_Base);
772 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
773
774 llvm::Value *ImplicitParam = 0;
775 QualType ImplicitParamTy;
776 if (D->getParent()->getNumVBases()) {
777 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
778 ImplicitParamTy = getContext().IntTy;
779 }
780
781 // FIXME: Provide a source location here.
Stephen Linc467c872013-06-19 18:10:35 +0000782 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000783 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000784}
785
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000786void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
787 const CXXRecordDecl *RD) {
788 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
789 MicrosoftVFTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
790 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
791
792 for (MicrosoftVFTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
793 E = VFPtrs.end(); I != E; ++I) {
794 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
795 if (VTable->hasInitializer())
796 continue;
797
798 const VTableLayout &VTLayout =
799 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
800 llvm::Constant *Init = CGVT.CreateVTableInitializer(
801 RD, VTLayout.vtable_component_begin(),
802 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
803 VTLayout.getNumVTableThunks());
804 VTable->setInitializer(Init);
805
806 VTable->setLinkage(Linkage);
807 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
808 }
809}
810
811llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
812 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
813 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
814 NeedsVirtualOffset = (NearestVBase != 0);
815
816 llvm::Value *VTableAddressPoint =
817 getAddrOfVTable(VTableClass, Base.getBaseOffset());
818 if (!VTableAddressPoint) {
819 assert(Base.getBase()->getNumVBases() &&
820 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
821 }
822 return VTableAddressPoint;
823}
824
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000825static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
826 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
827 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000828 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000829 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000830}
831
832llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
833 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
834 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
835 assert(VTable && "Couldn't find a vftable for the given base?");
836 return VTable;
837}
838
839llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
840 CharUnits VPtrOffset) {
841 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
842 // shouldn't be used in the given record type. We want to cache this result in
843 // VFTablesMap, thus a simple zero check is not sufficient.
844 VFTableIdTy ID(RD, VPtrOffset);
845 VFTablesMapTy::iterator I;
846 bool Inserted;
847 llvm::tie(I, Inserted) = VFTablesMap.insert(
848 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
849 if (!Inserted)
850 return I->second;
851
852 llvm::GlobalVariable *&VTable = I->second;
853
854 MicrosoftVFTableContext &VFTContext = CGM.getVFTableContext();
855 const MicrosoftVFTableContext::VFPtrListTy &VFPtrs =
856 VFTContext.getVFPtrOffsets(RD);
857
858 if (DeferredVFTables.insert(RD)) {
859 // We haven't processed this record type before.
860 // Queue up this v-table for possible deferred emission.
861 CGM.addDeferredVTable(RD);
862
863#ifndef NDEBUG
864 // Create all the vftables at once in order to make sure each vftable has
865 // a unique mangled name.
866 llvm::StringSet<> ObservedMangledNames;
867 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
868 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000869 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000870 if (!ObservedMangledNames.insert(Name.str()))
871 llvm_unreachable("Already saw this mangling before?");
872 }
873#endif
874 }
875
876 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
877 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
878 continue;
879
880 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
881 CGM.Int8PtrTy,
882 VFTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
883 .getNumVTableComponents());
884
885 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000886 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000887 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
888 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
889 VTable->setUnnamedAddr(true);
890 break;
891 }
892
893 return VTable;
894}
895
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000896llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
897 GlobalDecl GD,
898 llvm::Value *This,
899 llvm::Type *Ty) {
900 GD = GD.getCanonicalDecl();
901 CGBuilderTy &Builder = CGF.Builder;
902
903 Ty = Ty->getPointerTo()->getPointerTo();
904 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
905 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
906
907 MicrosoftVFTableContext::MethodVFTableLocation ML =
908 CGM.getVFTableContext().getMethodVFTableLocation(GD);
909 llvm::Value *VFuncPtr =
910 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
911 return Builder.CreateLoad(VFuncPtr);
912}
913
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000914void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
915 const CXXDestructorDecl *Dtor,
916 CXXDtorType DtorType,
917 SourceLocation CallLoc,
918 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000919 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
920
921 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000922 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000923 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000924 const CGFunctionInfo *FInfo =
925 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000926 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000927 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000928
929 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000930 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000931 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000932 DtorType == Dtor_Deleting);
933
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000934 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000935 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000936 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000937}
938
Reid Kleckner7810af02013-06-19 15:20:38 +0000939const VBTableVector &
940MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
941 // At this layer, we can key the cache off of a single class, which is much
942 // easier than caching at the GlobalVariable layer.
943 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
944 bool added;
945 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
946 VBTableVector &VBTables = I->second;
947 if (!added)
948 return VBTables;
949
950 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
951
952 return VBTables;
953}
954
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000955void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +0000956 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000957 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
958
Reid Kleckner7810af02013-06-19 15:20:38 +0000959 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
960 I != E; ++I) {
961 I->EmitVBTableDefinition(CGM, RD, Linkage);
962 }
963}
964
John McCallb91cd662012-05-01 05:23:51 +0000965bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
966 QualType elementType) {
967 // Microsoft seems to completely ignore the possibility of a
968 // two-argument usual deallocation function.
969 return elementType.isDestructedType();
970}
971
972bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
973 // Microsoft seems to completely ignore the possibility of a
974 // two-argument usual deallocation function.
975 return expr->getAllocatedType().isDestructedType();
976}
977
978CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
979 // The array cookie is always a size_t; we then pad that out to the
980 // alignment of the element type.
981 ASTContext &Ctx = getContext();
982 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
983 Ctx.getTypeAlignInChars(type));
984}
985
986llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
987 llvm::Value *allocPtr,
988 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +0000989 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +0000990 llvm::Value *numElementsPtr =
991 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
992 return CGF.Builder.CreateLoad(numElementsPtr);
993}
994
995llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
996 llvm::Value *newPtr,
997 llvm::Value *numElements,
998 const CXXNewExpr *expr,
999 QualType elementType) {
1000 assert(requiresArrayCookie(expr));
1001
1002 // The size of the cookie.
1003 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1004
1005 // Compute an offset to the cookie.
1006 llvm::Value *cookiePtr = newPtr;
1007
1008 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001009 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001010 llvm::Value *numElementsPtr
1011 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1012 CGF.Builder.CreateStore(numElements, numElementsPtr);
1013
1014 // Finally, compute a pointer to the actual data buffer by skipping
1015 // over the cookie completely.
1016 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1017 cookieSize.getQuantity());
1018}
1019
John McCallc84ed6a2012-05-01 06:13:13 +00001020void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001021 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001022 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001023 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1024 // threadsafe. Since the user may be linking in inline functions compiled by
1025 // cl.exe, there's no reason to provide a false sense of security by using
1026 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001027
Richard Smithdbf74ba2013-04-14 23:01:42 +00001028 if (D.getTLSKind())
1029 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1030
Reid Klecknerd8110b62013-09-10 20:14:30 +00001031 CGBuilderTy &Builder = CGF.Builder;
1032 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1033 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1034
1035 // Get the guard variable for this function if we have one already.
1036 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1037
1038 unsigned BitIndex;
1039 if (D.isExternallyVisible()) {
1040 // Externally visible variables have to be numbered in Sema to properly
1041 // handle unreachable VarDecls.
1042 BitIndex = getContext().getManglingNumber(&D);
1043 assert(BitIndex > 0);
1044 BitIndex--;
1045 } else {
1046 // Non-externally visible variables are numbered here in CodeGen.
1047 BitIndex = GI.BitIndex++;
1048 }
1049
1050 if (BitIndex >= 32) {
1051 if (D.isExternallyVisible())
1052 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1053 BitIndex %= 32;
1054 GI.Guard = 0;
1055 }
1056
1057 // Lazily create the i32 bitfield for this function.
1058 if (!GI.Guard) {
1059 // Mangle the name for the guard.
1060 SmallString<256> GuardName;
1061 {
1062 llvm::raw_svector_ostream Out(GuardName);
1063 getMangleContext().mangleStaticGuardVariable(&D, Out);
1064 Out.flush();
1065 }
1066
1067 // Create the guard variable with a zero-initializer. Just absorb linkage
1068 // and visibility from the guarded variable.
1069 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1070 GV->getLinkage(), Zero, GuardName.str());
1071 GI.Guard->setVisibility(GV->getVisibility());
1072 } else {
1073 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1074 "static local from the same function had different linkage");
1075 }
1076
1077 // Pseudo code for the test:
1078 // if (!(GuardVar & MyGuardBit)) {
1079 // GuardVar |= MyGuardBit;
1080 // ... initialize the object ...;
1081 // }
1082
1083 // Test our bit from the guard variable.
1084 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1085 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1086 llvm::Value *IsInitialized =
1087 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1088 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1089 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1090 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1091
1092 // Set our bit in the guard variable and emit the initializer and add a global
1093 // destructor if appropriate.
1094 CGF.EmitBlock(InitBlock);
1095 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1096 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1097 Builder.CreateBr(EndBlock);
1098
1099 // Continue.
1100 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001101}
1102
Reid Kleckner2341ae32013-04-11 18:13:19 +00001103// Member pointer helpers.
1104static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1105 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001106}
1107
Reid Kleckner452abac2013-05-09 21:01:17 +00001108static bool hasOnlyOneField(bool IsMemberFunction,
1109 MSInheritanceModel Inheritance) {
1110 return Inheritance <= MSIM_SinglePolymorphic ||
1111 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001112}
1113
Reid Kleckner2341ae32013-04-11 18:13:19 +00001114// Only member pointers to functions need a this adjustment, since it can be
1115// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001116static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001117 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001118 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001119}
1120
1121static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1122 return Inheritance >= MSIM_Virtual;
1123}
1124
1125// Use zero for the field offset of a null data member pointer if we can
1126// guarantee that zero is not a valid field offset, or if the member pointer has
1127// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1128// use zero for null. If there are multiple fields, we can use zero even if it
1129// is a valid field offset because null-ness testing will check the other
1130// fields.
1131static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1132 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1133}
1134
1135bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1136 // Null-ness for function memptrs only depends on the first field, which is
1137 // the function pointer. The rest don't matter, so we can zero initialize.
1138 if (MPT->isMemberFunctionPointer())
1139 return true;
1140
1141 // The virtual base adjustment field is always -1 for null, so if we have one
1142 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1143 // valid field offset.
1144 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1145 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1146 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1147 nullFieldOffsetIsZero(Inheritance));
1148}
1149
1150llvm::Type *
1151MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1152 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1153 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1154 llvm::SmallVector<llvm::Type *, 4> fields;
1155 if (MPT->isMemberFunctionPointer())
1156 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1157 else
1158 fields.push_back(CGM.IntTy); // FieldOffset
1159
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001160 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1161 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001162 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001163 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001164 fields.push_back(CGM.IntTy);
1165 if (hasVirtualBaseAdjustmentField(Inheritance))
1166 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1167
1168 if (fields.size() == 1)
1169 return fields[0];
1170 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1171}
1172
1173void MicrosoftCXXABI::
1174GetNullMemberPointerFields(const MemberPointerType *MPT,
1175 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1176 assert(fields.empty());
1177 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1178 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1179 if (MPT->isMemberFunctionPointer()) {
1180 // FunctionPointerOrVirtualThunk
1181 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1182 } else {
1183 if (nullFieldOffsetIsZero(Inheritance))
1184 fields.push_back(getZeroInt()); // FieldOffset
1185 else
1186 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001187 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001188
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001189 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1190 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001191 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001192 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001193 fields.push_back(getZeroInt());
1194 if (hasVirtualBaseAdjustmentField(Inheritance))
1195 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001196}
1197
1198llvm::Constant *
1199MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001200 llvm::SmallVector<llvm::Constant *, 4> fields;
1201 GetNullMemberPointerFields(MPT, fields);
1202 if (fields.size() == 1)
1203 return fields[0];
1204 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1205 assert(Res->getType() == ConvertMemberPointerType(MPT));
1206 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001207}
1208
1209llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001210MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1211 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001212 const CXXRecordDecl *RD,
1213 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001214{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001215 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001216
1217 // Single inheritance class member pointer are represented as scalars instead
1218 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001219 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001220 return FirstField;
1221
Reid Kleckner2341ae32013-04-11 18:13:19 +00001222 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001223 fields.push_back(FirstField);
1224
1225 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001226 fields.push_back(llvm::ConstantInt::get(
1227 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001228
Reid Kleckner2341ae32013-04-11 18:13:19 +00001229 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001230 CharUnits Offs = CharUnits::Zero();
1231 if (RD->getNumVBases())
1232 Offs = GetVBPtrOffsetFromBases(RD);
1233 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001234 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001235
1236 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001237 if (hasVirtualBaseAdjustmentField(Inheritance))
1238 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001239
Reid Kleckner2341ae32013-04-11 18:13:19 +00001240 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001241}
1242
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001243llvm::Constant *
1244MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1245 CharUnits offset) {
1246 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1247 llvm::Constant *FirstField =
1248 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001249 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1250 CharUnits::Zero());
1251}
1252
1253llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1254 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1255}
1256
1257llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1258 QualType MPType) {
1259 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1260 const ValueDecl *MPD = MP.getMemberPointerDecl();
1261 if (!MPD)
1262 return EmitNullMemberPointer(MPT);
1263
1264 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1265
1266 // FIXME PR15713: Support virtual inheritance paths.
1267
1268 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1269 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1270 MD, ThisAdjustment);
1271
1272 CharUnits FieldOffset =
1273 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1274 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001275}
1276
1277llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001278MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1279 const CXXMethodDecl *MD,
1280 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001281 assert(MD->isInstance() && "Member function must not be static!");
1282 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001283 CodeGenTypes &Types = CGM.getTypes();
1284
1285 llvm::Constant *FirstField;
1286 if (MD->isVirtual()) {
1287 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
1288 // the right offset.
Reid Kleckner5a823d52013-10-17 21:30:27 +00001289 CGM.ErrorUnsupported(MD, "pointer to virtual member function");
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001290 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1291 } else {
1292 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1293 llvm::Type *Ty;
1294 // Check whether the function has a computable LLVM signature.
1295 if (Types.isFuncTypeConvertible(FPT)) {
1296 // The function has a computable LLVM signature; use the correct type.
1297 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1298 } else {
1299 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1300 // function type is incomplete.
1301 Ty = CGM.PtrDiffTy;
1302 }
1303 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1304 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1305 }
1306
1307 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001308 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1309 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001310}
1311
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001312/// Member pointers are the same if they're either bitwise identical *or* both
1313/// null. Null-ness for function members is determined by the first field,
1314/// while for data member pointers we must compare all fields.
1315llvm::Value *
1316MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1317 llvm::Value *L,
1318 llvm::Value *R,
1319 const MemberPointerType *MPT,
1320 bool Inequality) {
1321 CGBuilderTy &Builder = CGF.Builder;
1322
1323 // Handle != comparisons by switching the sense of all boolean operations.
1324 llvm::ICmpInst::Predicate Eq;
1325 llvm::Instruction::BinaryOps And, Or;
1326 if (Inequality) {
1327 Eq = llvm::ICmpInst::ICMP_NE;
1328 And = llvm::Instruction::Or;
1329 Or = llvm::Instruction::And;
1330 } else {
1331 Eq = llvm::ICmpInst::ICMP_EQ;
1332 And = llvm::Instruction::And;
1333 Or = llvm::Instruction::Or;
1334 }
1335
1336 // If this is a single field member pointer (single inheritance), this is a
1337 // single icmp.
1338 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1339 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001340 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001341 return Builder.CreateICmp(Eq, L, R);
1342
1343 // Compare the first field.
1344 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1345 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1346 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1347
1348 // Compare everything other than the first field.
1349 llvm::Value *Res = 0;
1350 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1351 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1352 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1353 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1354 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1355 if (Res)
1356 Res = Builder.CreateBinOp(And, Res, Cmp);
1357 else
1358 Res = Cmp;
1359 }
1360
1361 // Check if the first field is 0 if this is a function pointer.
1362 if (MPT->isMemberFunctionPointer()) {
1363 // (l1 == r1 && ...) || l0 == 0
1364 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1365 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1366 Res = Builder.CreateBinOp(Or, Res, IsZero);
1367 }
1368
1369 // Combine the comparison of the first field, which must always be true for
1370 // this comparison to succeeed.
1371 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1372}
1373
Reid Kleckner407e8b62013-03-22 19:02:54 +00001374llvm::Value *
1375MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1376 llvm::Value *MemPtr,
1377 const MemberPointerType *MPT) {
1378 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001379 llvm::SmallVector<llvm::Constant *, 4> fields;
1380 // We only need one field for member functions.
1381 if (MPT->isMemberFunctionPointer())
1382 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1383 else
1384 GetNullMemberPointerFields(MPT, fields);
1385 assert(!fields.empty());
1386 llvm::Value *FirstField = MemPtr;
1387 if (MemPtr->getType()->isStructTy())
1388 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1389 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001390
Reid Kleckner2341ae32013-04-11 18:13:19 +00001391 // For function member pointers, we only need to test the function pointer
1392 // field. The other fields if any can be garbage.
1393 if (MPT->isMemberFunctionPointer())
1394 return Res;
1395
1396 // Otherwise, emit a series of compares and combine the results.
1397 for (int I = 1, E = fields.size(); I < E; ++I) {
1398 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1399 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1400 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1401 }
1402 return Res;
1403}
1404
Reid Kleckner452abac2013-05-09 21:01:17 +00001405bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1406 llvm::Constant *Val) {
1407 // Function pointers are null if the pointer in the first field is null.
1408 if (MPT->isMemberFunctionPointer()) {
1409 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1410 Val->getAggregateElement(0U) : Val;
1411 return FirstField->isNullValue();
1412 }
1413
1414 // If it's not a function pointer and it's zero initializable, we can easily
1415 // check zero.
1416 if (isZeroInitializable(MPT) && Val->isNullValue())
1417 return true;
1418
1419 // Otherwise, break down all the fields for comparison. Hopefully these
1420 // little Constants are reused, while a big null struct might not be.
1421 llvm::SmallVector<llvm::Constant *, 4> Fields;
1422 GetNullMemberPointerFields(MPT, Fields);
1423 if (Fields.size() == 1) {
1424 assert(Val->getType()->isIntegerTy());
1425 return Val == Fields[0];
1426 }
1427
1428 unsigned I, E;
1429 for (I = 0, E = Fields.size(); I != E; ++I) {
1430 if (Val->getAggregateElement(I) != Fields[I])
1431 break;
1432 }
1433 return I == E;
1434}
1435
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001436llvm::Value *
1437MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1438 llvm::Value *This,
1439 llvm::Value *VBTableOffset,
1440 llvm::Value *VBPtrOffset,
1441 llvm::Value **VBPtrOut) {
1442 CGBuilderTy &Builder = CGF.Builder;
1443 // Load the vbtable pointer from the vbptr in the instance.
1444 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1445 llvm::Value *VBPtr =
1446 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1447 if (VBPtrOut) *VBPtrOut = VBPtr;
1448 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1449 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1450
1451 // Load an i32 offset from the vb-table.
1452 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1453 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1454 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1455}
1456
Reid Kleckner2341ae32013-04-11 18:13:19 +00001457// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1458// it.
1459llvm::Value *
1460MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1461 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001462 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001463 llvm::Value *VBPtrOffset) {
1464 CGBuilderTy &Builder = CGF.Builder;
1465 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1466 llvm::BasicBlock *OriginalBB = 0;
1467 llvm::BasicBlock *SkipAdjustBB = 0;
1468 llvm::BasicBlock *VBaseAdjustBB = 0;
1469
1470 // In the unspecified inheritance model, there might not be a vbtable at all,
1471 // in which case we need to skip the virtual base lookup. If there is a
1472 // vbtable, the first entry is a no-op entry that gives back the original
1473 // base, so look for a virtual base adjustment offset of zero.
1474 if (VBPtrOffset) {
1475 OriginalBB = Builder.GetInsertBlock();
1476 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1477 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1478 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001479 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001480 "memptr.is_vbase");
1481 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1482 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001483 }
1484
Reid Kleckner2341ae32013-04-11 18:13:19 +00001485 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1486 // know the vbptr offset.
1487 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001488 CharUnits offs = CharUnits::Zero();
1489 if (RD->getNumVBases()) {
1490 offs = GetVBPtrOffsetFromBases(RD);
1491 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001492 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1493 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001494 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001495 llvm::Value *VBaseOffs =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001496 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001497 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1498
1499 // Merge control flow with the case where we didn't have to adjust.
1500 if (VBaseAdjustBB) {
1501 Builder.CreateBr(SkipAdjustBB);
1502 CGF.EmitBlock(SkipAdjustBB);
1503 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1504 Phi->addIncoming(Base, OriginalBB);
1505 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1506 return Phi;
1507 }
1508 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001509}
1510
1511llvm::Value *
1512MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1513 llvm::Value *Base,
1514 llvm::Value *MemPtr,
1515 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001516 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001517 unsigned AS = Base->getType()->getPointerAddressSpace();
1518 llvm::Type *PType =
1519 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1520 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001521 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1522 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001523
Reid Kleckner2341ae32013-04-11 18:13:19 +00001524 // Extract the fields we need, regardless of model. We'll apply them if we
1525 // have them.
1526 llvm::Value *FieldOffset = MemPtr;
1527 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1528 llvm::Value *VBPtrOffset = 0;
1529 if (MemPtr->getType()->isStructTy()) {
1530 // We need to extract values.
1531 unsigned I = 0;
1532 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1533 if (hasVBPtrOffsetField(Inheritance))
1534 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1535 if (hasVirtualBaseAdjustmentField(Inheritance))
1536 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001537 }
1538
Reid Kleckner2341ae32013-04-11 18:13:19 +00001539 if (VirtualBaseAdjustmentOffset) {
1540 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1541 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001542 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001543 llvm::Value *Addr =
1544 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001545
1546 // Cast the address to the appropriate pointer type, adopting the address
1547 // space of the base pointer.
1548 return Builder.CreateBitCast(Addr, PType);
1549}
1550
Reid Kleckner452abac2013-05-09 21:01:17 +00001551static MSInheritanceModel
1552getInheritanceFromMemptr(const MemberPointerType *MPT) {
1553 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1554}
1555
1556llvm::Value *
1557MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1558 const CastExpr *E,
1559 llvm::Value *Src) {
1560 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1561 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1562 E->getCastKind() == CK_ReinterpretMemberPointer);
1563
1564 // Use constant emission if we can.
1565 if (isa<llvm::Constant>(Src))
1566 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1567
1568 // We may be adding or dropping fields from the member pointer, so we need
1569 // both types and the inheritance models of both records.
1570 const MemberPointerType *SrcTy =
1571 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1572 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1573 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1574 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1575 bool IsFunc = SrcTy->isMemberFunctionPointer();
1576
1577 // If the classes use the same null representation, reinterpret_cast is a nop.
1578 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1579 if (IsReinterpret && (IsFunc ||
1580 nullFieldOffsetIsZero(SrcInheritance) ==
1581 nullFieldOffsetIsZero(DstInheritance)))
1582 return Src;
1583
1584 CGBuilderTy &Builder = CGF.Builder;
1585
1586 // Branch past the conversion if Src is null.
1587 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1588 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1589
1590 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1591 // pointer value of the destination type.
1592 if (IsReinterpret) {
1593 // For reinterpret casts, sema ensures that src and dst are both functions
1594 // or data and have the same size, which means the LLVM types should match.
1595 assert(Src->getType() == DstNull->getType());
1596 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1597 }
1598
1599 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1600 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1601 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1602 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1603 CGF.EmitBlock(ConvertBB);
1604
1605 // Decompose src.
1606 llvm::Value *FirstField = Src;
1607 llvm::Value *NonVirtualBaseAdjustment = 0;
1608 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1609 llvm::Value *VBPtrOffset = 0;
1610 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1611 // We need to extract values.
1612 unsigned I = 0;
1613 FirstField = Builder.CreateExtractValue(Src, I++);
1614 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1615 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1616 if (hasVBPtrOffsetField(SrcInheritance))
1617 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1618 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1619 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1620 }
1621
1622 // For data pointers, we adjust the field offset directly. For functions, we
1623 // have a separate field.
1624 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1625 if (Adj) {
1626 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1627 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1628 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1629 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1630 NVAdjustField = getZeroInt();
1631 if (isDerivedToBase)
1632 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1633 else
1634 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1635 }
1636
1637 // FIXME PR15713: Support conversions through virtually derived classes.
1638
1639 // Recompose dst from the null struct and the adjusted fields from src.
1640 llvm::Value *Dst;
1641 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1642 Dst = FirstField;
1643 } else {
1644 Dst = llvm::UndefValue::get(DstNull->getType());
1645 unsigned Idx = 0;
1646 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1647 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1648 Dst = Builder.CreateInsertValue(
1649 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1650 if (hasVBPtrOffsetField(DstInheritance))
1651 Dst = Builder.CreateInsertValue(
1652 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1653 if (hasVirtualBaseAdjustmentField(DstInheritance))
1654 Dst = Builder.CreateInsertValue(
1655 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1656 }
1657 Builder.CreateBr(ContinueBB);
1658
1659 // In the continuation, choose between DstNull and Dst.
1660 CGF.EmitBlock(ContinueBB);
1661 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1662 Phi->addIncoming(DstNull, OriginalBB);
1663 Phi->addIncoming(Dst, ConvertBB);
1664 return Phi;
1665}
1666
1667llvm::Constant *
1668MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1669 llvm::Constant *Src) {
1670 const MemberPointerType *SrcTy =
1671 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1672 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1673
1674 // If src is null, emit a new null for dst. We can't return src because dst
1675 // might have a new representation.
1676 if (MemberPointerConstantIsNull(SrcTy, Src))
1677 return EmitNullMemberPointer(DstTy);
1678
1679 // We don't need to do anything for reinterpret_casts of non-null member
1680 // pointers. We should only get here when the two type representations have
1681 // the same size.
1682 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1683 return Src;
1684
1685 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1686 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1687
1688 // Decompose src.
1689 llvm::Constant *FirstField = Src;
1690 llvm::Constant *NonVirtualBaseAdjustment = 0;
1691 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1692 llvm::Constant *VBPtrOffset = 0;
1693 bool IsFunc = SrcTy->isMemberFunctionPointer();
1694 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1695 // We need to extract values.
1696 unsigned I = 0;
1697 FirstField = Src->getAggregateElement(I++);
1698 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1699 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1700 if (hasVBPtrOffsetField(SrcInheritance))
1701 VBPtrOffset = Src->getAggregateElement(I++);
1702 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1703 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1704 }
1705
1706 // For data pointers, we adjust the field offset directly. For functions, we
1707 // have a separate field.
1708 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1709 if (Adj) {
1710 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1711 llvm::Constant *&NVAdjustField =
1712 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1713 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1714 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1715 NVAdjustField = getZeroInt();
1716 if (IsDerivedToBase)
1717 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1718 else
1719 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1720 }
1721
1722 // FIXME PR15713: Support conversions through virtually derived classes.
1723
1724 // Recompose dst from the null struct and the adjusted fields from src.
1725 if (hasOnlyOneField(IsFunc, DstInheritance))
1726 return FirstField;
1727
1728 llvm::SmallVector<llvm::Constant *, 4> Fields;
1729 Fields.push_back(FirstField);
1730 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1731 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1732 if (hasVBPtrOffsetField(DstInheritance))
1733 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1734 if (hasVirtualBaseAdjustmentField(DstInheritance))
1735 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1736 return llvm::ConstantStruct::getAnon(Fields);
1737}
1738
Reid Kleckner2341ae32013-04-11 18:13:19 +00001739llvm::Value *
1740MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1741 llvm::Value *&This,
1742 llvm::Value *MemPtr,
1743 const MemberPointerType *MPT) {
1744 assert(MPT->isMemberFunctionPointer());
1745 const FunctionProtoType *FPT =
1746 MPT->getPointeeType()->castAs<FunctionProtoType>();
1747 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1748 llvm::FunctionType *FTy =
1749 CGM.getTypes().GetFunctionType(
1750 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1751 CGBuilderTy &Builder = CGF.Builder;
1752
1753 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1754
1755 // Extract the fields we need, regardless of model. We'll apply them if we
1756 // have them.
1757 llvm::Value *FunctionPointer = MemPtr;
1758 llvm::Value *NonVirtualBaseAdjustment = NULL;
1759 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1760 llvm::Value *VBPtrOffset = NULL;
1761 if (MemPtr->getType()->isStructTy()) {
1762 // We need to extract values.
1763 unsigned I = 0;
1764 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001765 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1766 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001767 if (hasVBPtrOffsetField(Inheritance))
1768 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001769 if (hasVirtualBaseAdjustmentField(Inheritance))
1770 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1771 }
1772
1773 if (VirtualBaseAdjustmentOffset) {
1774 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1775 VBPtrOffset);
1776 }
1777
1778 if (NonVirtualBaseAdjustment) {
1779 // Apply the adjustment and cast back to the original struct type.
1780 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1781 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1782 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1783 }
1784
1785 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1786}
1787
Charles Davis53c59df2010-08-16 03:33:14 +00001788CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001789 return new MicrosoftCXXABI(CGM);
1790}
1791