blob: 4a02d4da51a966730acbe2fa4cde1184ef88c628 [file] [log] [blame]
Charles Davis74ce8592010-06-09 23:25:41 +00001//===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner57540c52011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davis74ce8592010-06-09 23:25:41 +000011// The class in this file generates structures that follow the Microsoft
12// Visual C++ ABI, which is actually not very well documented at all outside
13// of Microsoft.
14//
15//===----------------------------------------------------------------------===//
16
17#include "CGCXXABI.h"
18#include "CodeGenModule.h"
Reid Kleckner7810af02013-06-19 15:20:38 +000019#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
Charles Davis74ce8592010-06-09 23:25:41 +000021#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000023#include "clang/AST/VTableBuilder.h"
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000024#include "llvm/ADT/StringSet.h"
Charles Davis74ce8592010-06-09 23:25:41 +000025
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30
Charles Davis53c59df2010-08-16 03:33:14 +000031class MicrosoftCXXABI : public CGCXXABI {
Charles Davis74ce8592010-06-09 23:25:41 +000032public:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall5d865c322010-08-31 07:33:07 +000034
Stephen Lin9dc6eef2013-06-30 20:40:16 +000035 bool HasThisReturn(GlobalDecl GD) const;
36
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000037 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
38 // Structures that are not C++03 PODs are always indirect.
39 return !RD->isPOD();
40 }
41
42 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000043 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000044 return RAA_DirectInMemory;
45 return RAA_Default;
46 }
47
Joao Matos2ce88ef2012-07-17 17:10:11 +000048 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikieeb7d5982012-10-16 22:56:05 +000049 // No known support for deleted functions in MSVC yet, so this choice is
50 // arbitrary.
51 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos2ce88ef2012-07-17 17:10:11 +000052
John McCall82fb8922012-09-25 10:10:39 +000053 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
54 llvm::Value *ptr,
55 QualType type);
56
Reid Klecknerd8cbeec2013-05-29 18:02:47 +000057 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
58 llvm::Value *This,
59 const CXXRecordDecl *ClassDecl,
60 const CXXRecordDecl *BaseClassDecl);
61
John McCall5d865c322010-08-31 07:33:07 +000062 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
63 CXXCtorType Type,
64 CanQualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +000065 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +000066
Reid Kleckner7810af02013-06-19 15:20:38 +000067 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
68 const CXXRecordDecl *RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000069
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +000070 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
71 const CXXRecordDecl *RD);
72
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +000073 void EmitCXXConstructors(const CXXConstructorDecl *D);
74
Reid Klecknere7de47e2013-07-22 13:51:44 +000075 // Background on MSVC destructors
76 // ==============================
77 //
78 // Both Itanium and MSVC ABIs have destructor variants. The variant names
79 // roughly correspond in the following way:
80 // Itanium Microsoft
81 // Base -> no name, just ~Class
82 // Complete -> vbase destructor
83 // Deleting -> scalar deleting destructor
84 // vector deleting destructor
85 //
86 // The base and complete destructors are the same as in Itanium, although the
87 // complete destructor does not accept a VTT parameter when there are virtual
88 // bases. A separate mechanism involving vtordisps is used to ensure that
89 // virtual methods of destroyed subobjects are not called.
90 //
91 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
92 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
93 // pointer points to an array. The scalar deleting destructor assumes that
94 // bit 2 is zero, and therefore does not contain a loop.
95 //
96 // For virtual destructors, only one entry is reserved in the vftable, and it
97 // always points to the vector deleting destructor. The vector deleting
98 // destructor is the most general, so it can be used to destroy objects in
99 // place, delete single heap objects, or delete arrays.
100 //
101 // A TU defining a non-inline destructor is only guaranteed to emit a base
102 // destructor, and all of the other variants are emitted on an as-needed basis
103 // in COMDATs. Because a non-base destructor can be emitted in a TU that
104 // lacks a definition for the destructor, non-base destructors must always
105 // delegate to or alias the base destructor.
106
107 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
John McCall5d865c322010-08-31 07:33:07 +0000108 CXXDtorType Type,
109 CanQualType &ResTy,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000110 SmallVectorImpl<CanQualType> &ArgTys);
John McCall5d865c322010-08-31 07:33:07 +0000111
Reid Klecknere7de47e2013-07-22 13:51:44 +0000112 /// Non-base dtors should be emitted as delegating thunks in this ABI.
113 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
114 CXXDtorType DT) const {
115 return DT != Dtor_Base;
116 }
117
118 void EmitCXXDestructors(const CXXDestructorDecl *D);
119
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000120 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
121 MD = MD->getCanonicalDecl();
122 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000123 MicrosoftVTableContext::MethodVFTableLocation ML =
124 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000125 // The vbases might be ordered differently in the final overrider object
126 // and the complete object, so the "this" argument may sometimes point to
127 // memory that has no particular type (e.g. past the complete object).
128 // In this case, we just use a generic pointer type.
129 // FIXME: might want to have a more precise type in the non-virtual
130 // multiple inheritance case.
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000131 if (ML.VBase || !ML.VFPtrOffset.isZero())
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000132 return 0;
133 }
134 return MD->getParent();
135 }
136
137 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
138 GlobalDecl GD,
139 llvm::Value *This);
140
John McCall5d865c322010-08-31 07:33:07 +0000141 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
142 QualType &ResTy,
John McCall0f999f32012-09-25 08:00:39 +0000143 FunctionArgList &Params);
John McCall5d865c322010-08-31 07:33:07 +0000144
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000145 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
146 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
147
John McCall0f999f32012-09-25 08:00:39 +0000148 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCall29036752011-01-27 02:46:02 +0000149
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000150 void EmitConstructorCall(CodeGenFunction &CGF,
151 const CXXConstructorDecl *D, CXXCtorType Type,
152 bool ForVirtualBase, bool Delegating,
Stephen Linc467c872013-06-19 18:10:35 +0000153 llvm::Value *This,
154 CallExpr::const_arg_iterator ArgBeg,
155 CallExpr::const_arg_iterator ArgEnd);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000156
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000157 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
158
159 llvm::Value *getVTableAddressPointInStructor(
160 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
161 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
162 bool &NeedsVirtualOffset);
163
164 llvm::Constant *
165 getVTableAddressPointForConstExpr(BaseSubobject Base,
166 const CXXRecordDecl *VTableClass);
167
168 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
169 CharUnits VPtrOffset);
170
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000171 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
172 llvm::Value *This, llvm::Type *Ty);
173
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000174 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
175 const CXXDestructorDecl *Dtor,
176 CXXDtorType DtorType, SourceLocation CallLoc,
177 llvm::Value *This);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000178
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000179 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
180 CallArgList &CallArgs) {
181 assert(GD.getDtorType() == Dtor_Deleting &&
182 "Only deleting destructor thunks are available in this ABI");
183 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
184 CGM.getContext().IntTy);
185 }
186
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000187 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
Reid Kleckner7810af02013-06-19 15:20:38 +0000188
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000189 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
190 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
191 }
192
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000193 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
194 const ThisAdjustment &TA);
195
196 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
197 const ReturnAdjustment &RA);
198
John McCallc84ed6a2012-05-01 06:13:13 +0000199 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
200 llvm::GlobalVariable *DeclPtr,
201 bool PerformInit);
202
John McCall29036752011-01-27 02:46:02 +0000203 // ==== Notes on array cookies =========
204 //
205 // MSVC seems to only use cookies when the class has a destructor; a
206 // two-argument usual array deallocation function isn't sufficient.
207 //
208 // For example, this code prints "100" and "1":
209 // struct A {
210 // char x;
211 // void *operator new[](size_t sz) {
212 // printf("%u\n", sz);
213 // return malloc(sz);
214 // }
215 // void operator delete[](void *p, size_t sz) {
216 // printf("%u\n", sz);
217 // free(p);
218 // }
219 // };
220 // int main() {
221 // A *p = new A[100];
222 // delete[] p;
223 // }
224 // Whereas it prints "104" and "104" if you give A a destructor.
John McCallb91cd662012-05-01 05:23:51 +0000225
226 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
227 bool requiresArrayCookie(const CXXNewExpr *expr);
228 CharUnits getArrayCookieSizeImpl(QualType type);
229 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
230 llvm::Value *NewPtr,
231 llvm::Value *NumElements,
232 const CXXNewExpr *expr,
233 QualType ElementType);
234 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
235 llvm::Value *allocPtr,
236 CharUnits cookieSize);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000237
238private:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000239 MicrosoftMangleContext &getMangleContext() {
240 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
241 }
242
Reid Kleckner2341ae32013-04-11 18:13:19 +0000243 llvm::Constant *getZeroInt() {
244 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000245 }
246
Reid Kleckner2341ae32013-04-11 18:13:19 +0000247 llvm::Constant *getAllOnesInt() {
248 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000249 }
250
Reid Kleckner452abac2013-05-09 21:01:17 +0000251 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
252 return C ? C : getZeroInt();
253 }
254
255 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
256 return C ? C : getZeroInt();
257 }
258
Reid Kleckner2341ae32013-04-11 18:13:19 +0000259 void
260 GetNullMemberPointerFields(const MemberPointerType *MPT,
261 llvm::SmallVectorImpl<llvm::Constant *> &fields);
262
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000263 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
264 /// it is reusing a vbptr from a non-virtual base. RD must have morally
265 /// virtual bases.
266 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
267
268 /// \brief Shared code for virtual base adjustment. Returns the offset from
269 /// the vbptr to the virtual base. Optionally returns the address of the
270 /// vbptr itself.
271 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
272 llvm::Value *Base,
273 llvm::Value *VBPtrOffset,
274 llvm::Value *VBTableOffset,
275 llvm::Value **VBPtr = 0);
276
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000277 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
278 llvm::Value *Base,
279 int32_t VBPtrOffset,
280 int32_t VBTableOffset,
281 llvm::Value **VBPtr = 0) {
282 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
283 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
284 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
285 }
286
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000287 /// \brief Performs a full virtual base adjustment. Used to dereference
288 /// pointers to members of virtual bases.
Reid Kleckner2341ae32013-04-11 18:13:19 +0000289 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
290 llvm::Value *Base,
291 llvm::Value *VirtualBaseAdjustmentOffset,
292 llvm::Value *VBPtrOffset /* optional */);
293
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000294 /// \brief Emits a full member pointer with the fields common to data and
295 /// function member pointers.
296 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
297 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +0000298 const CXXRecordDecl *RD,
299 CharUnits NonVirtualBaseAdjustment);
300
301 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
302 const CXXMethodDecl *MD,
303 CharUnits NonVirtualBaseAdjustment);
304
305 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
306 llvm::Constant *MP);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000307
Reid Kleckner7810af02013-06-19 15:20:38 +0000308 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
309 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
310
311 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
312 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
313
Hans Wennborg88497d62013-11-15 17:24:45 +0000314 /// \brief Generate a thunk for calling a virtual member function MD.
315 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
316 StringRef ThunkName);
317
Reid Kleckner407e8b62013-03-22 19:02:54 +0000318public:
Reid Kleckner2341ae32013-04-11 18:13:19 +0000319 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
320
321 virtual bool isZeroInitializable(const MemberPointerType *MPT);
322
Reid Kleckner407e8b62013-03-22 19:02:54 +0000323 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
324
325 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
326 CharUnits offset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +0000327 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
328 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
Reid Kleckner407e8b62013-03-22 19:02:54 +0000329
Reid Kleckner700c3ee2013-04-30 20:15:14 +0000330 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
331 llvm::Value *L,
332 llvm::Value *R,
333 const MemberPointerType *MPT,
334 bool Inequality);
335
Reid Kleckner407e8b62013-03-22 19:02:54 +0000336 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
337 llvm::Value *MemPtr,
338 const MemberPointerType *MPT);
339
340 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
341 llvm::Value *Base,
342 llvm::Value *MemPtr,
343 const MemberPointerType *MPT);
344
Reid Kleckner452abac2013-05-09 21:01:17 +0000345 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
346 const CastExpr *E,
347 llvm::Value *Src);
348
349 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
350 llvm::Constant *Src);
351
Reid Kleckner2341ae32013-04-11 18:13:19 +0000352 virtual llvm::Value *
353 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
354 llvm::Value *&This,
355 llvm::Value *MemPtr,
356 const MemberPointerType *MPT);
357
Reid Kleckner7810af02013-06-19 15:20:38 +0000358private:
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000359 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
360 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
361 /// \brief All the vftables that have been referenced.
362 VFTablesMapTy VFTablesMap;
363
364 /// \brief This set holds the record decls we've deferred vtable emission for.
365 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
366
367
368 /// \brief All the vbtables which have been referenced.
Reid Kleckner7810af02013-06-19 15:20:38 +0000369 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
Reid Klecknerd8110b62013-09-10 20:14:30 +0000370
371 /// Info on the global variable used to guard initialization of static locals.
372 /// The BitIndex field is only used for externally invisible declarations.
373 struct GuardInfo {
374 GuardInfo() : Guard(0), BitIndex(0) {}
375 llvm::GlobalVariable *Guard;
376 unsigned BitIndex;
377 };
378
379 /// Map from DeclContext to the current guard variable. We assume that the
380 /// AST is visited in source code order.
381 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
Charles Davis74ce8592010-06-09 23:25:41 +0000382};
383
384}
385
John McCall82fb8922012-09-25 10:10:39 +0000386llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
387 llvm::Value *ptr,
388 QualType type) {
389 // FIXME: implement
390 return ptr;
391}
392
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000393/// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
394/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
395static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
396 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
397 E = RD->bases_end(); I != E; ++I) {
398 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
399 if (!I->isVirtual() && Base->getNumVBases() > 0)
400 return Base;
401 }
402 llvm_unreachable("RD must have an nv base with vbases");
403}
404
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000405CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
406 assert(RD->getNumVBases());
407 CharUnits Total = CharUnits::Zero();
408 while (RD) {
409 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
410 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
411 // -1 is the sentinel for no vbptr.
412 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
413 Total += VBPtrOffset;
414 break;
415 }
Reid Kleckner3758f9d2013-06-04 21:32:29 +0000416 RD = FindFirstNVBaseWithVBases(RD);
417 Total += RDLayout.getBaseClassOffset(RD);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000418 }
419 return Total;
420}
421
422llvm::Value *
423MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
424 llvm::Value *This,
425 const CXXRecordDecl *ClassDecl,
426 const CXXRecordDecl *BaseClassDecl) {
427 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
428 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000429 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000430 CharUnits VBTableChars =
431 IntSize *
432 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000433 llvm::Value *VBTableOffset =
434 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
435
436 llvm::Value *VBPtrToNewBase =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +0000437 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000438 VBPtrToNewBase =
439 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
440 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
441}
442
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000443bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
444 return isa<CXXConstructorDecl>(GD.getDecl());
John McCall0f999f32012-09-25 08:00:39 +0000445}
446
447void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
448 CXXCtorType Type,
449 CanQualType &ResTy,
450 SmallVectorImpl<CanQualType> &ArgTys) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000451 // 'this' parameter and 'this' return are already in place
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000452
453 const CXXRecordDecl *Class = Ctor->getParent();
454 if (Class->getNumVBases()) {
455 // Constructors of classes with virtual bases take an implicit parameter.
456 ArgTys.push_back(CGM.getContext().IntTy);
457 }
458}
459
Reid Kleckner7810af02013-06-19 15:20:38 +0000460llvm::BasicBlock *
461MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
462 const CXXRecordDecl *RD) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000463 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
464 assert(IsMostDerivedClass &&
465 "ctor for a class with virtual bases must have an implicit parameter");
Reid Kleckner7810af02013-06-19 15:20:38 +0000466 llvm::Value *IsCompleteObject =
467 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000468
469 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
470 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
471 CGF.Builder.CreateCondBr(IsCompleteObject,
472 CallVbaseCtorsBB, SkipVbaseCtorsBB);
473
474 CGF.EmitBlock(CallVbaseCtorsBB);
Reid Kleckner7810af02013-06-19 15:20:38 +0000475
476 // Fill in the vbtable pointers here.
477 EmitVBPtrStores(CGF, RD);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000478
479 // CGF will put the base ctor calls in this basic block for us later.
480
481 return SkipVbaseCtorsBB;
John McCall0f999f32012-09-25 08:00:39 +0000482}
483
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000484void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
485 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
486 // In most cases, an override for a vbase virtual method can adjust
487 // the "this" parameter by applying a constant offset.
488 // However, this is not enough while a constructor or a destructor of some
489 // class X is being executed if all the following conditions are met:
490 // - X has virtual bases, (1)
491 // - X overrides a virtual method M of a vbase Y, (2)
492 // - X itself is a vbase of the most derived class.
493 //
494 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
495 // which holds the extra amount of "this" adjustment we must do when we use
496 // the X vftables (i.e. during X ctor or dtor).
497 // Outside the ctors and dtors, the values of vtorDisps are zero.
498
499 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
500 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
501 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
502 CGBuilderTy &Builder = CGF.Builder;
503
504 unsigned AS =
505 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
506 llvm::Value *Int8This = 0; // Initialize lazily.
507
508 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
509 I != E; ++I) {
510 if (!I->second.hasVtorDisp())
511 continue;
512
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000513 llvm::Value *VBaseOffset =
514 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +0000515 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
516 // just to Trunc back immediately.
517 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
518 uint64_t ConstantVBaseOffset =
519 Layout.getVBaseClassOffset(I->first).getQuantity();
520
521 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
522 llvm::Value *VtorDispValue = Builder.CreateSub(
523 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
524 "vtordisp.value");
525
526 if (!Int8This)
527 Int8This = Builder.CreateBitCast(getThisValue(CGF),
528 CGF.Int8Ty->getPointerTo(AS));
529 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
530 // vtorDisp is always the 32-bits before the vbase in the class layout.
531 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
532 VtorDispPtr = Builder.CreateBitCast(
533 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
534
535 Builder.CreateStore(VtorDispValue, VtorDispPtr);
536 }
537}
538
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +0000539void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
540 // There's only one constructor type in this ABI.
541 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
542}
543
Reid Kleckner7810af02013-06-19 15:20:38 +0000544void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
545 const CXXRecordDecl *RD) {
546 llvm::Value *ThisInt8Ptr =
547 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
548
549 const VBTableVector &VBTables = EnumerateVBTables(RD);
550 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
551 I != E; ++I) {
552 const ASTRecordLayout &SubobjectLayout =
553 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
554 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
555 SubobjectLayout.getVBPtrOffset()).getQuantity();
556 llvm::Value *VBPtr =
557 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
558 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
559 "vbptr." + I->ReusingBase->getName());
560 CGF.Builder.CreateStore(I->GV, VBPtr);
561 }
562}
563
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000564void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
565 CXXDtorType Type,
566 CanQualType &ResTy,
567 SmallVectorImpl<CanQualType> &ArgTys) {
568 // 'this' is already in place
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000569
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000570 // TODO: 'for base' flag
571
572 if (Type == Dtor_Deleting) {
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000573 // The scalar deleting destructor takes an implicit int parameter.
574 ArgTys.push_back(CGM.getContext().IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000575 }
576}
577
Reid Klecknere7de47e2013-07-22 13:51:44 +0000578void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
579 // The TU defining a dtor is only guaranteed to emit a base destructor. All
580 // other destructor variants are delegating thunks.
581 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
582}
583
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000584llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
585 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
586 GD = GD.getCanonicalDecl();
587 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000588 // FIXME: consider splitting the vdtor vs regular method code into two
589 // functions.
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000590
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000591 GlobalDecl LookupGD = GD;
592 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
593 // Complete dtors take a pointer to the complete object,
594 // thus don't need adjustment.
595 if (GD.getDtorType() == Dtor_Complete)
596 return This;
597
598 // There's only Dtor_Deleting in vftable but it shares the this adjustment
599 // with the base one, so look up the deleting one instead.
600 LookupGD = GlobalDecl(DD, Dtor_Deleting);
601 }
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000602 MicrosoftVTableContext::MethodVFTableLocation ML =
603 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000604
605 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
606 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000607 CharUnits StaticOffset = ML.VFPtrOffset;
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000608 if (ML.VBase) {
609 bool AvoidVirtualOffset = false;
610 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
611 // A base destructor can only be called from a complete destructor of the
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000612 // same record type or another destructor of a more derived type;
613 // or a constructor of the same record type if an exception is thrown.
614 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
615 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000616 const CXXRecordDecl *CurRD =
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000617 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000618
619 if (MD->getParent() == CurRD) {
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000620 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
621 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
622 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
623 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
624 // We're calling the main base dtor from a complete structor,
625 // so we know the "this" offset statically.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000626 AvoidVirtualOffset = true;
627 } else {
628 // Let's see if we try to call a destructor of a non-virtual base.
629 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
630 E = CurRD->bases_end(); I != E; ++I) {
631 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
632 continue;
633 // If we call a base destructor for a non-virtual base, we statically
634 // know where it expects the vfptr and "this" to be.
Timur Iskhodzhanov406a4792013-10-17 09:11:45 +0000635 // The total offset should reflect the adjustment done by
636 // adjustThisParameterInVirtualFunctionPrologue().
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000637 AvoidVirtualOffset = true;
638 break;
639 }
640 }
641 }
642
643 if (AvoidVirtualOffset) {
644 const ASTRecordLayout &Layout =
645 CGF.getContext().getASTRecordLayout(MD->getParent());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000646 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
647 } else {
648 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov4ddf5922013-11-13 16:03:43 +0000649 llvm::Value *VBaseOffset =
650 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000651 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
652 }
653 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000654 if (!StaticOffset.isZero()) {
655 assert(StaticOffset.isPositive());
656 This = CGF.Builder.CreateBitCast(This, charPtrTy);
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000657 if (ML.VBase) {
658 // Non-virtual adjustment might result in a pointer outside the allocated
659 // object, e.g. if the final overrider class is laid out after the virtual
660 // base that declares a method in the most derived class.
661 // FIXME: Update the code that emits this adjustment in thunks prologues.
662 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
663 } else {
664 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
665 StaticOffset.getQuantity());
666 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000667 }
668 return This;
669}
670
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000671static bool IsDeletingDtor(GlobalDecl GD) {
672 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
673 if (isa<CXXDestructorDecl>(MD)) {
674 return GD.getDtorType() == Dtor_Deleting;
675 }
676 return false;
677}
678
John McCall0f999f32012-09-25 08:00:39 +0000679void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
680 QualType &ResTy,
681 FunctionArgList &Params) {
682 BuildThisParam(CGF, Params);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000683
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000684 ASTContext &Context = getContext();
685 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
686 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
687 ImplicitParamDecl *IsMostDerived
688 = ImplicitParamDecl::Create(Context, 0,
689 CGF.CurGD.getDecl()->getLocation(),
690 &Context.Idents.get("is_most_derived"),
691 Context.IntTy);
692 Params.push_back(IsMostDerived);
693 getStructorImplicitParamDecl(CGF) = IsMostDerived;
694 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000695 ImplicitParamDecl *ShouldDelete
696 = ImplicitParamDecl::Create(Context, 0,
697 CGF.CurGD.getDecl()->getLocation(),
698 &Context.Idents.get("should_call_delete"),
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000699 Context.IntTy);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000700 Params.push_back(ShouldDelete);
701 getStructorImplicitParamDecl(CGF) = ShouldDelete;
702 }
John McCall0f999f32012-09-25 08:00:39 +0000703}
704
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000705llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
706 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
707 GD = GD.getCanonicalDecl();
708 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000709
710 GlobalDecl LookupGD = GD;
711 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
712 // Complete destructors take a pointer to the complete object as a
713 // parameter, thus don't need this adjustment.
714 if (GD.getDtorType() == Dtor_Complete)
715 return This;
716
717 // There's no Dtor_Base in vftable but it shares the this adjustment with
718 // the deleting one, so look it up instead.
719 LookupGD = GlobalDecl(DD, Dtor_Deleting);
720 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000721
722 // In this ABI, every virtual function takes a pointer to one of the
723 // subobjects that first defines it as the 'this' parameter, rather than a
724 // pointer to ther final overrider subobject. Thus, we need to adjust it back
725 // to the final overrider subobject before use.
726 // See comments in the MicrosoftVFTableContext implementation for the details.
727
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000728 MicrosoftVTableContext::MethodVFTableLocation ML =
729 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
Timur Iskhodzhanov9e7f5052013-11-07 13:34:02 +0000730 CharUnits Adjustment = ML.VFPtrOffset;
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000731 if (ML.VBase) {
732 const ASTRecordLayout &DerivedLayout =
733 CGF.getContext().getASTRecordLayout(MD->getParent());
734 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
735 }
736
737 if (Adjustment.isZero())
738 return This;
739
740 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
741 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
742 *thisTy = This->getType();
743
744 This = CGF.Builder.CreateBitCast(This, charPtrTy);
745 assert(Adjustment.isPositive());
Timur Iskhodzhanov827365e2013-10-22 18:15:24 +0000746 This =
747 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000748 return CGF.Builder.CreateBitCast(This, thisTy);
749}
750
John McCall0f999f32012-09-25 08:00:39 +0000751void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
752 EmitThisParam(CGF);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000753
754 /// If this is a function that the ABI specifies returns 'this', initialize
755 /// the return slot to 'this' at the start of the function.
756 ///
757 /// Unlike the setting of return types, this is done within the ABI
758 /// implementation instead of by clients of CGCXXABI because:
759 /// 1) getThisValue is currently protected
760 /// 2) in theory, an ABI could implement 'this' returns some other way;
761 /// HasThisReturn only specifies a contract, not the implementation
762 if (HasThisReturn(CGF.CurGD))
John McCall0f999f32012-09-25 08:00:39 +0000763 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000764
765 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
766 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
767 assert(getStructorImplicitParamDecl(CGF) &&
768 "no implicit parameter for a constructor with virtual bases?");
769 getStructorImplicitParamValue(CGF)
770 = CGF.Builder.CreateLoad(
771 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
772 "is_most_derived");
773 }
774
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000775 if (IsDeletingDtor(CGF.CurGD)) {
776 assert(getStructorImplicitParamDecl(CGF) &&
777 "no implicit parameter for a deleting destructor?");
778 getStructorImplicitParamValue(CGF)
779 = CGF.Builder.CreateLoad(
780 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
781 "should_call_delete");
782 }
John McCall0f999f32012-09-25 08:00:39 +0000783}
784
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000785void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Stephen Linc467c872013-06-19 18:10:35 +0000786 const CXXConstructorDecl *D,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000787 CXXCtorType Type,
788 bool ForVirtualBase,
Stephen Linc467c872013-06-19 18:10:35 +0000789 bool Delegating,
790 llvm::Value *This,
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000791 CallExpr::const_arg_iterator ArgBeg,
792 CallExpr::const_arg_iterator ArgEnd) {
793 assert(Type == Ctor_Complete || Type == Ctor_Base);
794 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
795
796 llvm::Value *ImplicitParam = 0;
797 QualType ImplicitParamTy;
798 if (D->getParent()->getNumVBases()) {
799 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
800 ImplicitParamTy = getContext().IntTy;
801 }
802
803 // FIXME: Provide a source location here.
Stephen Linc467c872013-06-19 18:10:35 +0000804 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000805 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000806}
807
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000808void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
809 const CXXRecordDecl *RD) {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000810 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
811 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000812 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
813
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000814 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000815 E = VFPtrs.end(); I != E; ++I) {
816 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
817 if (VTable->hasInitializer())
818 continue;
819
820 const VTableLayout &VTLayout =
821 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
822 llvm::Constant *Init = CGVT.CreateVTableInitializer(
823 RD, VTLayout.vtable_component_begin(),
824 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
825 VTLayout.getNumVTableThunks());
826 VTable->setInitializer(Init);
827
828 VTable->setLinkage(Linkage);
829 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
830 }
831}
832
833llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
834 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
835 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
836 NeedsVirtualOffset = (NearestVBase != 0);
837
838 llvm::Value *VTableAddressPoint =
839 getAddrOfVTable(VTableClass, Base.getBaseOffset());
840 if (!VTableAddressPoint) {
841 assert(Base.getBase()->getNumVBases() &&
842 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
843 }
844 return VTableAddressPoint;
845}
846
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000847static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
848 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
849 SmallString<256> &Name) {
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000850 llvm::raw_svector_ostream Out(Name);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000851 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000852}
853
854llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
855 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
856 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
857 assert(VTable && "Couldn't find a vftable for the given base?");
858 return VTable;
859}
860
861llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
862 CharUnits VPtrOffset) {
863 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
864 // shouldn't be used in the given record type. We want to cache this result in
865 // VFTablesMap, thus a simple zero check is not sufficient.
866 VFTableIdTy ID(RD, VPtrOffset);
867 VFTablesMapTy::iterator I;
868 bool Inserted;
869 llvm::tie(I, Inserted) = VFTablesMap.insert(
870 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
871 if (!Inserted)
872 return I->second;
873
874 llvm::GlobalVariable *&VTable = I->second;
875
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000876 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
877 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
878 VTContext.getVFPtrOffsets(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000879
880 if (DeferredVFTables.insert(RD)) {
881 // We haven't processed this record type before.
882 // Queue up this v-table for possible deferred emission.
883 CGM.addDeferredVTable(RD);
884
885#ifndef NDEBUG
886 // Create all the vftables at once in order to make sure each vftable has
887 // a unique mangled name.
888 llvm::StringSet<> ObservedMangledNames;
889 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
890 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000891 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000892 if (!ObservedMangledNames.insert(Name.str()))
893 llvm_unreachable("Already saw this mangling before?");
894 }
895#endif
896 }
897
898 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
899 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
900 continue;
901
902 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
903 CGM.Int8PtrTy,
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000904 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000905 .getNumVTableComponents());
906
907 SmallString<256> Name;
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000908 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000909 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
910 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
911 VTable->setUnnamedAddr(true);
912 break;
913 }
914
915 return VTable;
916}
917
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000918llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
919 GlobalDecl GD,
920 llvm::Value *This,
921 llvm::Type *Ty) {
922 GD = GD.getCanonicalDecl();
923 CGBuilderTy &Builder = CGF.Builder;
924
925 Ty = Ty->getPointerTo()->getPointerTo();
926 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
927 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
928
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000929 MicrosoftVTableContext::MethodVFTableLocation ML =
930 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000931 llvm::Value *VFuncPtr =
932 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
933 return Builder.CreateLoad(VFuncPtr);
934}
935
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000936void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
937 const CXXDestructorDecl *Dtor,
938 CXXDtorType DtorType,
939 SourceLocation CallLoc,
940 llvm::Value *This) {
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000941 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
942
943 // We have only one destructor in the vftable but can get both behaviors
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000944 // by passing an implicit int parameter.
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000945 GlobalDecl GD(Dtor, Dtor_Deleting);
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000946 const CGFunctionInfo *FInfo =
947 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000948 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000949 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000950
951 ASTContext &Context = CGF.getContext();
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000952 llvm::Value *ImplicitParam =
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000953 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000954 DtorType == Dtor_Deleting);
955
Timur Iskhodzhanov62082b72013-10-16 18:24:06 +0000956 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000957 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov701981f2013-08-27 10:38:19 +0000958 ImplicitParam, Context.IntTy, 0, 0);
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +0000959}
960
Reid Kleckner7810af02013-06-19 15:20:38 +0000961const VBTableVector &
962MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
963 // At this layer, we can key the cache off of a single class, which is much
964 // easier than caching at the GlobalVariable layer.
965 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
966 bool added;
967 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
968 VBTableVector &VBTables = I->second;
969 if (!added)
970 return VBTables;
971
972 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
973
974 return VBTables;
975}
976
Hans Wennborg88497d62013-11-15 17:24:45 +0000977llvm::Function *
978MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
979 StringRef ThunkName) {
980 // If the thunk has been generated previously, just return it.
981 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
982 return cast<llvm::Function>(GV);
983
984 // Create the llvm::Function.
985 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
986 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
987 llvm::Function *ThunkFn =
988 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
989 ThunkName.str(), &CGM.getModule());
990 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
991
Hans Wennborg88497d62013-11-15 17:24:45 +0000992 ThunkFn->setLinkage(MD->isExternallyVisible()
993 ? llvm::GlobalValue::LinkOnceODRLinkage
994 : llvm::GlobalValue::InternalLinkage);
995
996 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
997 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
998
999 // Start codegen.
1000 CodeGenFunction CGF(CGM);
1001 CGF.StartThunk(ThunkFn, MD, FnInfo);
1002
1003 // Get to the Callee.
1004 llvm::Value *This = CGF.LoadCXXThis();
1005 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1006
1007 // Make the call and return the result.
1008 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1009
1010 return ThunkFn;
1011}
1012
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001013void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
Reid Kleckner7810af02013-06-19 15:20:38 +00001014 const VBTableVector &VBTables = EnumerateVBTables(RD);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001015 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1016
Reid Kleckner7810af02013-06-19 15:20:38 +00001017 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
1018 I != E; ++I) {
1019 I->EmitVBTableDefinition(CGM, RD, Linkage);
1020 }
1021}
1022
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001023llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1024 llvm::Value *This,
1025 const ThisAdjustment &TA) {
1026 if (TA.isEmpty())
1027 return This;
1028
1029 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1030
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00001031 if (!TA.Virtual.isEmpty()) {
1032 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1033 // Adjust the this argument based on the vtordisp value.
1034 llvm::Value *VtorDispPtr =
1035 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1036 VtorDispPtr =
1037 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1038 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1039 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1040
1041 if (TA.Virtual.Microsoft.VBPtrOffset) {
1042 // If the final overrider is defined in a virtual base other than the one
1043 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1044 // the vbtable of the derived class.
1045 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1046 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1047 llvm::Value *VBPtr;
1048 llvm::Value *VBaseOffset =
1049 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1050 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1051 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1052 }
1053 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00001054
1055 if (TA.NonVirtual) {
1056 // Non-virtual adjustment might result in a pointer outside the allocated
1057 // object, e.g. if the final overrider class is laid out after the virtual
1058 // base that declares a method in the most derived class.
1059 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1060 }
1061
1062 // Don't need to bitcast back, the call CodeGen will handle this.
1063 return V;
1064}
1065
1066llvm::Value *
1067MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1068 const ReturnAdjustment &RA) {
1069 if (RA.isEmpty())
1070 return Ret;
1071
1072 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1073
1074 if (RA.Virtual.Microsoft.VBIndex) {
1075 assert(RA.Virtual.Microsoft.VBIndex > 0);
1076 int32_t IntSize =
1077 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1078 llvm::Value *VBPtr;
1079 llvm::Value *VBaseOffset =
1080 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1081 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1082 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1083 }
1084
1085 if (RA.NonVirtual)
1086 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1087
1088 // Cast back to the original type.
1089 return CGF.Builder.CreateBitCast(V, Ret->getType());
1090}
1091
John McCallb91cd662012-05-01 05:23:51 +00001092bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1093 QualType elementType) {
1094 // Microsoft seems to completely ignore the possibility of a
1095 // two-argument usual deallocation function.
1096 return elementType.isDestructedType();
1097}
1098
1099bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1100 // Microsoft seems to completely ignore the possibility of a
1101 // two-argument usual deallocation function.
1102 return expr->getAllocatedType().isDestructedType();
1103}
1104
1105CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1106 // The array cookie is always a size_t; we then pad that out to the
1107 // alignment of the element type.
1108 ASTContext &Ctx = getContext();
1109 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1110 Ctx.getTypeAlignInChars(type));
1111}
1112
1113llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1114 llvm::Value *allocPtr,
1115 CharUnits cookieSize) {
Micah Villmowea2fea22012-10-25 15:39:14 +00001116 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001117 llvm::Value *numElementsPtr =
1118 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1119 return CGF.Builder.CreateLoad(numElementsPtr);
1120}
1121
1122llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1123 llvm::Value *newPtr,
1124 llvm::Value *numElements,
1125 const CXXNewExpr *expr,
1126 QualType elementType) {
1127 assert(requiresArrayCookie(expr));
1128
1129 // The size of the cookie.
1130 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1131
1132 // Compute an offset to the cookie.
1133 llvm::Value *cookiePtr = newPtr;
1134
1135 // Write the number of elements into the appropriate slot.
Micah Villmowea2fea22012-10-25 15:39:14 +00001136 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCallb91cd662012-05-01 05:23:51 +00001137 llvm::Value *numElementsPtr
1138 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1139 CGF.Builder.CreateStore(numElements, numElementsPtr);
1140
1141 // Finally, compute a pointer to the actual data buffer by skipping
1142 // over the cookie completely.
1143 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1144 cookieSize.getQuantity());
1145}
1146
John McCallc84ed6a2012-05-01 06:13:13 +00001147void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
Reid Klecknerd8110b62013-09-10 20:14:30 +00001148 llvm::GlobalVariable *GV,
John McCallc84ed6a2012-05-01 06:13:13 +00001149 bool PerformInit) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00001150 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1151 // threadsafe. Since the user may be linking in inline functions compiled by
1152 // cl.exe, there's no reason to provide a false sense of security by using
1153 // critical sections here.
John McCallc84ed6a2012-05-01 06:13:13 +00001154
Richard Smithdbf74ba2013-04-14 23:01:42 +00001155 if (D.getTLSKind())
1156 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1157
Reid Klecknerd8110b62013-09-10 20:14:30 +00001158 CGBuilderTy &Builder = CGF.Builder;
1159 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1160 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1161
1162 // Get the guard variable for this function if we have one already.
1163 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1164
1165 unsigned BitIndex;
1166 if (D.isExternallyVisible()) {
1167 // Externally visible variables have to be numbered in Sema to properly
1168 // handle unreachable VarDecls.
1169 BitIndex = getContext().getManglingNumber(&D);
1170 assert(BitIndex > 0);
1171 BitIndex--;
1172 } else {
1173 // Non-externally visible variables are numbered here in CodeGen.
1174 BitIndex = GI.BitIndex++;
1175 }
1176
1177 if (BitIndex >= 32) {
1178 if (D.isExternallyVisible())
1179 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1180 BitIndex %= 32;
1181 GI.Guard = 0;
1182 }
1183
1184 // Lazily create the i32 bitfield for this function.
1185 if (!GI.Guard) {
1186 // Mangle the name for the guard.
1187 SmallString<256> GuardName;
1188 {
1189 llvm::raw_svector_ostream Out(GuardName);
1190 getMangleContext().mangleStaticGuardVariable(&D, Out);
1191 Out.flush();
1192 }
1193
1194 // Create the guard variable with a zero-initializer. Just absorb linkage
1195 // and visibility from the guarded variable.
1196 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1197 GV->getLinkage(), Zero, GuardName.str());
1198 GI.Guard->setVisibility(GV->getVisibility());
1199 } else {
1200 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1201 "static local from the same function had different linkage");
1202 }
1203
1204 // Pseudo code for the test:
1205 // if (!(GuardVar & MyGuardBit)) {
1206 // GuardVar |= MyGuardBit;
1207 // ... initialize the object ...;
1208 // }
1209
1210 // Test our bit from the guard variable.
1211 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1212 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1213 llvm::Value *IsInitialized =
1214 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1215 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1216 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1217 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1218
1219 // Set our bit in the guard variable and emit the initializer and add a global
1220 // destructor if appropriate.
1221 CGF.EmitBlock(InitBlock);
1222 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1223 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1224 Builder.CreateBr(EndBlock);
1225
1226 // Continue.
1227 CGF.EmitBlock(EndBlock);
John McCallc84ed6a2012-05-01 06:13:13 +00001228}
1229
Reid Kleckner2341ae32013-04-11 18:13:19 +00001230// Member pointer helpers.
1231static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1232 return Inheritance == MSIM_Unspecified;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001233}
1234
Reid Kleckner452abac2013-05-09 21:01:17 +00001235static bool hasOnlyOneField(bool IsMemberFunction,
1236 MSInheritanceModel Inheritance) {
1237 return Inheritance <= MSIM_SinglePolymorphic ||
1238 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001239}
1240
Reid Kleckner2341ae32013-04-11 18:13:19 +00001241// Only member pointers to functions need a this adjustment, since it can be
1242// combined with the field offset for data pointers.
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001243static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001244 MSInheritanceModel Inheritance) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001245 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001246}
1247
1248static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1249 return Inheritance >= MSIM_Virtual;
1250}
1251
1252// Use zero for the field offset of a null data member pointer if we can
1253// guarantee that zero is not a valid field offset, or if the member pointer has
1254// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1255// use zero for null. If there are multiple fields, we can use zero even if it
1256// is a valid field offset because null-ness testing will check the other
1257// fields.
1258static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1259 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1260}
1261
1262bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1263 // Null-ness for function memptrs only depends on the first field, which is
1264 // the function pointer. The rest don't matter, so we can zero initialize.
1265 if (MPT->isMemberFunctionPointer())
1266 return true;
1267
1268 // The virtual base adjustment field is always -1 for null, so if we have one
1269 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1270 // valid field offset.
1271 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1272 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1273 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1274 nullFieldOffsetIsZero(Inheritance));
1275}
1276
1277llvm::Type *
1278MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1279 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1280 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1281 llvm::SmallVector<llvm::Type *, 4> fields;
1282 if (MPT->isMemberFunctionPointer())
1283 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1284 else
1285 fields.push_back(CGM.IntTy); // FieldOffset
1286
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001287 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1288 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001289 fields.push_back(CGM.IntTy);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001290 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001291 fields.push_back(CGM.IntTy);
1292 if (hasVirtualBaseAdjustmentField(Inheritance))
1293 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1294
1295 if (fields.size() == 1)
1296 return fields[0];
1297 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1298}
1299
1300void MicrosoftCXXABI::
1301GetNullMemberPointerFields(const MemberPointerType *MPT,
1302 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1303 assert(fields.empty());
1304 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1305 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1306 if (MPT->isMemberFunctionPointer()) {
1307 // FunctionPointerOrVirtualThunk
1308 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1309 } else {
1310 if (nullFieldOffsetIsZero(Inheritance))
1311 fields.push_back(getZeroInt()); // FieldOffset
1312 else
1313 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Kleckner407e8b62013-03-22 19:02:54 +00001314 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001315
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001316 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1317 Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001318 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001319 if (hasVBPtrOffsetField(Inheritance))
Reid Kleckner2341ae32013-04-11 18:13:19 +00001320 fields.push_back(getZeroInt());
1321 if (hasVirtualBaseAdjustmentField(Inheritance))
1322 fields.push_back(getAllOnesInt());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001323}
1324
1325llvm::Constant *
1326MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001327 llvm::SmallVector<llvm::Constant *, 4> fields;
1328 GetNullMemberPointerFields(MPT, fields);
1329 if (fields.size() == 1)
1330 return fields[0];
1331 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1332 assert(Res->getType() == ConvertMemberPointerType(MPT));
1333 return Res;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001334}
1335
1336llvm::Constant *
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001337MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1338 bool IsMemberFunction,
Reid Kleckner452abac2013-05-09 21:01:17 +00001339 const CXXRecordDecl *RD,
1340 CharUnits NonVirtualBaseAdjustment)
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001341{
Reid Kleckner2341ae32013-04-11 18:13:19 +00001342 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001343
1344 // Single inheritance class member pointer are represented as scalars instead
1345 // of aggregates.
Reid Kleckner452abac2013-05-09 21:01:17 +00001346 if (hasOnlyOneField(IsMemberFunction, Inheritance))
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001347 return FirstField;
1348
Reid Kleckner2341ae32013-04-11 18:13:19 +00001349 llvm::SmallVector<llvm::Constant *, 4> fields;
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001350 fields.push_back(FirstField);
1351
1352 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
Reid Kleckner452abac2013-05-09 21:01:17 +00001353 fields.push_back(llvm::ConstantInt::get(
1354 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001355
Reid Kleckner2341ae32013-04-11 18:13:19 +00001356 if (hasVBPtrOffsetField(Inheritance)) {
Reid Kleckneraec44092013-10-15 01:18:02 +00001357 CharUnits Offs = CharUnits::Zero();
1358 if (RD->getNumVBases())
1359 Offs = GetVBPtrOffsetFromBases(RD);
1360 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
Reid Kleckner2341ae32013-04-11 18:13:19 +00001361 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001362
1363 // The rest of the fields are adjusted by conversions to a more derived class.
Reid Kleckner2341ae32013-04-11 18:13:19 +00001364 if (hasVirtualBaseAdjustmentField(Inheritance))
1365 fields.push_back(getZeroInt());
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001366
Reid Kleckner2341ae32013-04-11 18:13:19 +00001367 return llvm::ConstantStruct::getAnon(fields);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001368}
1369
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001370llvm::Constant *
1371MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1372 CharUnits offset) {
1373 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1374 llvm::Constant *FirstField =
1375 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
Reid Kleckner452abac2013-05-09 21:01:17 +00001376 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1377 CharUnits::Zero());
1378}
1379
1380llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1381 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1382}
1383
1384llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1385 QualType MPType) {
1386 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1387 const ValueDecl *MPD = MP.getMemberPointerDecl();
1388 if (!MPD)
1389 return EmitNullMemberPointer(MPT);
1390
1391 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1392
1393 // FIXME PR15713: Support virtual inheritance paths.
1394
1395 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1396 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1397 MD, ThisAdjustment);
1398
1399 CharUnits FieldOffset =
1400 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1401 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001402}
1403
1404llvm::Constant *
Reid Kleckner452abac2013-05-09 21:01:17 +00001405MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1406 const CXXMethodDecl *MD,
1407 CharUnits NonVirtualBaseAdjustment) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001408 assert(MD->isInstance() && "Member function must not be static!");
1409 MD = MD->getCanonicalDecl();
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001410 CodeGenTypes &Types = CGM.getTypes();
1411
1412 llvm::Constant *FirstField;
Hans Wennborg88497d62013-11-15 17:24:45 +00001413 if (!MD->isVirtual()) {
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001414 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1415 llvm::Type *Ty;
1416 // Check whether the function has a computable LLVM signature.
1417 if (Types.isFuncTypeConvertible(FPT)) {
1418 // The function has a computable LLVM signature; use the correct type.
1419 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1420 } else {
1421 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1422 // function type is incomplete.
1423 Ty = CGM.PtrDiffTy;
1424 }
1425 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1426 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
Hans Wennborg88497d62013-11-15 17:24:45 +00001427 } else {
1428 MicrosoftVTableContext::MethodVFTableLocation ML =
1429 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1430 if (MD->isVariadic()) {
1431 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1432 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1433 } else if (!CGM.getTypes().isFuncTypeConvertible(
1434 MD->getType()->castAs<FunctionType>())) {
1435 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1436 "incomplete return or parameter type");
1437 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1438 } else if (ML.VBase) {
1439 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1440 "member function in virtual base class");
1441 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1442 } else {
1443 SmallString<256> ThunkName;
1444 int OffsetInVFTable =
1445 ML.Index *
1446 getContext().getTypeSizeInChars(getContext().VoidPtrTy).getQuantity();
1447 llvm::raw_svector_ostream Out(ThunkName);
1448 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1449 Out.flush();
1450
1451 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1452 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1453 }
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001454 }
1455
1456 // The rest of the fields are common with data member pointers.
Reid Kleckner452abac2013-05-09 21:01:17 +00001457 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1458 NonVirtualBaseAdjustment);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001459}
1460
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001461/// Member pointers are the same if they're either bitwise identical *or* both
1462/// null. Null-ness for function members is determined by the first field,
1463/// while for data member pointers we must compare all fields.
1464llvm::Value *
1465MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1466 llvm::Value *L,
1467 llvm::Value *R,
1468 const MemberPointerType *MPT,
1469 bool Inequality) {
1470 CGBuilderTy &Builder = CGF.Builder;
1471
1472 // Handle != comparisons by switching the sense of all boolean operations.
1473 llvm::ICmpInst::Predicate Eq;
1474 llvm::Instruction::BinaryOps And, Or;
1475 if (Inequality) {
1476 Eq = llvm::ICmpInst::ICMP_NE;
1477 And = llvm::Instruction::Or;
1478 Or = llvm::Instruction::And;
1479 } else {
1480 Eq = llvm::ICmpInst::ICMP_EQ;
1481 And = llvm::Instruction::And;
1482 Or = llvm::Instruction::Or;
1483 }
1484
1485 // If this is a single field member pointer (single inheritance), this is a
1486 // single icmp.
1487 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1488 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner452abac2013-05-09 21:01:17 +00001489 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
Reid Kleckner700c3ee2013-04-30 20:15:14 +00001490 return Builder.CreateICmp(Eq, L, R);
1491
1492 // Compare the first field.
1493 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1494 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1495 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1496
1497 // Compare everything other than the first field.
1498 llvm::Value *Res = 0;
1499 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1500 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1501 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1502 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1503 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1504 if (Res)
1505 Res = Builder.CreateBinOp(And, Res, Cmp);
1506 else
1507 Res = Cmp;
1508 }
1509
1510 // Check if the first field is 0 if this is a function pointer.
1511 if (MPT->isMemberFunctionPointer()) {
1512 // (l1 == r1 && ...) || l0 == 0
1513 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1514 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1515 Res = Builder.CreateBinOp(Or, Res, IsZero);
1516 }
1517
1518 // Combine the comparison of the first field, which must always be true for
1519 // this comparison to succeeed.
1520 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1521}
1522
Reid Kleckner407e8b62013-03-22 19:02:54 +00001523llvm::Value *
1524MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1525 llvm::Value *MemPtr,
1526 const MemberPointerType *MPT) {
1527 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001528 llvm::SmallVector<llvm::Constant *, 4> fields;
1529 // We only need one field for member functions.
1530 if (MPT->isMemberFunctionPointer())
1531 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1532 else
1533 GetNullMemberPointerFields(MPT, fields);
1534 assert(!fields.empty());
1535 llvm::Value *FirstField = MemPtr;
1536 if (MemPtr->getType()->isStructTy())
1537 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1538 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001539
Reid Kleckner2341ae32013-04-11 18:13:19 +00001540 // For function member pointers, we only need to test the function pointer
1541 // field. The other fields if any can be garbage.
1542 if (MPT->isMemberFunctionPointer())
1543 return Res;
1544
1545 // Otherwise, emit a series of compares and combine the results.
1546 for (int I = 1, E = fields.size(); I < E; ++I) {
1547 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1548 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1549 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1550 }
1551 return Res;
1552}
1553
Reid Kleckner452abac2013-05-09 21:01:17 +00001554bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1555 llvm::Constant *Val) {
1556 // Function pointers are null if the pointer in the first field is null.
1557 if (MPT->isMemberFunctionPointer()) {
1558 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1559 Val->getAggregateElement(0U) : Val;
1560 return FirstField->isNullValue();
1561 }
1562
1563 // If it's not a function pointer and it's zero initializable, we can easily
1564 // check zero.
1565 if (isZeroInitializable(MPT) && Val->isNullValue())
1566 return true;
1567
1568 // Otherwise, break down all the fields for comparison. Hopefully these
1569 // little Constants are reused, while a big null struct might not be.
1570 llvm::SmallVector<llvm::Constant *, 4> Fields;
1571 GetNullMemberPointerFields(MPT, Fields);
1572 if (Fields.size() == 1) {
1573 assert(Val->getType()->isIntegerTy());
1574 return Val == Fields[0];
1575 }
1576
1577 unsigned I, E;
1578 for (I = 0, E = Fields.size(); I != E; ++I) {
1579 if (Val->getAggregateElement(I) != Fields[I])
1580 break;
1581 }
1582 return I == E;
1583}
1584
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001585llvm::Value *
1586MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1587 llvm::Value *This,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001588 llvm::Value *VBPtrOffset,
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001589 llvm::Value *VBTableOffset,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001590 llvm::Value **VBPtrOut) {
1591 CGBuilderTy &Builder = CGF.Builder;
1592 // Load the vbtable pointer from the vbptr in the instance.
1593 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1594 llvm::Value *VBPtr =
1595 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1596 if (VBPtrOut) *VBPtrOut = VBPtr;
1597 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1598 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1599
1600 // Load an i32 offset from the vb-table.
1601 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1602 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1603 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1604}
1605
Reid Kleckner2341ae32013-04-11 18:13:19 +00001606// Returns an adjusted base cast to i8*, since we do more address arithmetic on
1607// it.
1608llvm::Value *
1609MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1610 const CXXRecordDecl *RD, llvm::Value *Base,
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001611 llvm::Value *VBTableOffset,
Reid Kleckner2341ae32013-04-11 18:13:19 +00001612 llvm::Value *VBPtrOffset) {
1613 CGBuilderTy &Builder = CGF.Builder;
1614 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1615 llvm::BasicBlock *OriginalBB = 0;
1616 llvm::BasicBlock *SkipAdjustBB = 0;
1617 llvm::BasicBlock *VBaseAdjustBB = 0;
1618
1619 // In the unspecified inheritance model, there might not be a vbtable at all,
1620 // in which case we need to skip the virtual base lookup. If there is a
1621 // vbtable, the first entry is a no-op entry that gives back the original
1622 // base, so look for a virtual base adjustment offset of zero.
1623 if (VBPtrOffset) {
1624 OriginalBB = Builder.GetInsertBlock();
1625 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1626 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1627 llvm::Value *IsVirtual =
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001628 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
Reid Kleckner2341ae32013-04-11 18:13:19 +00001629 "memptr.is_vbase");
1630 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1631 CGF.EmitBlock(VBaseAdjustBB);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001632 }
1633
Reid Kleckner2341ae32013-04-11 18:13:19 +00001634 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1635 // know the vbptr offset.
1636 if (!VBPtrOffset) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001637 CharUnits offs = CharUnits::Zero();
1638 if (RD->getNumVBases()) {
1639 offs = GetVBPtrOffsetFromBases(RD);
1640 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001641 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1642 }
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001643 llvm::Value *VBPtr = 0;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001644 llvm::Value *VBaseOffs =
Timur Iskhodzhanov07e6eff2013-10-27 17:10:27 +00001645 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001646 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1647
1648 // Merge control flow with the case where we didn't have to adjust.
1649 if (VBaseAdjustBB) {
1650 Builder.CreateBr(SkipAdjustBB);
1651 CGF.EmitBlock(SkipAdjustBB);
1652 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1653 Phi->addIncoming(Base, OriginalBB);
1654 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1655 return Phi;
1656 }
1657 return AdjustedBase;
Reid Kleckner407e8b62013-03-22 19:02:54 +00001658}
1659
1660llvm::Value *
1661MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1662 llvm::Value *Base,
1663 llvm::Value *MemPtr,
1664 const MemberPointerType *MPT) {
Reid Kleckner2341ae32013-04-11 18:13:19 +00001665 assert(MPT->isMemberDataPointer());
Reid Kleckner407e8b62013-03-22 19:02:54 +00001666 unsigned AS = Base->getType()->getPointerAddressSpace();
1667 llvm::Type *PType =
1668 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1669 CGBuilderTy &Builder = CGF.Builder;
Reid Kleckner2341ae32013-04-11 18:13:19 +00001670 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1671 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Kleckner407e8b62013-03-22 19:02:54 +00001672
Reid Kleckner2341ae32013-04-11 18:13:19 +00001673 // Extract the fields we need, regardless of model. We'll apply them if we
1674 // have them.
1675 llvm::Value *FieldOffset = MemPtr;
1676 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1677 llvm::Value *VBPtrOffset = 0;
1678 if (MemPtr->getType()->isStructTy()) {
1679 // We need to extract values.
1680 unsigned I = 0;
1681 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1682 if (hasVBPtrOffsetField(Inheritance))
1683 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1684 if (hasVirtualBaseAdjustmentField(Inheritance))
1685 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001686 }
1687
Reid Kleckner2341ae32013-04-11 18:13:19 +00001688 if (VirtualBaseAdjustmentOffset) {
1689 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1690 VBPtrOffset);
Reid Kleckner407e8b62013-03-22 19:02:54 +00001691 }
Reid Kleckner2341ae32013-04-11 18:13:19 +00001692 llvm::Value *Addr =
1693 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Kleckner407e8b62013-03-22 19:02:54 +00001694
1695 // Cast the address to the appropriate pointer type, adopting the address
1696 // space of the base pointer.
1697 return Builder.CreateBitCast(Addr, PType);
1698}
1699
Reid Kleckner452abac2013-05-09 21:01:17 +00001700static MSInheritanceModel
1701getInheritanceFromMemptr(const MemberPointerType *MPT) {
1702 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1703}
1704
1705llvm::Value *
1706MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1707 const CastExpr *E,
1708 llvm::Value *Src) {
1709 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1710 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1711 E->getCastKind() == CK_ReinterpretMemberPointer);
1712
1713 // Use constant emission if we can.
1714 if (isa<llvm::Constant>(Src))
1715 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1716
1717 // We may be adding or dropping fields from the member pointer, so we need
1718 // both types and the inheritance models of both records.
1719 const MemberPointerType *SrcTy =
1720 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1721 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1722 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1723 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1724 bool IsFunc = SrcTy->isMemberFunctionPointer();
1725
1726 // If the classes use the same null representation, reinterpret_cast is a nop.
1727 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1728 if (IsReinterpret && (IsFunc ||
1729 nullFieldOffsetIsZero(SrcInheritance) ==
1730 nullFieldOffsetIsZero(DstInheritance)))
1731 return Src;
1732
1733 CGBuilderTy &Builder = CGF.Builder;
1734
1735 // Branch past the conversion if Src is null.
1736 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1737 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1738
1739 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1740 // pointer value of the destination type.
1741 if (IsReinterpret) {
1742 // For reinterpret casts, sema ensures that src and dst are both functions
1743 // or data and have the same size, which means the LLVM types should match.
1744 assert(Src->getType() == DstNull->getType());
1745 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1746 }
1747
1748 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1749 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1750 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1751 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1752 CGF.EmitBlock(ConvertBB);
1753
1754 // Decompose src.
1755 llvm::Value *FirstField = Src;
1756 llvm::Value *NonVirtualBaseAdjustment = 0;
1757 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1758 llvm::Value *VBPtrOffset = 0;
1759 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1760 // We need to extract values.
1761 unsigned I = 0;
1762 FirstField = Builder.CreateExtractValue(Src, I++);
1763 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1764 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1765 if (hasVBPtrOffsetField(SrcInheritance))
1766 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1767 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1768 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1769 }
1770
1771 // For data pointers, we adjust the field offset directly. For functions, we
1772 // have a separate field.
1773 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1774 if (Adj) {
1775 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1776 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1777 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1778 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1779 NVAdjustField = getZeroInt();
1780 if (isDerivedToBase)
1781 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1782 else
1783 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1784 }
1785
1786 // FIXME PR15713: Support conversions through virtually derived classes.
1787
1788 // Recompose dst from the null struct and the adjusted fields from src.
1789 llvm::Value *Dst;
1790 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1791 Dst = FirstField;
1792 } else {
1793 Dst = llvm::UndefValue::get(DstNull->getType());
1794 unsigned Idx = 0;
1795 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1796 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1797 Dst = Builder.CreateInsertValue(
1798 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1799 if (hasVBPtrOffsetField(DstInheritance))
1800 Dst = Builder.CreateInsertValue(
1801 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1802 if (hasVirtualBaseAdjustmentField(DstInheritance))
1803 Dst = Builder.CreateInsertValue(
1804 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1805 }
1806 Builder.CreateBr(ContinueBB);
1807
1808 // In the continuation, choose between DstNull and Dst.
1809 CGF.EmitBlock(ContinueBB);
1810 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1811 Phi->addIncoming(DstNull, OriginalBB);
1812 Phi->addIncoming(Dst, ConvertBB);
1813 return Phi;
1814}
1815
1816llvm::Constant *
1817MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1818 llvm::Constant *Src) {
1819 const MemberPointerType *SrcTy =
1820 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1821 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1822
1823 // If src is null, emit a new null for dst. We can't return src because dst
1824 // might have a new representation.
1825 if (MemberPointerConstantIsNull(SrcTy, Src))
1826 return EmitNullMemberPointer(DstTy);
1827
1828 // We don't need to do anything for reinterpret_casts of non-null member
1829 // pointers. We should only get here when the two type representations have
1830 // the same size.
1831 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1832 return Src;
1833
1834 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1835 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1836
1837 // Decompose src.
1838 llvm::Constant *FirstField = Src;
1839 llvm::Constant *NonVirtualBaseAdjustment = 0;
1840 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1841 llvm::Constant *VBPtrOffset = 0;
1842 bool IsFunc = SrcTy->isMemberFunctionPointer();
1843 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1844 // We need to extract values.
1845 unsigned I = 0;
1846 FirstField = Src->getAggregateElement(I++);
1847 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1848 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1849 if (hasVBPtrOffsetField(SrcInheritance))
1850 VBPtrOffset = Src->getAggregateElement(I++);
1851 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1852 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1853 }
1854
1855 // For data pointers, we adjust the field offset directly. For functions, we
1856 // have a separate field.
1857 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1858 if (Adj) {
1859 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1860 llvm::Constant *&NVAdjustField =
1861 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1862 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1863 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1864 NVAdjustField = getZeroInt();
1865 if (IsDerivedToBase)
1866 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1867 else
1868 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1869 }
1870
1871 // FIXME PR15713: Support conversions through virtually derived classes.
1872
1873 // Recompose dst from the null struct and the adjusted fields from src.
1874 if (hasOnlyOneField(IsFunc, DstInheritance))
1875 return FirstField;
1876
1877 llvm::SmallVector<llvm::Constant *, 4> Fields;
1878 Fields.push_back(FirstField);
1879 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1880 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1881 if (hasVBPtrOffsetField(DstInheritance))
1882 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1883 if (hasVirtualBaseAdjustmentField(DstInheritance))
1884 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1885 return llvm::ConstantStruct::getAnon(Fields);
1886}
1887
Reid Kleckner2341ae32013-04-11 18:13:19 +00001888llvm::Value *
1889MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1890 llvm::Value *&This,
1891 llvm::Value *MemPtr,
1892 const MemberPointerType *MPT) {
1893 assert(MPT->isMemberFunctionPointer());
1894 const FunctionProtoType *FPT =
1895 MPT->getPointeeType()->castAs<FunctionProtoType>();
1896 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1897 llvm::FunctionType *FTy =
1898 CGM.getTypes().GetFunctionType(
1899 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1900 CGBuilderTy &Builder = CGF.Builder;
1901
1902 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1903
1904 // Extract the fields we need, regardless of model. We'll apply them if we
1905 // have them.
1906 llvm::Value *FunctionPointer = MemPtr;
1907 llvm::Value *NonVirtualBaseAdjustment = NULL;
1908 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1909 llvm::Value *VBPtrOffset = NULL;
1910 if (MemPtr->getType()->isStructTy()) {
1911 // We need to extract values.
1912 unsigned I = 0;
1913 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001914 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1915 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner7d0efb52013-05-03 01:15:11 +00001916 if (hasVBPtrOffsetField(Inheritance))
1917 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Kleckner2341ae32013-04-11 18:13:19 +00001918 if (hasVirtualBaseAdjustmentField(Inheritance))
1919 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1920 }
1921
1922 if (VirtualBaseAdjustmentOffset) {
1923 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1924 VBPtrOffset);
1925 }
1926
1927 if (NonVirtualBaseAdjustment) {
1928 // Apply the adjustment and cast back to the original struct type.
1929 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1930 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1931 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1932 }
1933
1934 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1935}
1936
Charles Davis53c59df2010-08-16 03:33:14 +00001937CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davis74ce8592010-06-09 23:25:41 +00001938 return new MicrosoftCXXABI(CGM);
1939}