blob: c1f9cb314a8850fef4ae6d2e370dfe9119e4b187 [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 Kleckner23f4c4b2013-06-21 12:45:15 +000048 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000049 return RAA_DirectInMemory;
50 return RAA_Default;
51 }
52
Joao Matos2ce88ef2012-07-17 17:10:11 +000053 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000054 // No known support for deleted functions in MSVC yet, so this choice is
55 // arbitrary.
56 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000057
Hans Wennborgfeedf852013-11-21 00:15:56 +000058 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
59
John McCall82fb8922012-09-25 10:10:39 +000060 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
61 llvm::Value *ptr,
62 QualType type);
63
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000064 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
65 llvm::Value *This,
66 const CXXRecordDecl *ClassDecl,
67 const CXXRecordDecl *BaseClassDecl);
68
John McCall5d865c322010-08-31 07:33:07 +000069 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
70 CXXCtorType Type,
71 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000072 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000073
Reid Kleckner7810af02013-06-19 15:20:38 +000074 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
75 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000076
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000077 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
78 const CXXRecordDecl *RD);
79
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000080 void EmitCXXConstructors(const CXXConstructorDecl *D);
81
Reid Klecknere7de47e2013-07-22 13:51:44 +000082 // Background on MSVC destructors
83 // ==============================
84 //
85 // Both Itanium and MSVC ABIs have destructor variants. The variant names
86 // roughly correspond in the following way:
87 // Itanium Microsoft
88 // Base -> no name, just ~Class
89 // Complete -> vbase destructor
90 // Deleting -> scalar deleting destructor
91 // vector deleting destructor
92 //
93 // The base and complete destructors are the same as in Itanium, although the
94 // complete destructor does not accept a VTT parameter when there are virtual
95 // bases. A separate mechanism involving vtordisps is used to ensure that
96 // virtual methods of destroyed subobjects are not called.
97 //
98 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
99 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
100 // pointer points to an array. The scalar deleting destructor assumes that
101 // bit 2 is zero, and therefore does not contain a loop.
102 //
103 // For virtual destructors, only one entry is reserved in the vftable, and it
104 // always points to the vector deleting destructor. The vector deleting
105 // destructor is the most general, so it can be used to destroy objects in
106 // place, delete single heap objects, or delete arrays.
107 //
108 // A TU defining a non-inline destructor is only guaranteed to emit a base
109 // destructor, and all of the other variants are emitted on an as-needed basis
110 // in COMDATs. Because a non-base destructor can be emitted in a TU that
111 // lacks a definition for the destructor, non-base destructors must always
112 // delegate to or alias the base destructor.
113
114 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000115 CXXDtorType Type,
116 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000117 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000118
Reid Klecknere7de47e2013-07-22 13:51:44 +0000119 /// Non-base dtors should be emitted as delegating thunks in this ABI.
120 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
121 CXXDtorType DT) const {
122 return DT != Dtor_Base;
123 }
124
125 void EmitCXXDestructors(const CXXDestructorDecl *D);
126
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000127 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
128 MD = MD->getCanonicalDecl();
129 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000130 MicrosoftVTableContext::MethodVFTableLocation ML =
131 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000132 // The vbases might be ordered differently in the final overrider object
133 // and the complete object, so the "this" argument may sometimes point to
134 // memory that has no particular type (e.g. past the complete object).
135 // In this case, we just use a generic pointer type.
136 // FIXME: might want to have a more precise type in the non-virtual
137 // multiple inheritance case.
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000138 if (ML.VBase || !ML.VFPtrOffset.isZero())
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000139 return 0;
140 }
141 return MD->getParent();
142 }
143
144 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
145 GlobalDecl GD,
146 llvm::Value *This);
147
Reid Kleckner89077a12013-12-17 19:46:40 +0000148 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
149 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000150
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000151 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
152 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
153
John McCall0f999f32012-09-25 08:00:39 +0000154 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000155
Reid Kleckner89077a12013-12-17 19:46:40 +0000156 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
157 const CXXConstructorDecl *D,
158 CXXCtorType Type, bool ForVirtualBase,
159 bool Delegating, CallArgList &Args);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000160
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000161 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
162 CXXDtorType Type, bool ForVirtualBase,
163 bool Delegating, llvm::Value *This);
164
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000165 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
166
167 llvm::Value *getVTableAddressPointInStructor(
168 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
169 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
170 bool &NeedsVirtualOffset);
171
172 llvm::Constant *
173 getVTableAddressPointForConstExpr(BaseSubobject Base,
174 const CXXRecordDecl *VTableClass);
175
176 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
177 CharUnits VPtrOffset);
178
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000179 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
180 llvm::Value *This, llvm::Type *Ty);
181
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000182 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
183 const CXXDestructorDecl *Dtor,
184 CXXDtorType DtorType, SourceLocation CallLoc,
185 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000186
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000187 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
188 CallArgList &CallArgs) {
189 assert(GD.getDtorType() == Dtor_Deleting &&
190 "Only deleting destructor thunks are available in this ABI");
191 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
192 CGM.getContext().IntTy);
193 }
194
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000196
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000197 llvm::GlobalVariable *
198 getAddrOfVBTable(const VBTableInfo &VBT, const CXXRecordDecl *RD,
199 llvm::GlobalVariable::LinkageTypes Linkage);
200
201 void emitVBTableDefinition(const VBTableInfo &VBT, const CXXRecordDecl *RD,
202 llvm::GlobalVariable *GV) const;
203
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000204 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
205 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
206 }
207
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000208 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
209 const ThisAdjustment &TA);
210
211 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
212 const ReturnAdjustment &RA);
213
John McCallc84ed6a2012-05-01 06:13:13 +0000214 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
215 llvm::GlobalVariable *DeclPtr,
216 bool PerformInit);
217
John McCall29036752011-01-27 02:46:02 +0000218 // ==== Notes on array cookies =========
219 //
220 // MSVC seems to only use cookies when the class has a destructor; a
221 // two-argument usual array deallocation function isn't sufficient.
222 //
223 // For example, this code prints "100" and "1":
224 // struct A {
225 // char x;
226 // void *operator new[](size_t sz) {
227 // printf("%u\n", sz);
228 // return malloc(sz);
229 // }
230 // void operator delete[](void *p, size_t sz) {
231 // printf("%u\n", sz);
232 // free(p);
233 // }
234 // };
235 // int main() {
236 // A *p = new A[100];
237 // delete[] p;
238 // }
239 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000240
241 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
242 bool requiresArrayCookie(const CXXNewExpr *expr);
243 CharUnits getArrayCookieSizeImpl(QualType type);
244 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
245 llvm::Value *NewPtr,
246 llvm::Value *NumElements,
247 const CXXNewExpr *expr,
248 QualType ElementType);
249 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
250 llvm::Value *allocPtr,
251 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000252
253private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000254 MicrosoftMangleContext &getMangleContext() {
255 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
256 }
257
Reid Kleckner2341ae32013-04-11 18:13:19 +0000258 llvm::Constant *getZeroInt() {
259 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000260 }
261
Reid Kleckner2341ae32013-04-11 18:13:19 +0000262 llvm::Constant *getAllOnesInt() {
263 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000264 }
265
Reid Kleckner452abac2013-05-09 21:01:17 +0000266 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
267 return C ? C : getZeroInt();
268 }
269
270 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
271 return C ? C : getZeroInt();
272 }
273
Reid Kleckner2341ae32013-04-11 18:13:19 +0000274 void
275 GetNullMemberPointerFields(const MemberPointerType *MPT,
276 llvm::SmallVectorImpl<llvm::Constant *> &fields);
277
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000278 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
279 /// it is reusing a vbptr from a non-virtual base. RD must have morally
280 /// virtual bases.
281 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
282
283 /// \brief Shared code for virtual base adjustment. Returns the offset from
284 /// the vbptr to the virtual base. Optionally returns the address of the
285 /// vbptr itself.
286 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
287 llvm::Value *Base,
288 llvm::Value *VBPtrOffset,
289 llvm::Value *VBTableOffset,
290 llvm::Value **VBPtr = 0);
291
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000292 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
293 llvm::Value *Base,
294 int32_t VBPtrOffset,
295 int32_t VBTableOffset,
296 llvm::Value **VBPtr = 0) {
297 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
298 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
299 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
300 }
301
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000302 /// \brief Performs a full virtual base adjustment. Used to dereference
303 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000304 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
305 llvm::Value *Base,
306 llvm::Value *VirtualBaseAdjustmentOffset,
307 llvm::Value *VBPtrOffset /* optional */);
308
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000309 /// \brief Emits a full member pointer with the fields common to data and
310 /// function member pointers.
311 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
312 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000313 const CXXRecordDecl *RD,
314 CharUnits NonVirtualBaseAdjustment);
315
316 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
317 const CXXMethodDecl *MD,
318 CharUnits NonVirtualBaseAdjustment);
319
320 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
321 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000322
Reid Kleckner7810af02013-06-19 15:20:38 +0000323 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
324 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
325
326 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000327 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000328
Hans Wennborg88497d62013-11-15 17:24:45 +0000329 /// \brief Generate a thunk for calling a virtual member function MD.
330 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
331 StringRef ThunkName);
332
Reid Kleckner407e8b62013-03-22 19:02:54 +0000333public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000334 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
335
336 virtual bool isZeroInitializable(const MemberPointerType *MPT);
337
Reid Kleckner407e8b62013-03-22 19:02:54 +0000338 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
339
340 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
341 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000342 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
343 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000344
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000345 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
346 llvm::Value *L,
347 llvm::Value *R,
348 const MemberPointerType *MPT,
349 bool Inequality);
350
Reid Kleckner407e8b62013-03-22 19:02:54 +0000351 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
352 llvm::Value *MemPtr,
353 const MemberPointerType *MPT);
354
355 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
356 llvm::Value *Base,
357 llvm::Value *MemPtr,
358 const MemberPointerType *MPT);
359
Reid Kleckner452abac2013-05-09 21:01:17 +0000360 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
361 const CastExpr *E,
362 llvm::Value *Src);
363
364 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
365 llvm::Constant *Src);
366
Reid Kleckner2341ae32013-04-11 18:13:19 +0000367 virtual llvm::Value *
368 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
369 llvm::Value *&This,
370 llvm::Value *MemPtr,
371 const MemberPointerType *MPT);
372
Reid Kleckner7810af02013-06-19 15:20:38 +0000373private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000374 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
375 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
376 /// \brief All the vftables that have been referenced.
377 VFTablesMapTy VFTablesMap;
378
379 /// \brief This set holds the record decls we've deferred vtable emission for.
380 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
381
382
383 /// \brief All the vbtables which have been referenced.
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000384 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000385
386 /// Info on the global variable used to guard initialization of static locals.
387 /// The BitIndex field is only used for externally invisible declarations.
388 struct GuardInfo {
389 GuardInfo() : Guard(0), BitIndex(0) {}
390 llvm::GlobalVariable *Guard;
391 unsigned BitIndex;
392 };
393
394 /// Map from DeclContext to the current guard variable. We assume that the
395 /// AST is visited in source code order.
396 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000397};
398
399}
400
John McCall82fb8922012-09-25 10:10:39 +0000401llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
402 llvm::Value *ptr,
403 QualType type) {
404 // FIXME: implement
405 return ptr;
406}
407
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000408/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
409/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
410static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
411 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
412 E = RD->bases_end(); I != E; ++I) {
413 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
414 if (!I->isVirtual() && Base->getNumVBases() > 0)
415 return Base;
416 }
417 llvm_unreachable("RD must have an nv base with vbases");
418}
419
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000420CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
421 assert(RD->getNumVBases());
422 CharUnits Total = CharUnits::Zero();
423 while (RD) {
424 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
425 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
426 // -1 is the sentinel for no vbptr.
427 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
428 Total += VBPtrOffset;
429 break;
430 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000431 RD = FindFirstNVBaseWithVBases(RD);
432 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000433 }
434 return Total;
435}
436
437llvm::Value *
438MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
439 llvm::Value *This,
440 const CXXRecordDecl *ClassDecl,
441 const CXXRecordDecl *BaseClassDecl) {
442 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
443 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000444 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000445 CharUnits VBTableChars =
446 IntSize *
447 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000448 llvm::Value *VBTableOffset =
449 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
450
451 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000452 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000453 VBPtrToNewBase =
454 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
455 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
456}
457
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000458bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
459 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000460}
461
Reid Kleckner89077a12013-12-17 19:46:40 +0000462void MicrosoftCXXABI::BuildConstructorSignature(
463 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
464 SmallVectorImpl<CanQualType> &ArgTys) {
465
466 // All parameters are already in place except is_most_derived, which goes
467 // after 'this' if it's variadic and last if it's not.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000468
469 const CXXRecordDecl *Class = Ctor->getParent();
Reid Kleckner89077a12013-12-17 19:46:40 +0000470 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000471 if (Class->getNumVBases()) {
Reid Kleckner89077a12013-12-17 19:46:40 +0000472 if (FPT->isVariadic())
473 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
474 else
475 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000476 }
477}
478
Reid Kleckner7810af02013-06-19 15:20:38 +0000479llvm::BasicBlock *
480MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
481 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000482 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
483 assert(IsMostDerivedClass &&
484 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000485 llvm::Value *IsCompleteObject =
486 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000487
488 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
489 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
490 CGF.Builder.CreateCondBr(IsCompleteObject,
491 CallVbaseCtorsBB, SkipVbaseCtorsBB);
492
493 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000494
495 // Fill in the vbtable pointers here.
496 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000497
498 // CGF will put the base ctor calls in this basic block for us later.
499
500 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000501}
502
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000503void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
504 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
505 // In most cases, an override for a vbase virtual method can adjust
506 // the "this" parameter by applying a constant offset.
507 // However, this is not enough while a constructor or a destructor of some
508 // class X is being executed if all the following conditions are met:
509 // - X has virtual bases, (1)
510 // - X overrides a virtual method M of a vbase Y, (2)
511 // - X itself is a vbase of the most derived class.
512 //
513 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
514 // which holds the extra amount of "this" adjustment we must do when we use
515 // the X vftables (i.e. during X ctor or dtor).
516 // Outside the ctors and dtors, the values of vtorDisps are zero.
517
518 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
519 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
520 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
521 CGBuilderTy &Builder = CGF.Builder;
522
523 unsigned AS =
524 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
525 llvm::Value *Int8This = 0; // Initialize lazily.
526
527 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
528 I != E; ++I) {
529 if (!I->second.hasVtorDisp())
530 continue;
531
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000532 llvm::Value *VBaseOffset =
533 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000534 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
535 // just to Trunc back immediately.
536 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
537 uint64_t ConstantVBaseOffset =
538 Layout.getVBaseClassOffset(I->first).getQuantity();
539
540 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
541 llvm::Value *VtorDispValue = Builder.CreateSub(
542 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
543 "vtordisp.value");
544
545 if (!Int8This)
546 Int8This = Builder.CreateBitCast(getThisValue(CGF),
547 CGF.Int8Ty->getPointerTo(AS));
548 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
549 // vtorDisp is always the 32-bits before the vbase in the class layout.
550 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
551 VtorDispPtr = Builder.CreateBitCast(
552 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
553
554 Builder.CreateStore(VtorDispValue, VtorDispPtr);
555 }
556}
557
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000558void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
559 // There's only one constructor type in this ABI.
560 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
561}
562
Reid Kleckner7810af02013-06-19 15:20:38 +0000563void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
564 const CXXRecordDecl *RD) {
565 llvm::Value *ThisInt8Ptr =
566 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
Reid Kleckner5f080942014-01-03 23:42:00 +0000567 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000568
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000569 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
570 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +0000571 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000572 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner7810af02013-06-19 15:20:38 +0000573 const ASTRecordLayout &SubobjectLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +0000574 CGM.getContext().getASTRecordLayout(VBT->BaseWithVBPtr);
575 CharUnits Offs = VBT->NonVirtualOffset;
576 Offs += SubobjectLayout.getVBPtrOffset();
577 if (VBT->getVBaseWithVBPtr())
578 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVBPtr());
Reid Kleckner7810af02013-06-19 15:20:38 +0000579 llvm::Value *VBPtr =
Reid Kleckner5f080942014-01-03 23:42:00 +0000580 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000581 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
Reid Kleckner5f080942014-01-03 23:42:00 +0000582 "vbptr." + VBT->ReusingBase->getName());
Reid Klecknerb40a27d2014-01-03 00:14:35 +0000583 CGF.Builder.CreateStore(GV, VBPtr);
Reid Kleckner7810af02013-06-19 15:20:38 +0000584 }
585}
586
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000587void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
588 CXXDtorType Type,
589 CanQualType &ResTy,
590 SmallVectorImpl<CanQualType> &ArgTys) {
591 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000592
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000593 // TODO: 'for base' flag
594
595 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000596 // The scalar deleting destructor takes an implicit int parameter.
597 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000598 }
599}
600
Reid Klecknere7de47e2013-07-22 13:51:44 +0000601void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
602 // The TU defining a dtor is only guaranteed to emit a base destructor. All
603 // other destructor variants are delegating thunks.
604 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
605}
606
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000607llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
608 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
609 GD = GD.getCanonicalDecl();
610 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000611 // FIXME: consider splitting the vdtor vs regular method code into two
612 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000613
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000614 GlobalDecl LookupGD = GD;
615 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
616 // Complete dtors take a pointer to the complete object,
617 // thus don't need adjustment.
618 if (GD.getDtorType() == Dtor_Complete)
619 return This;
620
621 // There's only Dtor_Deleting in vftable but it shares the this adjustment
622 // with the base one, so look up the deleting one instead.
623 LookupGD = GlobalDecl(DD, Dtor_Deleting);
624 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000625 MicrosoftVTableContext::MethodVFTableLocation ML =
626 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000627
628 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
629 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000630 CharUnits StaticOffset = ML.VFPtrOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000631 if (ML.VBase) {
632 bool AvoidVirtualOffset = false;
633 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
634 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000635 // same record type or another destructor of a more derived type;
636 // or a constructor of the same record type if an exception is thrown.
637 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
638 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000639 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000640 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000641
642 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000643 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
644 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
645 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
646 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
647 // We're calling the main base dtor from a complete structor,
648 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000649 AvoidVirtualOffset = true;
650 } else {
651 // Let's see if we try to call a destructor of a non-virtual base.
652 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
653 E = CurRD->bases_end(); I != E; ++I) {
654 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
655 continue;
656 // If we call a base destructor for a non-virtual base, we statically
657 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000658 // The total offset should reflect the adjustment done by
659 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000660 AvoidVirtualOffset = true;
661 break;
662 }
663 }
664 }
665
666 if (AvoidVirtualOffset) {
667 const ASTRecordLayout &Layout =
668 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000669 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
670 } else {
671 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000672 llvm::Value *VBaseOffset =
673 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000674 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
675 }
676 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000677 if (!StaticOffset.isZero()) {
678 assert(StaticOffset.isPositive());
679 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000680 if (ML.VBase) {
681 // Non-virtual adjustment might result in a pointer outside the allocated
682 // object, e.g. if the final overrider class is laid out after the virtual
683 // base that declares a method in the most derived class.
684 // FIXME: Update the code that emits this adjustment in thunks prologues.
685 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
686 } else {
687 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
688 StaticOffset.getQuantity());
689 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000690 }
691 return This;
692}
693
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000694static bool IsDeletingDtor(GlobalDecl GD) {
695 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
696 if (isa<CXXDestructorDecl>(MD)) {
697 return GD.getDtorType() == Dtor_Deleting;
698 }
699 return false;
700}
701
Reid Kleckner89077a12013-12-17 19:46:40 +0000702void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
703 QualType &ResTy,
704 FunctionArgList &Params) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000705 ASTContext &Context = getContext();
706 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
Reid Kleckner89077a12013-12-17 19:46:40 +0000707 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000708 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
709 ImplicitParamDecl *IsMostDerived
710 = ImplicitParamDecl::Create(Context, 0,
711 CGF.CurGD.getDecl()->getLocation(),
712 &Context.Idents.get("is_most_derived"),
713 Context.IntTy);
Reid Kleckner89077a12013-12-17 19:46:40 +0000714 // The 'most_derived' parameter goes second if the ctor is variadic and last
715 // if it's not. Dtors can't be variadic.
716 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
717 if (FPT->isVariadic())
718 Params.insert(Params.begin() + 1, IsMostDerived);
719 else
720 Params.push_back(IsMostDerived);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000721 getStructorImplicitParamDecl(CGF) = IsMostDerived;
722 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000723 ImplicitParamDecl *ShouldDelete
724 = ImplicitParamDecl::Create(Context, 0,
725 CGF.CurGD.getDecl()->getLocation(),
726 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000727 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000728 Params.push_back(ShouldDelete);
729 getStructorImplicitParamDecl(CGF) = ShouldDelete;
730 }
John McCall0f999f32012-09-25 08:00:39 +0000731}
732
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000733llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
734 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
735 GD = GD.getCanonicalDecl();
736 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000737
738 GlobalDecl LookupGD = GD;
739 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
740 // Complete destructors take a pointer to the complete object as a
741 // parameter, thus don't need this adjustment.
742 if (GD.getDtorType() == Dtor_Complete)
743 return This;
744
745 // There's no Dtor_Base in vftable but it shares the this adjustment with
746 // the deleting one, so look it up instead.
747 LookupGD = GlobalDecl(DD, Dtor_Deleting);
748 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000749
750 // In this ABI, every virtual function takes a pointer to one of the
751 // subobjects that first defines it as the 'this' parameter, rather than a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000752 // pointer to the final overrider subobject. Thus, we need to adjust it back
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000753 // to the final overrider subobject before use.
754 // See comments in the MicrosoftVFTableContext implementation for the details.
755
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000756 MicrosoftVTableContext::MethodVFTableLocation ML =
757 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000758 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000759 if (ML.VBase) {
760 const ASTRecordLayout &DerivedLayout =
761 CGF.getContext().getASTRecordLayout(MD->getParent());
762 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
763 }
764
765 if (Adjustment.isZero())
766 return This;
767
768 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
769 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
770 *thisTy = This->getType();
771
772 This = CGF.Builder.CreateBitCast(This, charPtrTy);
773 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000774 This =
775 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000776 return CGF.Builder.CreateBitCast(This, thisTy);
777}
778
John McCall0f999f32012-09-25 08:00:39 +0000779void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
780 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000781
782 /// If this is a function that the ABI specifies returns 'this', initialize
783 /// the return slot to 'this' at the start of the function.
784 ///
785 /// Unlike the setting of return types, this is done within the ABI
786 /// implementation instead of by clients of CGCXXABI because:
787 /// 1) getThisValue is currently protected
788 /// 2) in theory, an ABI could implement 'this' returns some other way;
789 /// HasThisReturn only specifies a contract, not the implementation
790 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000791 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000792
793 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
794 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
795 assert(getStructorImplicitParamDecl(CGF) &&
796 "no implicit parameter for a constructor with virtual bases?");
797 getStructorImplicitParamValue(CGF)
798 = CGF.Builder.CreateLoad(
799 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
800 "is_most_derived");
801 }
802
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000803 if (IsDeletingDtor(CGF.CurGD)) {
804 assert(getStructorImplicitParamDecl(CGF) &&
805 "no implicit parameter for a deleting destructor?");
806 getStructorImplicitParamValue(CGF)
807 = CGF.Builder.CreateLoad(
808 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
809 "should_call_delete");
810 }
John McCall0f999f32012-09-25 08:00:39 +0000811}
812
Reid Kleckner89077a12013-12-17 19:46:40 +0000813unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
814 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
815 bool ForVirtualBase, bool Delegating, CallArgList &Args) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000816 assert(Type == Ctor_Complete || Type == Ctor_Base);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000817
Reid Kleckner89077a12013-12-17 19:46:40 +0000818 // Check if we need a 'most_derived' parameter.
819 if (!D->getParent()->getNumVBases())
820 return 0;
821
822 // Add the 'most_derived' argument second if we are variadic or last if not.
823 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
824 llvm::Value *MostDerivedArg =
825 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
826 RValue RV = RValue::get(MostDerivedArg);
827 if (MostDerivedArg) {
828 if (FPT->isVariadic())
829 Args.insert(Args.begin() + 1,
830 CallArg(RV, getContext().IntTy, /*needscopy=*/false));
831 else
832 Args.add(RV, getContext().IntTy);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000833 }
834
Reid Kleckner89077a12013-12-17 19:46:40 +0000835 return 1; // Added one arg.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000836}
837
Reid Kleckner6fe771a2013-12-13 00:53:54 +0000838void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
839 const CXXDestructorDecl *DD,
840 CXXDtorType Type, bool ForVirtualBase,
841 bool Delegating, llvm::Value *This) {
842 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
843
844 if (DD->isVirtual())
845 This = adjustThisArgumentForVirtualCall(CGF, GlobalDecl(DD, Type), This);
846
847 // FIXME: Provide a source location here.
848 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
849 /*ImplicitParam=*/0, /*ImplicitParamTy=*/QualType(), 0, 0);
850}
851
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000852void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
853 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000854 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
855 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000856 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
857
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000858 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000859 E = VFPtrs.end(); I != E; ++I) {
860 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
861 if (VTable->hasInitializer())
862 continue;
863
864 const VTableLayout &VTLayout =
865 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
866 llvm::Constant *Init = CGVT.CreateVTableInitializer(
867 RD, VTLayout.vtable_component_begin(),
868 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
869 VTLayout.getNumVTableThunks());
870 VTable->setInitializer(Init);
871
872 VTable->setLinkage(Linkage);
873 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
874 }
875}
876
877llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
878 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
879 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
880 NeedsVirtualOffset = (NearestVBase != 0);
881
882 llvm::Value *VTableAddressPoint =
883 getAddrOfVTable(VTableClass, Base.getBaseOffset());
884 if (!VTableAddressPoint) {
885 assert(Base.getBase()->getNumVBases() &&
886 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
887 }
888 return VTableAddressPoint;
889}
890
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000891static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
892 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
893 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000894 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000895 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000896}
897
898llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
899 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
900 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
901 assert(VTable && "Couldn't find a vftable for the given base?");
902 return VTable;
903}
904
905llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
906 CharUnits VPtrOffset) {
907 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
908 // shouldn't be used in the given record type. We want to cache this result in
909 // VFTablesMap, thus a simple zero check is not sufficient.
910 VFTableIdTy ID(RD, VPtrOffset);
911 VFTablesMapTy::iterator I;
912 bool Inserted;
913 llvm::tie(I, Inserted) = VFTablesMap.insert(
914 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
915 if (!Inserted)
916 return I->second;
917
918 llvm::GlobalVariable *&VTable = I->second;
919
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000920 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
921 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
922 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000923
924 if (DeferredVFTables.insert(RD)) {
925 // We haven't processed this record type before.
926 // Queue up this v-table for possible deferred emission.
927 CGM.addDeferredVTable(RD);
928
929#ifndef NDEBUG
930 // Create all the vftables at once in order to make sure each vftable has
931 // a unique mangled name.
932 llvm::StringSet<> ObservedMangledNames;
933 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
934 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000935 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000936 if (!ObservedMangledNames.insert(Name.str()))
937 llvm_unreachable("Already saw this mangling before?");
938 }
939#endif
940 }
941
942 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
943 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
944 continue;
945
946 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
947 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000948 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000949 .getNumVTableComponents());
950
951 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000952 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000953 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
954 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
955 VTable->setUnnamedAddr(true);
956 break;
957 }
958
959 return VTable;
960}
961
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000962llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
963 GlobalDecl GD,
964 llvm::Value *This,
965 llvm::Type *Ty) {
966 GD = GD.getCanonicalDecl();
967 CGBuilderTy &Builder = CGF.Builder;
968
969 Ty = Ty->getPointerTo()->getPointerTo();
970 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
971 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
972
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000973 MicrosoftVTableContext::MethodVFTableLocation ML =
974 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000975 llvm::Value *VFuncPtr =
976 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
977 return Builder.CreateLoad(VFuncPtr);
978}
979
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000980void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
981 const CXXDestructorDecl *Dtor,
982 CXXDtorType DtorType,
983 SourceLocation CallLoc,
984 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000985 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
986
987 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000988 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000989 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000990 const CGFunctionInfo *FInfo =
991 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000992 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000993 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000994
995 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000996 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000997 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000998 DtorType == Dtor_Deleting);
999
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +00001000 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001001 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +00001002 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001003}
1004
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001005const VBTableGlobals &
1006MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001007 // At this layer, we can key the cache off of a single class, which is much
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001008 // easier than caching each vbtable individually.
1009 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1010 bool Added;
1011 llvm::tie(Entry, Added) = VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1012 VBTableGlobals &VBGlobals = Entry->second;
1013 if (!Added)
1014 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +00001015
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001016 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1017 VBGlobals.VBTables = &Context.enumerateVBTables(RD);
Reid Kleckner7810af02013-06-19 15:20:38 +00001018
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001019 // Cache the globals for all vbtables so we don't have to recompute the
1020 // mangled names.
1021 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1022 for (VBTableVector::const_iterator I = VBGlobals.VBTables->begin(),
1023 E = VBGlobals.VBTables->end();
1024 I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +00001025 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001026 }
1027
1028 return VBGlobals;
Reid Kleckner7810af02013-06-19 15:20:38 +00001029}
1030
Hans Wennborg88497d62013-11-15 17:24:45 +00001031llvm::Function *
1032MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1033 StringRef ThunkName) {
1034 // If the thunk has been generated previously, just return it.
1035 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1036 return cast<llvm::Function>(GV);
1037
1038 // Create the llvm::Function.
1039 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1040 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1041 llvm::Function *ThunkFn =
1042 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1043 ThunkName.str(), &CGM.getModule());
1044 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1045
Hans Wennborg88497d62013-11-15 17:24:45 +00001046 ThunkFn->setLinkage(MD->isExternallyVisible()
1047 ? llvm::GlobalValue::LinkOnceODRLinkage
1048 : llvm::GlobalValue::InternalLinkage);
1049
1050 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1051 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1052
1053 // Start codegen.
1054 CodeGenFunction CGF(CGM);
1055 CGF.StartThunk(ThunkFn, MD, FnInfo);
1056
1057 // Get to the Callee.
1058 llvm::Value *This = CGF.LoadCXXThis();
1059 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1060
1061 // Make the call and return the result.
1062 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1063
1064 return ThunkFn;
1065}
1066
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001067void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001068 const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1069 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
Reid Kleckner5f080942014-01-03 23:42:00 +00001070 const VBTableInfo *VBT = (*VBGlobals.VBTables)[I];
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001071 llvm::GlobalVariable *GV = VBGlobals.Globals[I];
Reid Kleckner5f080942014-01-03 23:42:00 +00001072 emitVBTableDefinition(*VBT, RD, GV);
Reid Kleckner7810af02013-06-19 15:20:38 +00001073 }
1074}
1075
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001076llvm::GlobalVariable *
1077MicrosoftCXXABI::getAddrOfVBTable(const VBTableInfo &VBT,
1078 const CXXRecordDecl *RD,
1079 llvm::GlobalVariable::LinkageTypes Linkage) {
1080 SmallString<256> OutName;
1081 llvm::raw_svector_ostream Out(OutName);
1082 MicrosoftMangleContext &Mangler =
1083 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext());
1084 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out);
1085 Out.flush();
1086 StringRef Name = OutName.str();
1087
1088 llvm::ArrayType *VBTableType =
1089 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1090
1091 assert(!CGM.getModule().getNamedGlobal(Name) &&
1092 "vbtable with this name already exists: mangling bug?");
1093 llvm::GlobalVariable *GV =
1094 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1095 GV->setUnnamedAddr(true);
1096 return GV;
1097}
1098
1099void MicrosoftCXXABI::emitVBTableDefinition(const VBTableInfo &VBT,
1100 const CXXRecordDecl *RD,
1101 llvm::GlobalVariable *GV) const {
1102 const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1103
1104 assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1105 "should only emit vbtables for classes with vbtables");
1106
1107 const ASTRecordLayout &BaseLayout =
Reid Kleckner5f080942014-01-03 23:42:00 +00001108 CGM.getContext().getASTRecordLayout(VBT.BaseWithVBPtr);
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001109 const ASTRecordLayout &DerivedLayout =
1110 CGM.getContext().getASTRecordLayout(RD);
1111
1112 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 0);
1113
1114 // The offset from ReusingBase's vbptr to itself always leads.
1115 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1116 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1117
1118 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1119 for (CXXRecordDecl::base_class_const_iterator I = ReusingBase->vbases_begin(),
1120 E = ReusingBase->vbases_end();
1121 I != E; ++I) {
1122 const CXXRecordDecl *VBase = I->getType()->getAsCXXRecordDecl();
1123 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1124 assert(!Offset.isNegative());
Reid Kleckner5f080942014-01-03 23:42:00 +00001125
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001126 // Make it relative to the subobject vbptr.
Reid Kleckner5f080942014-01-03 23:42:00 +00001127 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1128 if (VBT.getVBaseWithVBPtr())
1129 CompleteVBPtrOffset +=
1130 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVBPtr());
1131 Offset -= CompleteVBPtrOffset;
1132
Reid Klecknerb40a27d2014-01-03 00:14:35 +00001133 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1134 assert(Offsets[VBIndex] == 0 && "The same vbindex seen twice?");
1135 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1136 }
1137
1138 assert(Offsets.size() ==
1139 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1140 ->getElementType())->getNumElements());
1141 llvm::ArrayType *VBTableType =
1142 llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1143 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1144 GV->setInitializer(Init);
1145
1146 // Set the right visibility.
1147 CGM.setTypeVisibility(GV, RD, CodeGenModule::TVK_ForVTable);
1148}
1149
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001150llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1151 llvm::Value *This,
1152 const ThisAdjustment &TA) {
1153 if (TA.isEmpty())
1154 return This;
1155
1156 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1157
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001158 if (!TA.Virtual.isEmpty()) {
1159 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1160 // Adjust the this argument based on the vtordisp value.
1161 llvm::Value *VtorDispPtr =
1162 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1163 VtorDispPtr =
1164 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1165 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1166 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1167
1168 if (TA.Virtual.Microsoft.VBPtrOffset) {
1169 // If the final overrider is defined in a virtual base other than the one
1170 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1171 // the vbtable of the derived class.
1172 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1173 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1174 llvm::Value *VBPtr;
1175 llvm::Value *VBaseOffset =
1176 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1177 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1178 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1179 }
1180 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001181
1182 if (TA.NonVirtual) {
1183 // Non-virtual adjustment might result in a pointer outside the allocated
1184 // object, e.g. if the final overrider class is laid out after the virtual
1185 // base that declares a method in the most derived class.
1186 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1187 }
1188
1189 // Don't need to bitcast back, the call CodeGen will handle this.
1190 return V;
1191}
1192
1193llvm::Value *
1194MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1195 const ReturnAdjustment &RA) {
1196 if (RA.isEmpty())
1197 return Ret;
1198
1199 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1200
1201 if (RA.Virtual.Microsoft.VBIndex) {
1202 assert(RA.Virtual.Microsoft.VBIndex > 0);
1203 int32_t IntSize =
1204 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1205 llvm::Value *VBPtr;
1206 llvm::Value *VBaseOffset =
1207 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1208 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1209 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1210 }
1211
1212 if (RA.NonVirtual)
1213 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1214
1215 // Cast back to the original type.
1216 return CGF.Builder.CreateBitCast(V, Ret->getType());
1217}
1218
John McCallb91cd662012-05-01 05:23:51 +00001219bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1220 QualType elementType) {
1221 // Microsoft seems to completely ignore the possibility of a
1222 // two-argument usual deallocation function.
1223 return elementType.isDestructedType();
1224}
1225
1226bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1227 // Microsoft seems to completely ignore the possibility of a
1228 // two-argument usual deallocation function.
1229 return expr->getAllocatedType().isDestructedType();
1230}
1231
1232CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1233 // The array cookie is always a size_t; we then pad that out to the
1234 // alignment of the element type.
1235 ASTContext &Ctx = getContext();
1236 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1237 Ctx.getTypeAlignInChars(type));
1238}
1239
1240llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1241 llvm::Value *allocPtr,
1242 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001243 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001244 llvm::Value *numElementsPtr =
1245 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1246 return CGF.Builder.CreateLoad(numElementsPtr);
1247}
1248
1249llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1250 llvm::Value *newPtr,
1251 llvm::Value *numElements,
1252 const CXXNewExpr *expr,
1253 QualType elementType) {
1254 assert(requiresArrayCookie(expr));
1255
1256 // The size of the cookie.
1257 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1258
1259 // Compute an offset to the cookie.
1260 llvm::Value *cookiePtr = newPtr;
1261
1262 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001263 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001264 llvm::Value *numElementsPtr
1265 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1266 CGF.Builder.CreateStore(numElements, numElementsPtr);
1267
1268 // Finally, compute a pointer to the actual data buffer by skipping
1269 // over the cookie completely.
1270 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1271 cookieSize.getQuantity());
1272}
1273
John McCallc84ed6a2012-05-01 06:13:13 +00001274void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001275 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001276 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001277 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1278 // threadsafe. Since the user may be linking in inline functions compiled by
1279 // cl.exe, there's no reason to provide a false sense of security by using
1280 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001281
Richard Smithdbf74ba2013-04-14 23:01:42 +00001282 if (D.getTLSKind())
1283 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1284
Reid Klecknerd8110b62013-09-10 20:14:30 +00001285 CGBuilderTy &Builder = CGF.Builder;
1286 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1287 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1288
1289 // Get the guard variable for this function if we have one already.
1290 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1291
1292 unsigned BitIndex;
1293 if (D.isExternallyVisible()) {
1294 // Externally visible variables have to be numbered in Sema to properly
1295 // handle unreachable VarDecls.
1296 BitIndex = getContext().getManglingNumber(&D);
1297 assert(BitIndex > 0);
1298 BitIndex--;
1299 } else {
1300 // Non-externally visible variables are numbered here in CodeGen.
1301 BitIndex = GI.BitIndex++;
1302 }
1303
1304 if (BitIndex >= 32) {
1305 if (D.isExternallyVisible())
1306 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1307 BitIndex %= 32;
1308 GI.Guard = 0;
1309 }
1310
1311 // Lazily create the i32 bitfield for this function.
1312 if (!GI.Guard) {
1313 // Mangle the name for the guard.
1314 SmallString<256> GuardName;
1315 {
1316 llvm::raw_svector_ostream Out(GuardName);
1317 getMangleContext().mangleStaticGuardVariable(&D, Out);
1318 Out.flush();
1319 }
1320
1321 // Create the guard variable with a zero-initializer. Just absorb linkage
1322 // and visibility from the guarded variable.
1323 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1324 GV->getLinkage(), Zero, GuardName.str());
1325 GI.Guard->setVisibility(GV->getVisibility());
1326 } else {
1327 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1328 "static local from the same function had different linkage");
1329 }
1330
1331 // Pseudo code for the test:
1332 // if (!(GuardVar & MyGuardBit)) {
1333 // GuardVar |= MyGuardBit;
1334 // ... initialize the object ...;
1335 // }
1336
1337 // Test our bit from the guard variable.
1338 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1339 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1340 llvm::Value *IsInitialized =
1341 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1342 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1343 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1344 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1345
1346 // Set our bit in the guard variable and emit the initializer and add a global
1347 // destructor if appropriate.
1348 CGF.EmitBlock(InitBlock);
1349 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1350 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1351 Builder.CreateBr(EndBlock);
1352
1353 // Continue.
1354 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001355}
1356
Reid Kleckner2341ae32013-04-11 18:13:19 +00001357// Member pointer helpers.
1358static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1359 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001360}
1361
Reid Kleckner452abac2013-05-09 21:01:17 +00001362static bool hasOnlyOneField(bool IsMemberFunction,
1363 MSInheritanceModel Inheritance) {
1364 return Inheritance <= MSIM_SinglePolymorphic ||
1365 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001366}
1367
Reid Kleckner2341ae32013-04-11 18:13:19 +00001368// Only member pointers to functions need a this adjustment, since it can be
1369// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001370static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001371 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001372 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001373}
1374
1375static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1376 return Inheritance >= MSIM_Virtual;
1377}
1378
1379// Use zero for the field offset of a null data member pointer if we can
1380// guarantee that zero is not a valid field offset, or if the member pointer has
1381// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1382// use zero for null. If there are multiple fields, we can use zero even if it
1383// is a valid field offset because null-ness testing will check the other
1384// fields.
1385static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1386 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1387}
1388
1389bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1390 // Null-ness for function memptrs only depends on the first field, which is
1391 // the function pointer. The rest don't matter, so we can zero initialize.
1392 if (MPT->isMemberFunctionPointer())
1393 return true;
1394
1395 // The virtual base adjustment field is always -1 for null, so if we have one
1396 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1397 // valid field offset.
1398 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1399 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1400 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1401 nullFieldOffsetIsZero(Inheritance));
1402}
1403
1404llvm::Type *
1405MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1406 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1407 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1408 llvm::SmallVector<llvm::Type *, 4> fields;
1409 if (MPT->isMemberFunctionPointer())
1410 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1411 else
1412 fields.push_back(CGM.IntTy); // FieldOffset
1413
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001414 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1415 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001416 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001417 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001418 fields.push_back(CGM.IntTy);
1419 if (hasVirtualBaseAdjustmentField(Inheritance))
1420 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1421
1422 if (fields.size() == 1)
1423 return fields[0];
1424 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1425}
1426
1427void MicrosoftCXXABI::
1428GetNullMemberPointerFields(const MemberPointerType *MPT,
1429 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1430 assert(fields.empty());
1431 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1432 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1433 if (MPT->isMemberFunctionPointer()) {
1434 // FunctionPointerOrVirtualThunk
1435 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1436 } else {
1437 if (nullFieldOffsetIsZero(Inheritance))
1438 fields.push_back(getZeroInt()); // FieldOffset
1439 else
1440 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001441 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001442
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001443 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1444 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001445 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001446 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001447 fields.push_back(getZeroInt());
1448 if (hasVirtualBaseAdjustmentField(Inheritance))
1449 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001450}
1451
1452llvm::Constant *
1453MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001454 llvm::SmallVector<llvm::Constant *, 4> fields;
1455 GetNullMemberPointerFields(MPT, fields);
1456 if (fields.size() == 1)
1457 return fields[0];
1458 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1459 assert(Res->getType() == ConvertMemberPointerType(MPT));
1460 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001461}
1462
1463llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001464MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1465 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001466 const CXXRecordDecl *RD,
1467 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001468{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001469 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001470
1471 // Single inheritance class member pointer are represented as scalars instead
1472 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001473 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001474 return FirstField;
1475
Reid Kleckner2341ae32013-04-11 18:13:19 +00001476 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001477 fields.push_back(FirstField);
1478
1479 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001480 fields.push_back(llvm::ConstantInt::get(
1481 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001482
Reid Kleckner2341ae32013-04-11 18:13:19 +00001483 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001484 CharUnits Offs = CharUnits::Zero();
1485 if (RD->getNumVBases())
1486 Offs = GetVBPtrOffsetFromBases(RD);
1487 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001488 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001489
1490 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001491 if (hasVirtualBaseAdjustmentField(Inheritance))
1492 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001493
Reid Kleckner2341ae32013-04-11 18:13:19 +00001494 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001495}
1496
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001497llvm::Constant *
1498MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1499 CharUnits offset) {
1500 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1501 llvm::Constant *FirstField =
1502 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001503 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1504 CharUnits::Zero());
1505}
1506
1507llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1508 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1509}
1510
1511llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1512 QualType MPType) {
1513 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1514 const ValueDecl *MPD = MP.getMemberPointerDecl();
1515 if (!MPD)
1516 return EmitNullMemberPointer(MPT);
1517
1518 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1519
1520 // FIXME PR15713: Support virtual inheritance paths.
1521
1522 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1523 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1524 MD, ThisAdjustment);
1525
1526 CharUnits FieldOffset =
1527 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1528 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001529}
1530
1531llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001532MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1533 const CXXMethodDecl *MD,
1534 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001535 assert(MD->isInstance() && "Member function must not be static!");
1536 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001537 CodeGenTypes &Types = CGM.getTypes();
1538
1539 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001540 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001541 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1542 llvm::Type *Ty;
1543 // Check whether the function has a computable LLVM signature.
1544 if (Types.isFuncTypeConvertible(FPT)) {
1545 // The function has a computable LLVM signature; use the correct type.
1546 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1547 } else {
1548 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1549 // function type is incomplete.
1550 Ty = CGM.PtrDiffTy;
1551 }
1552 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1553 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001554 } else {
1555 MicrosoftVTableContext::MethodVFTableLocation ML =
1556 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1557 if (MD->isVariadic()) {
1558 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1559 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1560 } else if (!CGM.getTypes().isFuncTypeConvertible(
1561 MD->getType()->castAs<FunctionType>())) {
1562 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1563 "incomplete return or parameter type");
1564 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1565 } else if (ML.VBase) {
1566 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1567 "member function in virtual base class");
1568 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1569 } else {
1570 SmallString<256> ThunkName;
David Majnemer2a816452013-12-09 10:44:32 +00001571 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1572 getContext().getTargetInfo().getPointerWidth(0));
1573 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
Hans Wennborg88497d62013-11-15 17:24:45 +00001574 llvm::raw_svector_ostream Out(ThunkName);
1575 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1576 Out.flush();
1577
1578 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1579 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1580 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001581 }
1582
1583 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001584 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1585 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001586}
1587
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001588/// Member pointers are the same if they're either bitwise identical *or* both
1589/// null. Null-ness for function members is determined by the first field,
1590/// while for data member pointers we must compare all fields.
1591llvm::Value *
1592MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1593 llvm::Value *L,
1594 llvm::Value *R,
1595 const MemberPointerType *MPT,
1596 bool Inequality) {
1597 CGBuilderTy &Builder = CGF.Builder;
1598
1599 // Handle != comparisons by switching the sense of all boolean operations.
1600 llvm::ICmpInst::Predicate Eq;
1601 llvm::Instruction::BinaryOps And, Or;
1602 if (Inequality) {
1603 Eq = llvm::ICmpInst::ICMP_NE;
1604 And = llvm::Instruction::Or;
1605 Or = llvm::Instruction::And;
1606 } else {
1607 Eq = llvm::ICmpInst::ICMP_EQ;
1608 And = llvm::Instruction::And;
1609 Or = llvm::Instruction::Or;
1610 }
1611
1612 // If this is a single field member pointer (single inheritance), this is a
1613 // single icmp.
1614 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1615 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001616 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001617 return Builder.CreateICmp(Eq, L, R);
1618
1619 // Compare the first field.
1620 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1621 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1622 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1623
1624 // Compare everything other than the first field.
1625 llvm::Value *Res = 0;
1626 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1627 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1628 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1629 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1630 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1631 if (Res)
1632 Res = Builder.CreateBinOp(And, Res, Cmp);
1633 else
1634 Res = Cmp;
1635 }
1636
1637 // Check if the first field is 0 if this is a function pointer.
1638 if (MPT->isMemberFunctionPointer()) {
1639 // (l1 == r1 && ...) || l0 == 0
1640 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1641 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1642 Res = Builder.CreateBinOp(Or, Res, IsZero);
1643 }
1644
1645 // Combine the comparison of the first field, which must always be true for
1646 // this comparison to succeeed.
1647 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1648}
1649
Reid Kleckner407e8b62013-03-22 19:02:54 +00001650llvm::Value *
1651MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1652 llvm::Value *MemPtr,
1653 const MemberPointerType *MPT) {
1654 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001655 llvm::SmallVector<llvm::Constant *, 4> fields;
1656 // We only need one field for member functions.
1657 if (MPT->isMemberFunctionPointer())
1658 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1659 else
1660 GetNullMemberPointerFields(MPT, fields);
1661 assert(!fields.empty());
1662 llvm::Value *FirstField = MemPtr;
1663 if (MemPtr->getType()->isStructTy())
1664 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1665 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001666
Reid Kleckner2341ae32013-04-11 18:13:19 +00001667 // For function member pointers, we only need to test the function pointer
1668 // field. The other fields if any can be garbage.
1669 if (MPT->isMemberFunctionPointer())
1670 return Res;
1671
1672 // Otherwise, emit a series of compares and combine the results.
1673 for (int I = 1, E = fields.size(); I < E; ++I) {
1674 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1675 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1676 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1677 }
1678 return Res;
1679}
1680
Reid Kleckner452abac2013-05-09 21:01:17 +00001681bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1682 llvm::Constant *Val) {
1683 // Function pointers are null if the pointer in the first field is null.
1684 if (MPT->isMemberFunctionPointer()) {
1685 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1686 Val->getAggregateElement(0U) : Val;
1687 return FirstField->isNullValue();
1688 }
1689
1690 // If it's not a function pointer and it's zero initializable, we can easily
1691 // check zero.
1692 if (isZeroInitializable(MPT) && Val->isNullValue())
1693 return true;
1694
1695 // Otherwise, break down all the fields for comparison. Hopefully these
1696 // little Constants are reused, while a big null struct might not be.
1697 llvm::SmallVector<llvm::Constant *, 4> Fields;
1698 GetNullMemberPointerFields(MPT, Fields);
1699 if (Fields.size() == 1) {
1700 assert(Val->getType()->isIntegerTy());
1701 return Val == Fields[0];
1702 }
1703
1704 unsigned I, E;
1705 for (I = 0, E = Fields.size(); I != E; ++I) {
1706 if (Val->getAggregateElement(I) != Fields[I])
1707 break;
1708 }
1709 return I == E;
1710}
1711
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001712llvm::Value *
1713MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1714 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001715 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001716 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001717 llvm::Value **VBPtrOut) {
1718 CGBuilderTy &Builder = CGF.Builder;
1719 // Load the vbtable pointer from the vbptr in the instance.
1720 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1721 llvm::Value *VBPtr =
1722 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1723 if (VBPtrOut) *VBPtrOut = VBPtr;
1724 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1725 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1726
1727 // Load an i32 offset from the vb-table.
1728 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1729 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1730 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1731}
1732
Reid Kleckner2341ae32013-04-11 18:13:19 +00001733// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1734// it.
1735llvm::Value *
1736MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1737 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001738 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001739 llvm::Value *VBPtrOffset) {
1740 CGBuilderTy &Builder = CGF.Builder;
1741 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1742 llvm::BasicBlock *OriginalBB = 0;
1743 llvm::BasicBlock *SkipAdjustBB = 0;
1744 llvm::BasicBlock *VBaseAdjustBB = 0;
1745
1746 // In the unspecified inheritance model, there might not be a vbtable at all,
1747 // in which case we need to skip the virtual base lookup. If there is a
1748 // vbtable, the first entry is a no-op entry that gives back the original
1749 // base, so look for a virtual base adjustment offset of zero.
1750 if (VBPtrOffset) {
1751 OriginalBB = Builder.GetInsertBlock();
1752 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1753 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1754 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001755 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001756 "memptr.is_vbase");
1757 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1758 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001759 }
1760
Reid Kleckner2341ae32013-04-11 18:13:19 +00001761 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1762 // know the vbptr offset.
1763 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001764 CharUnits offs = CharUnits::Zero();
1765 if (RD->getNumVBases()) {
1766 offs = GetVBPtrOffsetFromBases(RD);
1767 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001768 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1769 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001770 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001771 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001772 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001773 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1774
1775 // Merge control flow with the case where we didn't have to adjust.
1776 if (VBaseAdjustBB) {
1777 Builder.CreateBr(SkipAdjustBB);
1778 CGF.EmitBlock(SkipAdjustBB);
1779 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1780 Phi->addIncoming(Base, OriginalBB);
1781 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1782 return Phi;
1783 }
1784 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001785}
1786
1787llvm::Value *
1788MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1789 llvm::Value *Base,
1790 llvm::Value *MemPtr,
1791 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001792 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001793 unsigned AS = Base->getType()->getPointerAddressSpace();
1794 llvm::Type *PType =
1795 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1796 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001797 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1798 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001799
Reid Kleckner2341ae32013-04-11 18:13:19 +00001800 // Extract the fields we need, regardless of model. We'll apply them if we
1801 // have them.
1802 llvm::Value *FieldOffset = MemPtr;
1803 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1804 llvm::Value *VBPtrOffset = 0;
1805 if (MemPtr->getType()->isStructTy()) {
1806 // We need to extract values.
1807 unsigned I = 0;
1808 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1809 if (hasVBPtrOffsetField(Inheritance))
1810 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1811 if (hasVirtualBaseAdjustmentField(Inheritance))
1812 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001813 }
1814
Reid Kleckner2341ae32013-04-11 18:13:19 +00001815 if (VirtualBaseAdjustmentOffset) {
1816 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1817 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001818 }
Reid Klecknerae945122013-12-05 22:44:07 +00001819
1820 // Cast to char*.
1821 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1822
1823 // Apply the offset, which we assume is non-null.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001824 llvm::Value *Addr =
1825 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001826
1827 // Cast the address to the appropriate pointer type, adopting the address
1828 // space of the base pointer.
1829 return Builder.CreateBitCast(Addr, PType);
1830}
1831
Reid Kleckner452abac2013-05-09 21:01:17 +00001832static MSInheritanceModel
1833getInheritanceFromMemptr(const MemberPointerType *MPT) {
1834 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1835}
1836
1837llvm::Value *
1838MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1839 const CastExpr *E,
1840 llvm::Value *Src) {
1841 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1842 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1843 E->getCastKind() == CK_ReinterpretMemberPointer);
1844
1845 // Use constant emission if we can.
1846 if (isa<llvm::Constant>(Src))
1847 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1848
1849 // We may be adding or dropping fields from the member pointer, so we need
1850 // both types and the inheritance models of both records.
1851 const MemberPointerType *SrcTy =
1852 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1853 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1854 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1855 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1856 bool IsFunc = SrcTy->isMemberFunctionPointer();
1857
1858 // If the classes use the same null representation, reinterpret_cast is a nop.
1859 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1860 if (IsReinterpret && (IsFunc ||
1861 nullFieldOffsetIsZero(SrcInheritance) ==
1862 nullFieldOffsetIsZero(DstInheritance)))
1863 return Src;
1864
1865 CGBuilderTy &Builder = CGF.Builder;
1866
1867 // Branch past the conversion if Src is null.
1868 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1869 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1870
1871 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1872 // pointer value of the destination type.
1873 if (IsReinterpret) {
1874 // For reinterpret casts, sema ensures that src and dst are both functions
1875 // or data and have the same size, which means the LLVM types should match.
1876 assert(Src->getType() == DstNull->getType());
1877 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1878 }
1879
1880 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1881 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1882 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1883 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1884 CGF.EmitBlock(ConvertBB);
1885
1886 // Decompose src.
1887 llvm::Value *FirstField = Src;
1888 llvm::Value *NonVirtualBaseAdjustment = 0;
1889 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1890 llvm::Value *VBPtrOffset = 0;
1891 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1892 // We need to extract values.
1893 unsigned I = 0;
1894 FirstField = Builder.CreateExtractValue(Src, I++);
1895 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1896 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1897 if (hasVBPtrOffsetField(SrcInheritance))
1898 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1899 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1900 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1901 }
1902
1903 // For data pointers, we adjust the field offset directly. For functions, we
1904 // have a separate field.
1905 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1906 if (Adj) {
1907 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1908 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1909 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1910 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1911 NVAdjustField = getZeroInt();
1912 if (isDerivedToBase)
1913 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1914 else
1915 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1916 }
1917
1918 // FIXME PR15713: Support conversions through virtually derived classes.
1919
1920 // Recompose dst from the null struct and the adjusted fields from src.
1921 llvm::Value *Dst;
1922 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1923 Dst = FirstField;
1924 } else {
1925 Dst = llvm::UndefValue::get(DstNull->getType());
1926 unsigned Idx = 0;
1927 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1928 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1929 Dst = Builder.CreateInsertValue(
1930 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1931 if (hasVBPtrOffsetField(DstInheritance))
1932 Dst = Builder.CreateInsertValue(
1933 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1934 if (hasVirtualBaseAdjustmentField(DstInheritance))
1935 Dst = Builder.CreateInsertValue(
1936 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1937 }
1938 Builder.CreateBr(ContinueBB);
1939
1940 // In the continuation, choose between DstNull and Dst.
1941 CGF.EmitBlock(ContinueBB);
1942 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1943 Phi->addIncoming(DstNull, OriginalBB);
1944 Phi->addIncoming(Dst, ConvertBB);
1945 return Phi;
1946}
1947
1948llvm::Constant *
1949MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1950 llvm::Constant *Src) {
1951 const MemberPointerType *SrcTy =
1952 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1953 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1954
1955 // If src is null, emit a new null for dst. We can't return src because dst
1956 // might have a new representation.
1957 if (MemberPointerConstantIsNull(SrcTy, Src))
1958 return EmitNullMemberPointer(DstTy);
1959
1960 // We don't need to do anything for reinterpret_casts of non-null member
1961 // pointers. We should only get here when the two type representations have
1962 // the same size.
1963 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1964 return Src;
1965
1966 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1967 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1968
1969 // Decompose src.
1970 llvm::Constant *FirstField = Src;
1971 llvm::Constant *NonVirtualBaseAdjustment = 0;
1972 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1973 llvm::Constant *VBPtrOffset = 0;
1974 bool IsFunc = SrcTy->isMemberFunctionPointer();
1975 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1976 // We need to extract values.
1977 unsigned I = 0;
1978 FirstField = Src->getAggregateElement(I++);
1979 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1980 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1981 if (hasVBPtrOffsetField(SrcInheritance))
1982 VBPtrOffset = Src->getAggregateElement(I++);
1983 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1984 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1985 }
1986
1987 // For data pointers, we adjust the field offset directly. For functions, we
1988 // have a separate field.
1989 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1990 if (Adj) {
1991 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1992 llvm::Constant *&NVAdjustField =
1993 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1994 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1995 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1996 NVAdjustField = getZeroInt();
1997 if (IsDerivedToBase)
1998 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1999 else
2000 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2001 }
2002
2003 // FIXME PR15713: Support conversions through virtually derived classes.
2004
2005 // Recompose dst from the null struct and the adjusted fields from src.
2006 if (hasOnlyOneField(IsFunc, DstInheritance))
2007 return FirstField;
2008
2009 llvm::SmallVector<llvm::Constant *, 4> Fields;
2010 Fields.push_back(FirstField);
2011 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
2012 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2013 if (hasVBPtrOffsetField(DstInheritance))
2014 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2015 if (hasVirtualBaseAdjustmentField(DstInheritance))
2016 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2017 return llvm::ConstantStruct::getAnon(Fields);
2018}
2019
Reid Kleckner2341ae32013-04-11 18:13:19 +00002020llvm::Value *
2021MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
2022 llvm::Value *&This,
2023 llvm::Value *MemPtr,
2024 const MemberPointerType *MPT) {
2025 assert(MPT->isMemberFunctionPointer());
2026 const FunctionProtoType *FPT =
2027 MPT->getPointeeType()->castAs<FunctionProtoType>();
2028 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
2029 llvm::FunctionType *FTy =
2030 CGM.getTypes().GetFunctionType(
2031 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2032 CGBuilderTy &Builder = CGF.Builder;
2033
2034 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2035
2036 // Extract the fields we need, regardless of model. We'll apply them if we
2037 // have them.
2038 llvm::Value *FunctionPointer = MemPtr;
2039 llvm::Value *NonVirtualBaseAdjustment = NULL;
2040 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
2041 llvm::Value *VBPtrOffset = NULL;
2042 if (MemPtr->getType()->isStructTy()) {
2043 // We need to extract values.
2044 unsigned I = 0;
2045 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002046 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
2047 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00002048 if (hasVBPtrOffsetField(Inheritance))
2049 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00002050 if (hasVirtualBaseAdjustmentField(Inheritance))
2051 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2052 }
2053
2054 if (VirtualBaseAdjustmentOffset) {
2055 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
2056 VBPtrOffset);
2057 }
2058
2059 if (NonVirtualBaseAdjustment) {
2060 // Apply the adjustment and cast back to the original struct type.
2061 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2062 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2063 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2064 }
2065
2066 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2067}
2068
Charles Davis53c59df2010-08-16 03:33:14 +00002069CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00002070 return new MicrosoftCXXABI(CGM);
2071}