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