blob: 3433c8ca30ce6c3f84ac9c3a63c9d8d541f7e451 [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"
Reid Kleckner7810af02013-06-19 15:20:38 +000018#include "CGVTables.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "CodeGenModule.h"
Charles Davis74ce8592010-06-09 23:25:41 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000022#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000023#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000024
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29
Reid Klecknerb40a27d2014-01-03 00:14:35 +000030/// Holds all the vbtable globals for a given class.
31struct VBTableGlobals {
32 const VBTableVector *VBTables;
33 SmallVector<llvm::GlobalVariable *, 2> Globals;
34};
35
Charles Davis53c59df2010-08-16 03:33:14 +000036class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000037public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000038 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000039
Stephen Lin9dc6eef2013-06-30 20:40:16 +000040 bool HasThisReturn(GlobalDecl GD) const;
41
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000042 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
43 // Structures that are not C++03 PODs are always indirect.
44 return !RD->isPOD();
45 }
46
47 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner314ef7b2014-02-01 00:04:45 +000048 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor()) {
49 llvm::Triple::ArchType Arch = CGM.getTarget().getTriple().getArch();
50 if (Arch == llvm::Triple::x86)
51 return RAA_DirectInMemory;
52 // On x64, pass non-trivial records indirectly.
53 // FIXME: Test other Windows architectures.
54 return RAA_Indirect;
55 }
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000056 return RAA_Default;
57 }
58
Joao Matos2ce88ef2012-07-17 17:10:11 +000059 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000060 // No known support for deleted functions in MSVC yet, so this choice is
61 // arbitrary.
62 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000063
Hans Wennborgfeedf852013-11-21 00:15:56 +000064 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
65
John McCall82fb8922012-09-25 10:10:39 +000066 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
67 llvm::Value *ptr,
68 QualType type);
69
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000070 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
71 llvm::Value *This,
72 const CXXRecordDecl *ClassDecl,
73 const CXXRecordDecl *BaseClassDecl);
74
John McCall5d865c322010-08-31 07:33:07 +000075 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
76 CXXCtorType Type,
77 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000078 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000079
Reid Kleckner7810af02013-06-19 15:20:38 +000080 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
81 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000082
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000083 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
84 const CXXRecordDecl *RD);
85
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000086 void EmitCXXConstructors(const CXXConstructorDecl *D);
87
Reid Klecknere7de47e2013-07-22 13:51:44 +000088 // Background on MSVC destructors
89 // ==============================
90 //
91 // Both Itanium and MSVC ABIs have destructor variants. The variant names
92 // roughly correspond in the following way:
93 // Itanium Microsoft
94 // Base -> no name, just ~Class
95 // Complete -> vbase destructor
96 // Deleting -> scalar deleting destructor
97 // vector deleting destructor
98 //
99 // The base and complete destructors are the same as in Itanium, although the
100 // complete destructor does not accept a VTT parameter when there are virtual
101 // bases. A separate mechanism involving vtordisps is used to ensure that
102 // virtual methods of destroyed subobjects are not called.
103 //
104 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
105 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
106 // pointer points to an array. The scalar deleting destructor assumes that
107 // bit 2 is zero, and therefore does not contain a loop.
108 //
109 // For virtual destructors, only one entry is reserved in the vftable, and it
110 // always points to the vector deleting destructor. The vector deleting
111 // destructor is the most general, so it can be used to destroy objects in
112 // place, delete single heap objects, or delete arrays.
113 //
114 // A TU defining a non-inline destructor is only guaranteed to emit a base
115 // destructor, and all of the other variants are emitted on an as-needed basis
116 // in COMDATs. Because a non-base destructor can be emitted in a TU that
117 // lacks a definition for the destructor, non-base destructors must always
118 // delegate to or alias the base destructor.
119
120 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000121 CXXDtorType Type,
122 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000123 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000124
Reid Klecknere7de47e2013-07-22 13:51:44 +0000125 /// Non-base dtors should be emitted as delegating thunks in this ABI.
126 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
127 CXXDtorType DT) const {
128 return DT != Dtor_Base;
129 }
130
131 void EmitCXXDestructors(const CXXDestructorDecl *D);
132
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000133 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
134 MD = MD->getCanonicalDecl();
135 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000136 MicrosoftVTableContext::MethodVFTableLocation ML =
137 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000138 // The vbases might be ordered differently in the final overrider object
139 // and the complete object, so the "this" argument may sometimes point to
140 // memory that has no particular type (e.g. past the complete object).
141 // In this case, we just use a generic pointer type.
142 // FIXME: might want to have a more precise type in the non-virtual
143 // multiple inheritance case.
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000144 if (ML.VBase || !ML.VFPtrOffset.isZero())
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000145 return 0;
146 }
147 return MD->getParent();
148 }
149
150 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
151 GlobalDecl GD,
152 llvm::Value *This);
153
Reid Kleckner89077a12013-12-17 19:46:40 +0000154 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
155 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000156
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000157 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
158 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
159
John McCall0f999f32012-09-25 08:00:39 +0000160 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000161
Reid Kleckner89077a12013-12-17 19:46:40 +0000162 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
163 const CXXConstructorDecl *D,
164 CXXCtorType Type, bool ForVirtualBase,
165 bool Delegating, CallArgList &Args);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000166
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
168 CXXDtorType Type, bool ForVirtualBase,
169 bool Delegating, llvm::Value *This);
170
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000171 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
172
173 llvm::Value *getVTableAddressPointInStructor(
174 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
175 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
176 bool &NeedsVirtualOffset);
177
178 llvm::Constant *
179 getVTableAddressPointForConstExpr(BaseSubobject Base,
180 const CXXRecordDecl *VTableClass);
181
182 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
183 CharUnits VPtrOffset);
184
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000185 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
186 llvm::Value *This, llvm::Type *Ty);
187
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000188 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
189 const CXXDestructorDecl *Dtor,
190 CXXDtorType DtorType, SourceLocation CallLoc,
191 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000192
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000193 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
194 CallArgList &CallArgs) {
195 assert(GD.getDtorType() == Dtor_Deleting &&
196 "Only deleting destructor thunks are available in this ABI");
197 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
198 CGM.getContext().IntTy);
199 }
200
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000201 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000202
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000203 llvm::GlobalVariable *
204 getAddrOfVBTable(const VBTableInfo &VBT, const CXXRecordDecl *RD,
205 llvm::GlobalVariable::LinkageTypes Linkage);
206
207 void emitVBTableDefinition(const VBTableInfo &VBT, const CXXRecordDecl *RD,
208 llvm::GlobalVariable *GV) const;
209
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000210 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
211 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
212 }
213
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000214 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
215 const ThisAdjustment &TA);
216
217 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
218 const ReturnAdjustment &RA);
219
John McCallc84ed6a2012-05-01 06:13:13 +0000220 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
221 llvm::GlobalVariable *DeclPtr,
222 bool PerformInit);
223
John McCall29036752011-01-27 02:46:02 +0000224 // ==== Notes on array cookies =========
225 //
226 // MSVC seems to only use cookies when the class has a destructor; a
227 // two-argument usual array deallocation function isn't sufficient.
228 //
229 // For example, this code prints "100" and "1":
230 // struct A {
231 // char x;
232 // void *operator new[](size_t sz) {
233 // printf("%u\n", sz);
234 // return malloc(sz);
235 // }
236 // void operator delete[](void *p, size_t sz) {
237 // printf("%u\n", sz);
238 // free(p);
239 // }
240 // };
241 // int main() {
242 // A *p = new A[100];
243 // delete[] p;
244 // }
245 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000246
247 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
248 bool requiresArrayCookie(const CXXNewExpr *expr);
249 CharUnits getArrayCookieSizeImpl(QualType type);
250 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
251 llvm::Value *NewPtr,
252 llvm::Value *NumElements,
253 const CXXNewExpr *expr,
254 QualType ElementType);
255 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
256 llvm::Value *allocPtr,
257 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000258
259private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000260 MicrosoftMangleContext &getMangleContext() {
261 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
262 }
263
Reid Kleckner2341ae32013-04-11 18:13:19 +0000264 llvm::Constant *getZeroInt() {
265 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000266 }
267
Reid Kleckner2341ae32013-04-11 18:13:19 +0000268 llvm::Constant *getAllOnesInt() {
269 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000270 }
271
Reid Kleckner452abac2013-05-09 21:01:17 +0000272 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
273 return C ? C : getZeroInt();
274 }
275
276 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
277 return C ? C : getZeroInt();
278 }
279
Reid Kleckner2341ae32013-04-11 18:13:19 +0000280 void
281 GetNullMemberPointerFields(const MemberPointerType *MPT,
282 llvm::SmallVectorImpl<llvm::Constant *> &fields);
283
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000284 /// \brief Shared code for virtual base adjustment. Returns the offset from
285 /// the vbptr to the virtual base. Optionally returns the address of the
286 /// vbptr itself.
287 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
288 llvm::Value *Base,
289 llvm::Value *VBPtrOffset,
290 llvm::Value *VBTableOffset,
291 llvm::Value **VBPtr = 0);
292
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000293 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
294 llvm::Value *Base,
295 int32_t VBPtrOffset,
296 int32_t VBTableOffset,
297 llvm::Value **VBPtr = 0) {
298 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
299 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
300 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
301 }
302
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000303 /// \brief Performs a full virtual base adjustment. Used to dereference
304 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000305 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
306 llvm::Value *Base,
307 llvm::Value *VirtualBaseAdjustmentOffset,
308 llvm::Value *VBPtrOffset /* optional */);
309
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000310 /// \brief Emits a full member pointer with the fields common to data and
311 /// function member pointers.
312 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
313 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000314 const CXXRecordDecl *RD,
315 CharUnits NonVirtualBaseAdjustment);
316
317 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
318 const CXXMethodDecl *MD,
319 CharUnits NonVirtualBaseAdjustment);
320
321 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
322 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000323
Reid Kleckner7810af02013-06-19 15:20:38 +0000324 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
325 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
326
327 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000328 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000329
Hans Wennborg88497d62013-11-15 17:24:45 +0000330 /// \brief Generate a thunk for calling a virtual member function MD.
331 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
332 StringRef ThunkName);
333
Reid Kleckner407e8b62013-03-22 19:02:54 +0000334public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000335 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
336
337 virtual bool isZeroInitializable(const MemberPointerType *MPT);
338
Reid Kleckner407e8b62013-03-22 19:02:54 +0000339 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
340
341 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
342 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000343 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
344 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000345
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000346 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
347 llvm::Value *L,
348 llvm::Value *R,
349 const MemberPointerType *MPT,
350 bool Inequality);
351
Reid Kleckner407e8b62013-03-22 19:02:54 +0000352 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
353 llvm::Value *MemPtr,
354 const MemberPointerType *MPT);
355
356 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
357 llvm::Value *Base,
358 llvm::Value *MemPtr,
359 const MemberPointerType *MPT);
360
Reid Kleckner452abac2013-05-09 21:01:17 +0000361 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
362 const CastExpr *E,
363 llvm::Value *Src);
364
365 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
366 llvm::Constant *Src);
367
Reid Kleckner2341ae32013-04-11 18:13:19 +0000368 virtual llvm::Value *
369 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
370 llvm::Value *&This,
371 llvm::Value *MemPtr,
372 const MemberPointerType *MPT);
373
Reid Kleckner7810af02013-06-19 15:20:38 +0000374private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000375 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
376 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
377 /// \brief All the vftables that have been referenced.
378 VFTablesMapTy VFTablesMap;
379
380 /// \brief This set holds the record decls we've deferred vtable emission for.
381 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
382
383
384 /// \brief All the vbtables which have been referenced.
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000385 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000386
387 /// Info on the global variable used to guard initialization of static locals.
388 /// The BitIndex field is only used for externally invisible declarations.
389 struct GuardInfo {
390 GuardInfo() : Guard(0), BitIndex(0) {}
391 llvm::GlobalVariable *Guard;
392 unsigned BitIndex;
393 };
394
395 /// Map from DeclContext to the current guard variable. We assume that the
396 /// AST is visited in source code order.
397 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000398};
399
400}
401
John McCall82fb8922012-09-25 10:10:39 +0000402llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
403 llvm::Value *ptr,
404 QualType type) {
405 // FIXME: implement
406 return ptr;
407}
408
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000409llvm::Value *
410MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
411 llvm::Value *This,
412 const CXXRecordDecl *ClassDecl,
413 const CXXRecordDecl *BaseClassDecl) {
Reid Kleckner5b1b5d52014-01-14 00:50:39 +0000414 int64_t VBPtrChars =
415 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000416 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000417 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000418 CharUnits VBTableChars =
419 IntSize *
420 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000421 llvm::Value *VBTableOffset =
422 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
423
424 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000425 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000426 VBPtrToNewBase =
427 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
428 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
429}
430
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000431bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
432 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000433}
434
Reid Kleckner89077a12013-12-17 19:46:40 +0000435void MicrosoftCXXABI::BuildConstructorSignature(
436 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
437 SmallVectorImpl<CanQualType> &ArgTys) {
438
439 // All parameters are already in place except is_most_derived, which goes
440 // after 'this' if it's variadic and last if it's not.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000441
442 const CXXRecordDecl *Class = Ctor->getParent();
Reid Kleckner89077a12013-12-17 19:46:40 +0000443 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000444 if (Class->getNumVBases()) {
Reid Kleckner89077a12013-12-17 19:46:40 +0000445 if (FPT->isVariadic())
446 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
447 else
448 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000449 }
450}
451
Reid Kleckner7810af02013-06-19 15:20:38 +0000452llvm::BasicBlock *
453MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
454 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000455 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
456 assert(IsMostDerivedClass &&
457 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000458 llvm::Value *IsCompleteObject =
459 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000460
461 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
462 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
463 CGF.Builder.CreateCondBr(IsCompleteObject,
464 CallVbaseCtorsBB, SkipVbaseCtorsBB);
465
466 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000467
468 // Fill in the vbtable pointers here.
469 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000470
471 // CGF will put the base ctor calls in this basic block for us later.
472
473 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000474}
475
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000476void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
477 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
478 // In most cases, an override for a vbase virtual method can adjust
479 // the "this" parameter by applying a constant offset.
480 // However, this is not enough while a constructor or a destructor of some
481 // class X is being executed if all the following conditions are met:
482 // - X has virtual bases, (1)
483 // - X overrides a virtual method M of a vbase Y, (2)
484 // - X itself is a vbase of the most derived class.
485 //
486 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
487 // which holds the extra amount of "this" adjustment we must do when we use
488 // the X vftables (i.e. during X ctor or dtor).
489 // Outside the ctors and dtors, the values of vtorDisps are zero.
490
491 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
492 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
493 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
494 CGBuilderTy &Builder = CGF.Builder;
495
496 unsigned AS =
497 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
498 llvm::Value *Int8This = 0; // Initialize lazily.
499
500 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
501 I != E; ++I) {
502 if (!I->second.hasVtorDisp())
503 continue;
504
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000505 llvm::Value *VBaseOffset =
506 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000507 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
508 // just to Trunc back immediately.
509 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
510 uint64_t ConstantVBaseOffset =
511 Layout.getVBaseClassOffset(I->first).getQuantity();
512
513 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
514 llvm::Value *VtorDispValue = Builder.CreateSub(
515 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
516 "vtordisp.value");
517
518 if (!Int8This)
519 Int8This = Builder.CreateBitCast(getThisValue(CGF),
520 CGF.Int8Ty->getPointerTo(AS));
521 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
522 // vtorDisp is always the 32-bits before the vbase in the class layout.
523 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
524 VtorDispPtr = Builder.CreateBitCast(
525 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
526
527 Builder.CreateStore(VtorDispValue, VtorDispPtr);
528 }
529}
530
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000531void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
532 // There's only one constructor type in this ABI.
533 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
534}
535
Reid Kleckner7810af02013-06-19 15:20:38 +0000536void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
537 const CXXRecordDecl *RD) {
538 llvm::Value *ThisInt8Ptr =
539 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
Reid Kleckner5f080942014-01-03 23:42:00 +0000540 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000541
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000542 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
543 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +0000544 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000545 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner7810af02013-06-19 15:20:38 +0000546 const ASTRecordLayout &SubobjectLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +0000547 CGM.getContext().getASTRecordLayout(VBT->BaseWithVBPtr);
548 CharUnits Offs = VBT->NonVirtualOffset;
549 Offs += SubobjectLayout.getVBPtrOffset();
550 if (VBT->getVBaseWithVBPtr())
551 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVBPtr());
Reid Kleckner7810af02013-06-19 15:20:38 +0000552 llvm::Value *VBPtr =
Reid Kleckner5f080942014-01-03 23:42:00 +0000553 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000554 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
Reid Kleckner5f080942014-01-03 23:42:00 +0000555 "vbptr." + VBT->ReusingBase->getName());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000556 CGF.Builder.CreateStore(GV, VBPtr);
Reid Kleckner7810af02013-06-19 15:20:38 +0000557 }
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);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000645 llvm::Value *VBaseOffset =
646 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000647 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
Reid Kleckner89077a12013-12-17 19:46:40 +0000675void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
676 QualType &ResTy,
677 FunctionArgList &Params) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000678 ASTContext &Context = getContext();
679 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000680 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000681 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
682 ImplicitParamDecl *IsMostDerived
683 = ImplicitParamDecl::Create(Context, 0,
684 CGF.CurGD.getDecl()->getLocation(),
685 &Context.Idents.get("is_most_derived"),
686 Context.IntTy);
Reid Kleckner89077a12013-12-17 19:46:40 +0000687 // The 'most_derived' parameter goes second if the ctor is variadic and last
688 // if it's not. Dtors can't be variadic.
689 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
690 if (FPT->isVariadic())
691 Params.insert(Params.begin() + 1, IsMostDerived);
692 else
693 Params.push_back(IsMostDerived);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000694 getStructorImplicitParamDecl(CGF) = IsMostDerived;
695 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000696 ImplicitParamDecl *ShouldDelete
697 = ImplicitParamDecl::Create(Context, 0,
698 CGF.CurGD.getDecl()->getLocation(),
699 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000700 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000701 Params.push_back(ShouldDelete);
702 getStructorImplicitParamDecl(CGF) = ShouldDelete;
703 }
John McCall0f999f32012-09-25 08:00:39 +0000704}
705
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000706llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
707 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
708 GD = GD.getCanonicalDecl();
709 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000710
711 GlobalDecl LookupGD = GD;
712 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
713 // Complete destructors take a pointer to the complete object as a
714 // parameter, thus don't need this adjustment.
715 if (GD.getDtorType() == Dtor_Complete)
716 return This;
717
718 // There's no Dtor_Base in vftable but it shares the this adjustment with
719 // the deleting one, so look it up instead.
720 LookupGD = GlobalDecl(DD, Dtor_Deleting);
721 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000722
723 // In this ABI, every virtual function takes a pointer to one of the
724 // subobjects that first defines it as the 'this' parameter, rather than a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000725 // pointer to the final overrider subobject. Thus, we need to adjust it back
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000726 // to the final overrider subobject before use.
727 // See comments in the MicrosoftVFTableContext implementation for the details.
728
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000729 MicrosoftVTableContext::MethodVFTableLocation ML =
730 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000731 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000732 if (ML.VBase) {
733 const ASTRecordLayout &DerivedLayout =
734 CGF.getContext().getASTRecordLayout(MD->getParent());
735 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
736 }
737
738 if (Adjustment.isZero())
739 return This;
740
741 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
742 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
743 *thisTy = This->getType();
744
745 This = CGF.Builder.CreateBitCast(This, charPtrTy);
746 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000747 This =
748 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000749 return CGF.Builder.CreateBitCast(This, thisTy);
750}
751
John McCall0f999f32012-09-25 08:00:39 +0000752void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
753 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000754
755 /// If this is a function that the ABI specifies returns 'this', initialize
756 /// the return slot to 'this' at the start of the function.
757 ///
758 /// Unlike the setting of return types, this is done within the ABI
759 /// implementation instead of by clients of CGCXXABI because:
760 /// 1) getThisValue is currently protected
761 /// 2) in theory, an ABI could implement 'this' returns some other way;
762 /// HasThisReturn only specifies a contract, not the implementation
763 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000764 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000765
766 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
767 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
768 assert(getStructorImplicitParamDecl(CGF) &&
769 "no implicit parameter for a constructor with virtual bases?");
770 getStructorImplicitParamValue(CGF)
771 = CGF.Builder.CreateLoad(
772 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
773 "is_most_derived");
774 }
775
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000776 if (IsDeletingDtor(CGF.CurGD)) {
777 assert(getStructorImplicitParamDecl(CGF) &&
778 "no implicit parameter for a deleting destructor?");
779 getStructorImplicitParamValue(CGF)
780 = CGF.Builder.CreateLoad(
781 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
782 "should_call_delete");
783 }
John McCall0f999f32012-09-25 08:00:39 +0000784}
785
Reid Kleckner89077a12013-12-17 19:46:40 +0000786unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
787 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
788 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000789 assert(Type == Ctor_Complete || Type == Ctor_Base);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000790
Reid Kleckner89077a12013-12-17 19:46:40 +0000791 // Check if we need a 'most_derived' parameter.
792 if (!D->getParent()->getNumVBases())
793 return 0;
794
795 // Add the 'most_derived' argument second if we are variadic or last if not.
796 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
797 llvm::Value *MostDerivedArg =
798 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
799 RValue RV = RValue::get(MostDerivedArg);
800 if (MostDerivedArg) {
801 if (FPT->isVariadic())
802 Args.insert(Args.begin() + 1,
803 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
804 else
805 Args.add(RV, getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000806 }
807
Reid Kleckner89077a12013-12-17 19:46:40 +0000808 return 1; // Added one arg.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000809}
810
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000811void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
812 const CXXDestructorDecl *DD,
813 CXXDtorType Type, bool ForVirtualBase,
814 bool Delegating, llvm::Value *This) {
815 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
816
817 if (DD->isVirtual())
818 This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
819
820 // FIXME: Provide a source location here.
821 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
822 /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
823}
824
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000825void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
826 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000827 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
828 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000829 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
830
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000831 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000832 E = VFPtrs.end(); I != E; ++I) {
833 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
834 if (VTable->hasInitializer())
835 continue;
836
837 const VTableLayout &VTLayout =
838 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
839 llvm::Constant *Init = CGVT.CreateVTableInitializer(
840 RD, VTLayout.vtable_component_begin(),
841 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
842 VTLayout.getNumVTableThunks());
843 VTable->setInitializer(Init);
844
845 VTable->setLinkage(Linkage);
846 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
847 }
848}
849
850llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
851 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
852 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
853 NeedsVirtualOffset = (NearestVBase != 0);
854
855 llvm::Value *VTableAddressPoint =
856 getAddrOfVTable(VTableClass, Base.getBaseOffset());
857 if (!VTableAddressPoint) {
858 assert(Base.getBase()->getNumVBases() &&
859 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
860 }
861 return VTableAddressPoint;
862}
863
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000864static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
865 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
866 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000867 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000868 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000869}
870
871llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
872 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
873 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
874 assert(VTable && "Couldn't find a vftable for the given base?");
875 return VTable;
876}
877
878llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
879 CharUnits VPtrOffset) {
880 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
881 // shouldn't be used in the given record type. We want to cache this result in
882 // VFTablesMap, thus a simple zero check is not sufficient.
883 VFTableIdTy ID(RD, VPtrOffset);
884 VFTablesMapTy::iterator I;
885 bool Inserted;
886 llvm::tie(I, Inserted) = VFTablesMap.insert(
887 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
888 if (!Inserted)
889 return I->second;
890
891 llvm::GlobalVariable *&VTable = I->second;
892
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000893 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
894 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
895 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000896
897 if (DeferredVFTables.insert(RD)) {
898 // We haven't processed this record type before.
899 // Queue up this v-table for possible deferred emission.
900 CGM.addDeferredVTable(RD);
901
902#ifndef NDEBUG
903 // Create all the vftables at once in order to make sure each vftable has
904 // a unique mangled name.
905 llvm::StringSet<> ObservedMangledNames;
906 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
907 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000908 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000909 if (!ObservedMangledNames.insert(Name.str()))
910 llvm_unreachable("Already saw this mangling before?");
911 }
912#endif
913 }
914
915 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
916 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
917 continue;
918
919 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
920 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000921 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000922 .getNumVTableComponents());
923
924 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000925 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000926 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
927 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
928 VTable->setUnnamedAddr(true);
929 break;
930 }
931
932 return VTable;
933}
934
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000935llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
936 GlobalDecl GD,
937 llvm::Value *This,
938 llvm::Type *Ty) {
939 GD = GD.getCanonicalDecl();
940 CGBuilderTy &Builder = CGF.Builder;
941
942 Ty = Ty->getPointerTo()->getPointerTo();
943 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
944 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
945
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000946 MicrosoftVTableContext::MethodVFTableLocation ML =
947 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000948 llvm::Value *VFuncPtr =
949 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
950 return Builder.CreateLoad(VFuncPtr);
951}
952
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000953void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
954 const CXXDestructorDecl *Dtor,
955 CXXDtorType DtorType,
956 SourceLocation CallLoc,
957 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000958 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
959
960 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000961 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000962 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000963 const CGFunctionInfo *FInfo =
964 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000965 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000966 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000967
968 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000969 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000970 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000971 DtorType == Dtor_Deleting);
972
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000973 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000974 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000975 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000976}
977
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000978const VBTableGlobals &
979MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +0000980 // At this layer, we can key the cache off of a single class, which is much
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000981 // easier than caching each vbtable individually.
982 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
983 bool Added;
984 llvm::tie(Entry, Added) = VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
985 VBTableGlobals &VBGlobals = Entry->second;
986 if (!Added)
987 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +0000988
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000989 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
990 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000991
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000992 // Cache the globals for all vbtables so we don't have to recompute the
993 // mangled names.
994 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
995 for (VBTableVector::const_iterator I = VBGlobals.VBTables->begin(),
996 E = VBGlobals.VBTables->end();
997 I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +0000998 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000999 }
1000
1001 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +00001002}
1003
Hans Wennborg88497d62013-11-15 17:24:45 +00001004llvm::Function *
1005MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1006 StringRef ThunkName) {
1007 // If the thunk has been generated previously, just return it.
1008 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1009 return cast<llvm::Function>(GV);
1010
1011 // Create the llvm::Function.
1012 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1013 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1014 llvm::Function *ThunkFn =
1015 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1016 ThunkName.str(), &CGM.getModule());
1017 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1018
Hans Wennborg88497d62013-11-15 17:24:45 +00001019 ThunkFn->setLinkage(MD->isExternallyVisible()
1020 ? llvm::GlobalValue::LinkOnceODRLinkage
1021 : llvm::GlobalValue::InternalLinkage);
1022
1023 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1024 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1025
1026 // Start codegen.
1027 CodeGenFunction CGF(CGM);
1028 CGF.StartThunk(ThunkFn, MD, FnInfo);
1029
1030 // Get to the Callee.
1031 llvm::Value *This = CGF.LoadCXXThis();
1032 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1033
1034 // Make the call and return the result.
1035 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1036
1037 return ThunkFn;
1038}
1039
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001040void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001041 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1042 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +00001043 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001044 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner5f080942014-01-03 23:42:00 +00001045 emitVBTableDefinition(*VBT, RD, GV);
Reid Kleckner7810af02013-06-19 15:20:38 +00001046 }
1047}
1048
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001049llvm::GlobalVariable *
1050MicrosoftCXXABI::getAddrOfVBTable(const VBTableInfo &VBT,
1051 const CXXRecordDecl *RD,
1052 llvm::GlobalVariable::LinkageTypes Linkage) {
1053 SmallString<256> OutName;
1054 llvm::raw_svector_ostream Out(OutName);
1055 MicrosoftMangleContext &Mangler =
1056 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext());
1057 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out);
1058 Out.flush();
1059 StringRef Name = OutName.str();
1060
1061 llvm::ArrayType *VBTableType =
1062 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1063
1064 assert(!CGM.getModule().getNamedGlobal(Name) &&
1065 "vbtable with this name already exists: mangling bug?");
1066 llvm::GlobalVariable *GV =
1067 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1068 GV->setUnnamedAddr(true);
1069 return GV;
1070}
1071
1072void MicrosoftCXXABI::emitVBTableDefinition(const VBTableInfo &VBT,
1073 const CXXRecordDecl *RD,
1074 llvm::GlobalVariable *GV) const {
1075 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1076
1077 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1078 "should only emit vbtables for classes with vbtables");
1079
1080 const ASTRecordLayout &BaseLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +00001081 CGM.getContext().getASTRecordLayout(VBT.BaseWithVBPtr);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001082 const ASTRecordLayout &DerivedLayout =
1083 CGM.getContext().getASTRecordLayout(RD);
1084
1085 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0);
1086
1087 // The offset from ReusingBase's vbptr to itself always leads.
1088 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1089 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1090
1091 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1092 for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(),
1093 E = ReusingBase->vbases_end();
1094 I != E; ++I) {
1095 const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl();
1096 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1097 assert(!Offset.isNegative());
Reid Kleckner5f080942014-01-03 23:42:00 +00001098
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001099 // Make it relative to the subobject vbptr.
Reid Kleckner5f080942014-01-03 23:42:00 +00001100 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1101 if (VBT.getVBaseWithVBPtr())
1102 CompleteVBPtrOffset +=
1103 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVBPtr());
1104 Offset -= CompleteVBPtrOffset;
1105
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001106 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1107 assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?");
1108 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1109 }
1110
1111 assert(Offsets.size() ==
1112 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1113 ->getElementType())->getNumElements());
1114 llvm::ArrayType *VBTableType =
1115 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1116 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1117 GV->setInitializer(Init);
1118
1119 // Set the right visibility.
1120 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForVTable);
1121}
1122
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001123llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1124 llvm::Value *This,
1125 const ThisAdjustment &TA) {
1126 if (TA.isEmpty())
1127 return This;
1128
1129 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1130
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001131 if (!TA.Virtual.isEmpty()) {
1132 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1133 // Adjust the this argument based on the vtordisp value.
1134 llvm::Value *VtorDispPtr =
1135 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1136 VtorDispPtr =
1137 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1138 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1139 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1140
1141 if (TA.Virtual.Microsoft.VBPtrOffset) {
1142 // If the final overrider is defined in a virtual base other than the one
1143 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1144 // the vbtable of the derived class.
1145 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1146 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1147 llvm::Value *VBPtr;
1148 llvm::Value *VBaseOffset =
1149 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1150 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1151 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1152 }
1153 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001154
1155 if (TA.NonVirtual) {
1156 // Non-virtual adjustment might result in a pointer outside the allocated
1157 // object, e.g. if the final overrider class is laid out after the virtual
1158 // base that declares a method in the most derived class.
1159 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1160 }
1161
1162 // Don't need to bitcast back, the call CodeGen will handle this.
1163 return V;
1164}
1165
1166llvm::Value *
1167MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1168 const ReturnAdjustment &RA) {
1169 if (RA.isEmpty())
1170 return Ret;
1171
1172 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1173
1174 if (RA.Virtual.Microsoft.VBIndex) {
1175 assert(RA.Virtual.Microsoft.VBIndex > 0);
1176 int32_t IntSize =
1177 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1178 llvm::Value *VBPtr;
1179 llvm::Value *VBaseOffset =
1180 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1181 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1182 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1183 }
1184
1185 if (RA.NonVirtual)
1186 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1187
1188 // Cast back to the original type.
1189 return CGF.Builder.CreateBitCast(V, Ret->getType());
1190}
1191
John McCallb91cd662012-05-01 05:23:51 +00001192bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1193 QualType elementType) {
1194 // Microsoft seems to completely ignore the possibility of a
1195 // two-argument usual deallocation function.
1196 return elementType.isDestructedType();
1197}
1198
1199bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1200 // Microsoft seems to completely ignore the possibility of a
1201 // two-argument usual deallocation function.
1202 return expr->getAllocatedType().isDestructedType();
1203}
1204
1205CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1206 // The array cookie is always a size_t; we then pad that out to the
1207 // alignment of the element type.
1208 ASTContext &Ctx = getContext();
1209 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1210 Ctx.getTypeAlignInChars(type));
1211}
1212
1213llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1214 llvm::Value *allocPtr,
1215 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001216 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001217 llvm::Value *numElementsPtr =
1218 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1219 return CGF.Builder.CreateLoad(numElementsPtr);
1220}
1221
1222llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1223 llvm::Value *newPtr,
1224 llvm::Value *numElements,
1225 const CXXNewExpr *expr,
1226 QualType elementType) {
1227 assert(requiresArrayCookie(expr));
1228
1229 // The size of the cookie.
1230 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1231
1232 // Compute an offset to the cookie.
1233 llvm::Value *cookiePtr = newPtr;
1234
1235 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001236 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001237 llvm::Value *numElementsPtr
1238 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1239 CGF.Builder.CreateStore(numElements, numElementsPtr);
1240
1241 // Finally, compute a pointer to the actual data buffer by skipping
1242 // over the cookie completely.
1243 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1244 cookieSize.getQuantity());
1245}
1246
John McCallc84ed6a2012-05-01 06:13:13 +00001247void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001248 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001249 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001250 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1251 // threadsafe. Since the user may be linking in inline functions compiled by
1252 // cl.exe, there's no reason to provide a false sense of security by using
1253 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001254
Richard Smithdbf74ba2013-04-14 23:01:42 +00001255 if (D.getTLSKind())
1256 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1257
Reid Klecknerd8110b62013-09-10 20:14:30 +00001258 CGBuilderTy &Builder = CGF.Builder;
1259 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1260 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1261
1262 // Get the guard variable for this function if we have one already.
1263 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1264
1265 unsigned BitIndex;
1266 if (D.isExternallyVisible()) {
1267 // Externally visible variables have to be numbered in Sema to properly
1268 // handle unreachable VarDecls.
1269 BitIndex = getContext().getManglingNumber(&D);
1270 assert(BitIndex > 0);
1271 BitIndex--;
1272 } else {
1273 // Non-externally visible variables are numbered here in CodeGen.
1274 BitIndex = GI.BitIndex++;
1275 }
1276
1277 if (BitIndex >= 32) {
1278 if (D.isExternallyVisible())
1279 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1280 BitIndex %= 32;
1281 GI.Guard = 0;
1282 }
1283
1284 // Lazily create the i32 bitfield for this function.
1285 if (!GI.Guard) {
1286 // Mangle the name for the guard.
1287 SmallString<256> GuardName;
1288 {
1289 llvm::raw_svector_ostream Out(GuardName);
1290 getMangleContext().mangleStaticGuardVariable(&D, Out);
1291 Out.flush();
1292 }
1293
1294 // Create the guard variable with a zero-initializer. Just absorb linkage
1295 // and visibility from the guarded variable.
1296 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1297 GV->getLinkage(), Zero, GuardName.str());
1298 GI.Guard->setVisibility(GV->getVisibility());
1299 } else {
1300 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1301 "static local from the same function had different linkage");
1302 }
1303
1304 // Pseudo code for the test:
1305 // if (!(GuardVar & MyGuardBit)) {
1306 // GuardVar |= MyGuardBit;
1307 // ... initialize the object ...;
1308 // }
1309
1310 // Test our bit from the guard variable.
1311 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1312 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1313 llvm::Value *IsInitialized =
1314 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1315 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1316 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1317 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1318
1319 // Set our bit in the guard variable and emit the initializer and add a global
1320 // destructor if appropriate.
1321 CGF.EmitBlock(InitBlock);
1322 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1323 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1324 Builder.CreateBr(EndBlock);
1325
1326 // Continue.
1327 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001328}
1329
Reid Kleckner2341ae32013-04-11 18:13:19 +00001330// Member pointer helpers.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001331static bool hasVBPtrOffsetField(MSInheritanceAttr::Spelling Inheritance) {
1332 return Inheritance == MSInheritanceAttr::Keyword_unspecified_inheritance;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001333}
1334
Reid Kleckner452abac2013-05-09 21:01:17 +00001335static bool hasOnlyOneField(bool IsMemberFunction,
David Majnemer1cdd96d2014-01-17 09:01:00 +00001336 MSInheritanceAttr::Spelling Inheritance) {
1337 if (IsMemberFunction)
1338 return Inheritance <= MSInheritanceAttr::Keyword_single_inheritance;
1339 return Inheritance <= MSInheritanceAttr::Keyword_multiple_inheritance;
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001340}
1341
Reid Kleckner2341ae32013-04-11 18:13:19 +00001342// Only member pointers to functions need a this adjustment, since it can be
1343// combined with the field offset for data pointers.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001344static bool
1345hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
1346 MSInheritanceAttr::Spelling Inheritance) {
1347 return IsMemberFunction &&
1348 Inheritance >= MSInheritanceAttr::Keyword_multiple_inheritance;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001349}
1350
David Majnemer1cdd96d2014-01-17 09:01:00 +00001351static bool
1352hasVirtualBaseAdjustmentField(MSInheritanceAttr::Spelling Inheritance) {
1353 return Inheritance >= MSInheritanceAttr::Keyword_virtual_inheritance;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001354}
1355
1356// Use zero for the field offset of a null data member pointer if we can
1357// guarantee that zero is not a valid field offset, or if the member pointer has
1358// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1359// use zero for null. If there are multiple fields, we can use zero even if it
1360// is a valid field offset because null-ness testing will check the other
1361// fields.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001362static bool nullFieldOffsetIsZero(const CXXRecordDecl *RD) {
1363 return RD->getMSInheritanceModel() >=
1364 MSInheritanceAttr::Keyword_virtual_inheritance ||
1365 (RD->hasDefinition() && RD->isPolymorphic());
Reid Kleckner2341ae32013-04-11 18:13:19 +00001366}
1367
1368bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1369 // Null-ness for function memptrs only depends on the first field, which is
1370 // the function pointer. The rest don't matter, so we can zero initialize.
1371 if (MPT->isMemberFunctionPointer())
1372 return true;
1373
1374 // The virtual base adjustment field is always -1 for null, so if we have one
1375 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1376 // valid field offset.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001377 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1378 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001379 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
David Majnemer1cdd96d2014-01-17 09:01:00 +00001380 nullFieldOffsetIsZero(RD));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001381}
1382
1383llvm::Type *
1384MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001385 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1386 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001387 llvm::SmallVector<llvm::Type *, 4> fields;
1388 if (MPT->isMemberFunctionPointer())
1389 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1390 else
1391 fields.push_back(CGM.IntTy); // FieldOffset
1392
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001393 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1394 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001395 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001396 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001397 fields.push_back(CGM.IntTy);
1398 if (hasVirtualBaseAdjustmentField(Inheritance))
1399 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1400
1401 if (fields.size() == 1)
1402 return fields[0];
1403 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1404}
1405
1406void MicrosoftCXXABI::
1407GetNullMemberPointerFields(const MemberPointerType *MPT,
1408 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1409 assert(fields.empty());
David Majnemer1cdd96d2014-01-17 09:01:00 +00001410 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1411 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001412 if (MPT->isMemberFunctionPointer()) {
1413 // FunctionPointerOrVirtualThunk
1414 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1415 } else {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001416 if (nullFieldOffsetIsZero(RD))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001417 fields.push_back(getZeroInt()); // FieldOffset
1418 else
1419 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001420 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001421
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001422 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1423 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001424 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001425 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001426 fields.push_back(getZeroInt());
1427 if (hasVirtualBaseAdjustmentField(Inheritance))
1428 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001429}
1430
1431llvm::Constant *
1432MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001433 llvm::SmallVector<llvm::Constant *, 4> fields;
1434 GetNullMemberPointerFields(MPT, fields);
1435 if (fields.size() == 1)
1436 return fields[0];
1437 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1438 assert(Res->getType() == ConvertMemberPointerType(MPT));
1439 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001440}
1441
1442llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001443MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1444 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001445 const CXXRecordDecl *RD,
1446 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001447{
David Majnemer1cdd96d2014-01-17 09:01:00 +00001448 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001449
1450 // Single inheritance class member pointer are represented as scalars instead
1451 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001452 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001453 return FirstField;
1454
Reid Kleckner2341ae32013-04-11 18:13:19 +00001455 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001456 fields.push_back(FirstField);
1457
1458 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001459 fields.push_back(llvm::ConstantInt::get(
1460 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001461
Reid Kleckner2341ae32013-04-11 18:13:19 +00001462 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001463 CharUnits Offs = CharUnits::Zero();
1464 if (RD->getNumVBases())
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001465 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckneraec44092013-10-15 01:18:02 +00001466 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001467 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001468
1469 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001470 if (hasVirtualBaseAdjustmentField(Inheritance))
1471 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001472
Reid Kleckner2341ae32013-04-11 18:13:19 +00001473 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001474}
1475
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001476llvm::Constant *
1477MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1478 CharUnits offset) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001479 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001480 llvm::Constant *FirstField =
1481 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001482 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1483 CharUnits::Zero());
1484}
1485
1486llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1487 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1488}
1489
1490llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1491 QualType MPType) {
1492 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1493 const ValueDecl *MPD = MP.getMemberPointerDecl();
1494 if (!MPD)
1495 return EmitNullMemberPointer(MPT);
1496
1497 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1498
1499 // FIXME PR15713: Support virtual inheritance paths.
1500
1501 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
David Majnemer1cdd96d2014-01-17 09:01:00 +00001502 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1503 ThisAdjustment);
Reid Kleckner452abac2013-05-09 21:01:17 +00001504
1505 CharUnits FieldOffset =
1506 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1507 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001508}
1509
1510llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001511MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1512 const CXXMethodDecl *MD,
1513 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001514 assert(MD->isInstance() && "Member function must not be static!");
1515 MD = MD->getCanonicalDecl();
David Majnemer1cdd96d2014-01-17 09:01:00 +00001516 RD = RD->getMostRecentDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001517 CodeGenTypes &Types = CGM.getTypes();
1518
1519 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001520 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001521 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1522 llvm::Type *Ty;
1523 // Check whether the function has a computable LLVM signature.
1524 if (Types.isFuncTypeConvertible(FPT)) {
1525 // The function has a computable LLVM signature; use the correct type.
1526 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1527 } else {
1528 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1529 // function type is incomplete.
1530 Ty = CGM.PtrDiffTy;
1531 }
1532 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1533 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001534 } else {
1535 MicrosoftVTableContext::MethodVFTableLocation ML =
1536 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1537 if (MD->isVariadic()) {
1538 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1539 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1540 } else if (!CGM.getTypes().isFuncTypeConvertible(
1541 MD->getType()->castAs<FunctionType>())) {
1542 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1543 "incomplete return or parameter type");
1544 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1545 } else if (ML.VBase) {
1546 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1547 "member function in virtual base class");
1548 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1549 } else {
1550 SmallString<256> ThunkName;
David Majnemer2a816452013-12-09 10:44:32 +00001551 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1552 getContext().getTargetInfo().getPointerWidth(0));
1553 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
Hans Wennborg88497d62013-11-15 17:24:45 +00001554 llvm::raw_svector_ostream Out(ThunkName);
1555 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1556 Out.flush();
1557
1558 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1559 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1560 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001561 }
1562
1563 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001564 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1565 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001566}
1567
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001568/// Member pointers are the same if they're either bitwise identical *or* both
1569/// null. Null-ness for function members is determined by the first field,
1570/// while for data member pointers we must compare all fields.
1571llvm::Value *
1572MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1573 llvm::Value *L,
1574 llvm::Value *R,
1575 const MemberPointerType *MPT,
1576 bool Inequality) {
1577 CGBuilderTy &Builder = CGF.Builder;
1578
1579 // Handle != comparisons by switching the sense of all boolean operations.
1580 llvm::ICmpInst::Predicate Eq;
1581 llvm::Instruction::BinaryOps And, Or;
1582 if (Inequality) {
1583 Eq = llvm::ICmpInst::ICMP_NE;
1584 And = llvm::Instruction::Or;
1585 Or = llvm::Instruction::And;
1586 } else {
1587 Eq = llvm::ICmpInst::ICMP_EQ;
1588 And = llvm::Instruction::And;
1589 Or = llvm::Instruction::Or;
1590 }
1591
1592 // If this is a single field member pointer (single inheritance), this is a
1593 // single icmp.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001594 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1595 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001596 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001597 return Builder.CreateICmp(Eq, L, R);
1598
1599 // Compare the first field.
1600 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1601 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1602 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1603
1604 // Compare everything other than the first field.
1605 llvm::Value *Res = 0;
1606 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1607 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1608 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1609 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1610 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1611 if (Res)
1612 Res = Builder.CreateBinOp(And, Res, Cmp);
1613 else
1614 Res = Cmp;
1615 }
1616
1617 // Check if the first field is 0 if this is a function pointer.
1618 if (MPT->isMemberFunctionPointer()) {
1619 // (l1 == r1 && ...) || l0 == 0
1620 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1621 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1622 Res = Builder.CreateBinOp(Or, Res, IsZero);
1623 }
1624
1625 // Combine the comparison of the first field, which must always be true for
1626 // this comparison to succeeed.
1627 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1628}
1629
Reid Kleckner407e8b62013-03-22 19:02:54 +00001630llvm::Value *
1631MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1632 llvm::Value *MemPtr,
1633 const MemberPointerType *MPT) {
1634 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001635 llvm::SmallVector<llvm::Constant *, 4> fields;
1636 // We only need one field for member functions.
1637 if (MPT->isMemberFunctionPointer())
1638 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1639 else
1640 GetNullMemberPointerFields(MPT, fields);
1641 assert(!fields.empty());
1642 llvm::Value *FirstField = MemPtr;
1643 if (MemPtr->getType()->isStructTy())
1644 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1645 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001646
Reid Kleckner2341ae32013-04-11 18:13:19 +00001647 // For function member pointers, we only need to test the function pointer
1648 // field. The other fields if any can be garbage.
1649 if (MPT->isMemberFunctionPointer())
1650 return Res;
1651
1652 // Otherwise, emit a series of compares and combine the results.
1653 for (int I = 1, E = fields.size(); I < E; ++I) {
1654 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1655 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1656 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1657 }
1658 return Res;
1659}
1660
Reid Kleckner452abac2013-05-09 21:01:17 +00001661bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1662 llvm::Constant *Val) {
1663 // Function pointers are null if the pointer in the first field is null.
1664 if (MPT->isMemberFunctionPointer()) {
1665 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1666 Val->getAggregateElement(0U) : Val;
1667 return FirstField->isNullValue();
1668 }
1669
1670 // If it's not a function pointer and it's zero initializable, we can easily
1671 // check zero.
1672 if (isZeroInitializable(MPT) && Val->isNullValue())
1673 return true;
1674
1675 // Otherwise, break down all the fields for comparison. Hopefully these
1676 // little Constants are reused, while a big null struct might not be.
1677 llvm::SmallVector<llvm::Constant *, 4> Fields;
1678 GetNullMemberPointerFields(MPT, Fields);
1679 if (Fields.size() == 1) {
1680 assert(Val->getType()->isIntegerTy());
1681 return Val == Fields[0];
1682 }
1683
1684 unsigned I, E;
1685 for (I = 0, E = Fields.size(); I != E; ++I) {
1686 if (Val->getAggregateElement(I) != Fields[I])
1687 break;
1688 }
1689 return I == E;
1690}
1691
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001692llvm::Value *
1693MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1694 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001695 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001696 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001697 llvm::Value **VBPtrOut) {
1698 CGBuilderTy &Builder = CGF.Builder;
1699 // Load the vbtable pointer from the vbptr in the instance.
1700 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1701 llvm::Value *VBPtr =
1702 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1703 if (VBPtrOut) *VBPtrOut = VBPtr;
1704 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1705 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1706
1707 // Load an i32 offset from the vb-table.
1708 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1709 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1710 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1711}
1712
Reid Kleckner2341ae32013-04-11 18:13:19 +00001713// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1714// it.
1715llvm::Value *
1716MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1717 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001718 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001719 llvm::Value *VBPtrOffset) {
1720 CGBuilderTy &Builder = CGF.Builder;
1721 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1722 llvm::BasicBlock *OriginalBB = 0;
1723 llvm::BasicBlock *SkipAdjustBB = 0;
1724 llvm::BasicBlock *VBaseAdjustBB = 0;
1725
1726 // In the unspecified inheritance model, there might not be a vbtable at all,
1727 // in which case we need to skip the virtual base lookup. If there is a
1728 // vbtable, the first entry is a no-op entry that gives back the original
1729 // base, so look for a virtual base adjustment offset of zero.
1730 if (VBPtrOffset) {
1731 OriginalBB = Builder.GetInsertBlock();
1732 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1733 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1734 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001735 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001736 "memptr.is_vbase");
1737 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1738 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001739 }
1740
Reid Kleckner2341ae32013-04-11 18:13:19 +00001741 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1742 // know the vbptr offset.
1743 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001744 CharUnits offs = CharUnits::Zero();
Reid Kleckner5b1b5d52014-01-14 00:50:39 +00001745 if (RD->getNumVBases())
1746 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
Reid Kleckner2341ae32013-04-11 18:13:19 +00001747 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1748 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001749 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001750 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001751 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001752 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1753
1754 // Merge control flow with the case where we didn't have to adjust.
1755 if (VBaseAdjustBB) {
1756 Builder.CreateBr(SkipAdjustBB);
1757 CGF.EmitBlock(SkipAdjustBB);
1758 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1759 Phi->addIncoming(Base, OriginalBB);
1760 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1761 return Phi;
1762 }
1763 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001764}
1765
1766llvm::Value *
1767MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1768 llvm::Value *Base,
1769 llvm::Value *MemPtr,
1770 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001771 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001772 unsigned AS = Base->getType()->getPointerAddressSpace();
1773 llvm::Type *PType =
1774 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1775 CGBuilderTy &Builder = CGF.Builder;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001776 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1777 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001778
Reid Kleckner2341ae32013-04-11 18:13:19 +00001779 // Extract the fields we need, regardless of model. We'll apply them if we
1780 // have them.
1781 llvm::Value *FieldOffset = MemPtr;
1782 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1783 llvm::Value *VBPtrOffset = 0;
1784 if (MemPtr->getType()->isStructTy()) {
1785 // We need to extract values.
1786 unsigned I = 0;
1787 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1788 if (hasVBPtrOffsetField(Inheritance))
1789 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1790 if (hasVirtualBaseAdjustmentField(Inheritance))
1791 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001792 }
1793
Reid Kleckner2341ae32013-04-11 18:13:19 +00001794 if (VirtualBaseAdjustmentOffset) {
1795 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1796 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001797 }
Reid Klecknerae945122013-12-05 22:44:07 +00001798
1799 // Cast to char*.
1800 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1801
1802 // Apply the offset, which we assume is non-null.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001803 llvm::Value *Addr =
1804 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001805
1806 // Cast the address to the appropriate pointer type, adopting the address
1807 // space of the base pointer.
1808 return Builder.CreateBitCast(Addr, PType);
1809}
1810
David Majnemer1cdd96d2014-01-17 09:01:00 +00001811static MSInheritanceAttr::Spelling
Reid Kleckner452abac2013-05-09 21:01:17 +00001812getInheritanceFromMemptr(const MemberPointerType *MPT) {
David Majnemer1cdd96d2014-01-17 09:01:00 +00001813 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001814}
1815
1816llvm::Value *
1817MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1818 const CastExpr *E,
1819 llvm::Value *Src) {
1820 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1821 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1822 E->getCastKind() == CK_ReinterpretMemberPointer);
1823
1824 // Use constant emission if we can.
1825 if (isa<llvm::Constant>(Src))
1826 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1827
1828 // We may be adding or dropping fields from the member pointer, so we need
1829 // both types and the inheritance models of both records.
1830 const MemberPointerType *SrcTy =
1831 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1832 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
Reid Kleckner452abac2013-05-09 21:01:17 +00001833 bool IsFunc = SrcTy->isMemberFunctionPointer();
1834
1835 // If the classes use the same null representation, reinterpret_cast is a nop.
1836 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001837 if (IsReinterpret && IsFunc)
1838 return Src;
1839
1840 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
1841 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
1842 if (IsReinterpret &&
1843 nullFieldOffsetIsZero(SrcRD) == nullFieldOffsetIsZero(DstRD))
Reid Kleckner452abac2013-05-09 21:01:17 +00001844 return Src;
1845
1846 CGBuilderTy &Builder = CGF.Builder;
1847
1848 // Branch past the conversion if Src is null.
1849 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1850 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1851
1852 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1853 // pointer value of the destination type.
1854 if (IsReinterpret) {
1855 // For reinterpret casts, sema ensures that src and dst are both functions
1856 // or data and have the same size, which means the LLVM types should match.
1857 assert(Src->getType() == DstNull->getType());
1858 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1859 }
1860
1861 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1862 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1863 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1864 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1865 CGF.EmitBlock(ConvertBB);
1866
1867 // Decompose src.
1868 llvm::Value *FirstField = Src;
1869 llvm::Value *NonVirtualBaseAdjustment = 0;
1870 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1871 llvm::Value *VBPtrOffset = 0;
David Majnemer1cdd96d2014-01-17 09:01:00 +00001872 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001873 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1874 // We need to extract values.
1875 unsigned I = 0;
1876 FirstField = Builder.CreateExtractValue(Src, I++);
1877 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1878 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1879 if (hasVBPtrOffsetField(SrcInheritance))
1880 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1881 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1882 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1883 }
1884
1885 // For data pointers, we adjust the field offset directly. For functions, we
1886 // have a separate field.
1887 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1888 if (Adj) {
1889 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1890 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1891 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1892 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1893 NVAdjustField = getZeroInt();
1894 if (isDerivedToBase)
1895 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1896 else
1897 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1898 }
1899
1900 // FIXME PR15713: Support conversions through virtually derived classes.
1901
1902 // Recompose dst from the null struct and the adjusted fields from src.
David Majnemer1cdd96d2014-01-17 09:01:00 +00001903 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001904 llvm::Value *Dst;
1905 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1906 Dst = FirstField;
1907 } else {
1908 Dst = llvm::UndefValue::get(DstNull->getType());
1909 unsigned Idx = 0;
1910 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1911 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1912 Dst = Builder.CreateInsertValue(
1913 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1914 if (hasVBPtrOffsetField(DstInheritance))
1915 Dst = Builder.CreateInsertValue(
1916 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1917 if (hasVirtualBaseAdjustmentField(DstInheritance))
1918 Dst = Builder.CreateInsertValue(
1919 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1920 }
1921 Builder.CreateBr(ContinueBB);
1922
1923 // In the continuation, choose between DstNull and Dst.
1924 CGF.EmitBlock(ContinueBB);
1925 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1926 Phi->addIncoming(DstNull, OriginalBB);
1927 Phi->addIncoming(Dst, ConvertBB);
1928 return Phi;
1929}
1930
1931llvm::Constant *
1932MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1933 llvm::Constant *Src) {
1934 const MemberPointerType *SrcTy =
1935 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1936 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1937
1938 // If src is null, emit a new null for dst. We can't return src because dst
1939 // might have a new representation.
1940 if (MemberPointerConstantIsNull(SrcTy, Src))
1941 return EmitNullMemberPointer(DstTy);
1942
1943 // We don't need to do anything for reinterpret_casts of non-null member
1944 // pointers. We should only get here when the two type representations have
1945 // the same size.
1946 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1947 return Src;
1948
David Majnemer1cdd96d2014-01-17 09:01:00 +00001949 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
1950 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
Reid Kleckner452abac2013-05-09 21:01:17 +00001951
1952 // Decompose src.
1953 llvm::Constant *FirstField = Src;
1954 llvm::Constant *NonVirtualBaseAdjustment = 0;
1955 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1956 llvm::Constant *VBPtrOffset = 0;
1957 bool IsFunc = SrcTy->isMemberFunctionPointer();
1958 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1959 // We need to extract values.
1960 unsigned I = 0;
1961 FirstField = Src->getAggregateElement(I++);
1962 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1963 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1964 if (hasVBPtrOffsetField(SrcInheritance))
1965 VBPtrOffset = Src->getAggregateElement(I++);
1966 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1967 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1968 }
1969
1970 // For data pointers, we adjust the field offset directly. For functions, we
1971 // have a separate field.
1972 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1973 if (Adj) {
1974 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1975 llvm::Constant *&NVAdjustField =
1976 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1977 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1978 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1979 NVAdjustField = getZeroInt();
1980 if (IsDerivedToBase)
1981 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1982 else
1983 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1984 }
1985
1986 // FIXME PR15713: Support conversions through virtually derived classes.
1987
1988 // Recompose dst from the null struct and the adjusted fields from src.
1989 if (hasOnlyOneField(IsFunc, DstInheritance))
1990 return FirstField;
1991
1992 llvm::SmallVector<llvm::Constant *, 4> Fields;
1993 Fields.push_back(FirstField);
1994 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1995 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1996 if (hasVBPtrOffsetField(DstInheritance))
1997 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1998 if (hasVirtualBaseAdjustmentField(DstInheritance))
1999 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2000 return llvm::ConstantStruct::getAnon(Fields);
2001}
2002
Reid Kleckner2341ae32013-04-11 18:13:19 +00002003llvm::Value *
2004MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
2005 llvm::Value *&This,
2006 llvm::Value *MemPtr,
2007 const MemberPointerType *MPT) {
2008 assert(MPT->isMemberFunctionPointer());
2009 const FunctionProtoType *FPT =
2010 MPT->getPointeeType()->castAs<FunctionProtoType>();
David Majnemer1cdd96d2014-01-17 09:01:00 +00002011 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner2341ae32013-04-11 18:13:19 +00002012 llvm::FunctionType *FTy =
2013 CGM.getTypes().GetFunctionType(
2014 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2015 CGBuilderTy &Builder = CGF.Builder;
2016
David Majnemer1cdd96d2014-01-17 09:01:00 +00002017 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
Reid Kleckner2341ae32013-04-11 18:13:19 +00002018
2019 // Extract the fields we need, regardless of model. We'll apply them if we
2020 // have them.
2021 llvm::Value *FunctionPointer = MemPtr;
2022 llvm::Value *NonVirtualBaseAdjustment = NULL;
2023 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
2024 llvm::Value *VBPtrOffset = NULL;
2025 if (MemPtr->getType()->isStructTy()) {
2026 // We need to extract values.
2027 unsigned I = 0;
2028 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002029 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
2030 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00002031 if (hasVBPtrOffsetField(Inheritance))
2032 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002033 if (hasVirtualBaseAdjustmentField(Inheritance))
2034 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2035 }
2036
2037 if (VirtualBaseAdjustmentOffset) {
2038 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
2039 VBPtrOffset);
2040 }
2041
2042 if (NonVirtualBaseAdjustment) {
2043 // Apply the adjustment and cast back to the original struct type.
2044 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2045 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2046 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2047 }
2048
2049 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2050}
2051
Charles Davis53c59df2010-08-16 03:33:14 +00002052CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00002053 return new MicrosoftCXXABI(CGM);
2054}