blob: a0e4f4d38478d17081369500f758a283178958aa [file] [log] [blame]
Charles Davisc3926642010-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 Lattnerfc8f0e12011-04-15 05:22:18 +000010// This provides C++ code generation targeting the Microsoft Visual C++ ABI.
Charles Davisc3926642010-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"
Charles Davisc3926642010-06-09 23:25:41 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
Charles Davisc3926642010-06-09 23:25:41 +000021
22using namespace clang;
23using namespace CodeGen;
24
25namespace {
26
Charles Davis071cc7d2010-08-16 03:33:14 +000027class MicrosoftCXXABI : public CGCXXABI {
Charles Davisc3926642010-06-09 23:25:41 +000028public:
Peter Collingbourne14110472011-01-13 18:57:25 +000029 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
John McCall4c40d982010-08-31 07:33:07 +000030
Joao Matos285baac2012-07-17 17:10:11 +000031 StringRef GetPureVirtualCallName() { return "_purecall"; }
David Blaikie2eb9a952012-10-16 22:56:05 +000032 // No known support for deleted functions in MSVC yet, so this choice is
33 // arbitrary.
34 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
Joao Matos285baac2012-07-17 17:10:11 +000035
John McCallecd03b42012-09-25 10:10:39 +000036 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
37 llvm::Value *ptr,
38 QualType type);
39
John McCall4c40d982010-08-31 07:33:07 +000040 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
41 CXXCtorType Type,
42 CanQualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000043 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000044
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000045 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF);
46
John McCall4c40d982010-08-31 07:33:07 +000047 void BuildDestructorSignature(const CXXDestructorDecl *Ctor,
48 CXXDtorType Type,
49 CanQualType &ResTy,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000050 SmallVectorImpl<CanQualType> &ArgTys);
John McCall4c40d982010-08-31 07:33:07 +000051
52 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
53 QualType &ResTy,
John McCallbd315742012-09-25 08:00:39 +000054 FunctionArgList &Params);
John McCall4c40d982010-08-31 07:33:07 +000055
John McCallbd315742012-09-25 08:00:39 +000056 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
John McCallfd708262011-01-27 02:46:02 +000057
Manman Ren63fd4082013-03-20 16:59:38 +000058 llvm::Value *EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000059 const CXXConstructorDecl *D,
60 CXXCtorType Type, bool ForVirtualBase,
61 bool Delegating,
62 llvm::Value *This,
63 CallExpr::const_arg_iterator ArgBeg,
64 CallExpr::const_arg_iterator ArgEnd);
65
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +000066 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
67 const CXXDestructorDecl *Dtor,
68 CXXDtorType DtorType,
69 SourceLocation CallLoc,
70 ReturnValueSlot ReturnValue,
71 llvm::Value *This);
72
John McCall20bb1752012-05-01 06:13:13 +000073 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
74 llvm::GlobalVariable *DeclPtr,
75 bool PerformInit);
76
John McCallfd708262011-01-27 02:46:02 +000077 // ==== Notes on array cookies =========
78 //
79 // MSVC seems to only use cookies when the class has a destructor; a
80 // two-argument usual array deallocation function isn't sufficient.
81 //
82 // For example, this code prints "100" and "1":
83 // struct A {
84 // char x;
85 // void *operator new[](size_t sz) {
86 // printf("%u\n", sz);
87 // return malloc(sz);
88 // }
89 // void operator delete[](void *p, size_t sz) {
90 // printf("%u\n", sz);
91 // free(p);
92 // }
93 // };
94 // int main() {
95 // A *p = new A[100];
96 // delete[] p;
97 // }
98 // Whereas it prints "104" and "104" if you give A a destructor.
John McCalle2b45e22012-05-01 05:23:51 +000099
100 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
101 bool requiresArrayCookie(const CXXNewExpr *expr);
102 CharUnits getArrayCookieSizeImpl(QualType type);
103 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
104 llvm::Value *NewPtr,
105 llvm::Value *NumElements,
106 const CXXNewExpr *expr,
107 QualType ElementType);
108 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
109 llvm::Value *allocPtr,
110 CharUnits cookieSize);
John McCallbd315742012-09-25 08:00:39 +0000111 static bool needThisReturn(GlobalDecl GD);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000112
113private:
Reid Klecknera3609b02013-04-11 18:13:19 +0000114 llvm::Constant *getZeroInt() {
115 return llvm::ConstantInt::get(CGM.IntTy, 0);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000116 }
117
Reid Klecknera3609b02013-04-11 18:13:19 +0000118 llvm::Constant *getAllOnesInt() {
119 return llvm::Constant::getAllOnesValue(CGM.IntTy);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000120 }
121
Reid Klecknera3609b02013-04-11 18:13:19 +0000122 void
123 GetNullMemberPointerFields(const MemberPointerType *MPT,
124 llvm::SmallVectorImpl<llvm::Constant *> &fields);
125
126 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
127 llvm::Value *Base,
128 llvm::Value *VirtualBaseAdjustmentOffset,
129 llvm::Value *VBPtrOffset /* optional */);
130
Reid Klecknera8a0f762013-03-22 19:02:54 +0000131public:
Reid Klecknera3609b02013-04-11 18:13:19 +0000132 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
133
134 virtual bool isZeroInitializable(const MemberPointerType *MPT);
135
Reid Klecknera8a0f762013-03-22 19:02:54 +0000136 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
137
138 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
139 CharUnits offset);
140
141 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
142 llvm::Value *MemPtr,
143 const MemberPointerType *MPT);
144
145 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
146 llvm::Value *Base,
147 llvm::Value *MemPtr,
148 const MemberPointerType *MPT);
149
Reid Klecknera3609b02013-04-11 18:13:19 +0000150 virtual llvm::Value *
151 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
152 llvm::Value *&This,
153 llvm::Value *MemPtr,
154 const MemberPointerType *MPT);
155
Charles Davisc3926642010-06-09 23:25:41 +0000156};
157
158}
159
John McCallecd03b42012-09-25 10:10:39 +0000160llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
161 llvm::Value *ptr,
162 QualType type) {
163 // FIXME: implement
164 return ptr;
165}
166
John McCallbd315742012-09-25 08:00:39 +0000167bool MicrosoftCXXABI::needThisReturn(GlobalDecl GD) {
168 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
169 return isa<CXXConstructorDecl>(MD);
170}
171
172void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
173 CXXCtorType Type,
174 CanQualType &ResTy,
175 SmallVectorImpl<CanQualType> &ArgTys) {
176 // 'this' is already in place
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000177
John McCallbd315742012-09-25 08:00:39 +0000178 // Ctor returns this ptr
179 ResTy = ArgTys[0];
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000180
181 const CXXRecordDecl *Class = Ctor->getParent();
182 if (Class->getNumVBases()) {
183 // Constructors of classes with virtual bases take an implicit parameter.
184 ArgTys.push_back(CGM.getContext().IntTy);
185 }
186}
187
188llvm::BasicBlock *MicrosoftCXXABI::EmitCtorCompleteObjectHandler(
189 CodeGenFunction &CGF) {
190 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
191 assert(IsMostDerivedClass &&
192 "ctor for a class with virtual bases must have an implicit parameter");
193 llvm::Value *IsCompleteObject
194 = CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
195
196 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
197 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
198 CGF.Builder.CreateCondBr(IsCompleteObject,
199 CallVbaseCtorsBB, SkipVbaseCtorsBB);
200
201 CGF.EmitBlock(CallVbaseCtorsBB);
202 // FIXME: emit vbtables somewhere around here.
203
204 // CGF will put the base ctor calls in this basic block for us later.
205
206 return SkipVbaseCtorsBB;
John McCallbd315742012-09-25 08:00:39 +0000207}
208
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000209void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
210 CXXDtorType Type,
211 CanQualType &ResTy,
212 SmallVectorImpl<CanQualType> &ArgTys) {
213 // 'this' is already in place
214 // TODO: 'for base' flag
215
216 if (Type == Dtor_Deleting) {
217 // The scalar deleting destructor takes an implicit bool parameter.
218 ArgTys.push_back(CGM.getContext().BoolTy);
219 }
220}
221
222static bool IsDeletingDtor(GlobalDecl GD) {
223 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
224 if (isa<CXXDestructorDecl>(MD)) {
225 return GD.getDtorType() == Dtor_Deleting;
226 }
227 return false;
228}
229
John McCallbd315742012-09-25 08:00:39 +0000230void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
231 QualType &ResTy,
232 FunctionArgList &Params) {
233 BuildThisParam(CGF, Params);
234 if (needThisReturn(CGF.CurGD)) {
235 ResTy = Params[0]->getType();
236 }
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000237
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000238 ASTContext &Context = getContext();
239 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
240 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
241 ImplicitParamDecl *IsMostDerived
242 = ImplicitParamDecl::Create(Context, 0,
243 CGF.CurGD.getDecl()->getLocation(),
244 &Context.Idents.get("is_most_derived"),
245 Context.IntTy);
246 Params.push_back(IsMostDerived);
247 getStructorImplicitParamDecl(CGF) = IsMostDerived;
248 } else if (IsDeletingDtor(CGF.CurGD)) {
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000249 ImplicitParamDecl *ShouldDelete
250 = ImplicitParamDecl::Create(Context, 0,
251 CGF.CurGD.getDecl()->getLocation(),
252 &Context.Idents.get("should_call_delete"),
253 Context.BoolTy);
254 Params.push_back(ShouldDelete);
255 getStructorImplicitParamDecl(CGF) = ShouldDelete;
256 }
John McCallbd315742012-09-25 08:00:39 +0000257}
258
259void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
260 EmitThisParam(CGF);
261 if (needThisReturn(CGF.CurGD)) {
262 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
263 }
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000264
265 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
266 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
267 assert(getStructorImplicitParamDecl(CGF) &&
268 "no implicit parameter for a constructor with virtual bases?");
269 getStructorImplicitParamValue(CGF)
270 = CGF.Builder.CreateLoad(
271 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
272 "is_most_derived");
273 }
274
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +0000275 if (IsDeletingDtor(CGF.CurGD)) {
276 assert(getStructorImplicitParamDecl(CGF) &&
277 "no implicit parameter for a deleting destructor?");
278 getStructorImplicitParamValue(CGF)
279 = CGF.Builder.CreateLoad(
280 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
281 "should_call_delete");
282 }
John McCallbd315742012-09-25 08:00:39 +0000283}
284
Manman Ren63fd4082013-03-20 16:59:38 +0000285llvm::Value *MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000286 const CXXConstructorDecl *D,
287 CXXCtorType Type, bool ForVirtualBase,
288 bool Delegating,
289 llvm::Value *This,
290 CallExpr::const_arg_iterator ArgBeg,
291 CallExpr::const_arg_iterator ArgEnd) {
292 assert(Type == Ctor_Complete || Type == Ctor_Base);
293 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
294
295 llvm::Value *ImplicitParam = 0;
296 QualType ImplicitParamTy;
297 if (D->getParent()->getNumVBases()) {
298 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
299 ImplicitParamTy = getContext().IntTy;
300 }
301
302 // FIXME: Provide a source location here.
303 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
304 ImplicitParam, ImplicitParamTy,
305 ArgBeg, ArgEnd);
Manman Ren63fd4082013-03-20 16:59:38 +0000306 return Callee;
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000307}
308
Timur Iskhodzhanov0f9827f2013-02-15 14:45:22 +0000309RValue MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
310 const CXXDestructorDecl *Dtor,
311 CXXDtorType DtorType,
312 SourceLocation CallLoc,
313 ReturnValueSlot ReturnValue,
314 llvm::Value *This) {
315 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
316
317 // We have only one destructor in the vftable but can get both behaviors
318 // by passing an implicit bool parameter.
319 const CGFunctionInfo *FInfo
320 = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
321 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
322 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, This, Ty);
323
324 ASTContext &Context = CGF.getContext();
325 llvm::Value *ImplicitParam
326 = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()),
327 DtorType == Dtor_Deleting);
328
329 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
330 ImplicitParam, Context.BoolTy, 0, 0);
331}
332
John McCalle2b45e22012-05-01 05:23:51 +0000333bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
334 QualType elementType) {
335 // Microsoft seems to completely ignore the possibility of a
336 // two-argument usual deallocation function.
337 return elementType.isDestructedType();
338}
339
340bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
341 // Microsoft seems to completely ignore the possibility of a
342 // two-argument usual deallocation function.
343 return expr->getAllocatedType().isDestructedType();
344}
345
346CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
347 // The array cookie is always a size_t; we then pad that out to the
348 // alignment of the element type.
349 ASTContext &Ctx = getContext();
350 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
351 Ctx.getTypeAlignInChars(type));
352}
353
354llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
355 llvm::Value *allocPtr,
356 CharUnits cookieSize) {
Micah Villmow956a5a12012-10-25 15:39:14 +0000357 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000358 llvm::Value *numElementsPtr =
359 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
360 return CGF.Builder.CreateLoad(numElementsPtr);
361}
362
363llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
364 llvm::Value *newPtr,
365 llvm::Value *numElements,
366 const CXXNewExpr *expr,
367 QualType elementType) {
368 assert(requiresArrayCookie(expr));
369
370 // The size of the cookie.
371 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
372
373 // Compute an offset to the cookie.
374 llvm::Value *cookiePtr = newPtr;
375
376 // Write the number of elements into the appropriate slot.
Micah Villmow956a5a12012-10-25 15:39:14 +0000377 unsigned AS = newPtr->getType()->getPointerAddressSpace();
John McCalle2b45e22012-05-01 05:23:51 +0000378 llvm::Value *numElementsPtr
379 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
380 CGF.Builder.CreateStore(numElements, numElementsPtr);
381
382 // Finally, compute a pointer to the actual data buffer by skipping
383 // over the cookie completely.
384 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
385 cookieSize.getQuantity());
386}
387
John McCall20bb1752012-05-01 06:13:13 +0000388void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
389 llvm::GlobalVariable *DeclPtr,
390 bool PerformInit) {
391 // FIXME: this code was only tested for global initialization.
392 // Not sure whether we want thread-safe static local variables as VS
393 // doesn't make them thread-safe.
394
Richard Smith04e51762013-04-14 23:01:42 +0000395 if (D.getTLSKind())
396 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
397
John McCall20bb1752012-05-01 06:13:13 +0000398 // Emit the initializer and add a global destructor if appropriate.
399 CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
400}
401
Reid Klecknera3609b02013-04-11 18:13:19 +0000402// Member pointer helpers.
403static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
404 return Inheritance == MSIM_Unspecified;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000405}
406
Reid Klecknera3609b02013-04-11 18:13:19 +0000407// Only member pointers to functions need a this adjustment, since it can be
408// combined with the field offset for data pointers.
409static bool hasNonVirtualBaseAdjustmentField(const MemberPointerType *MPT,
410 MSInheritanceModel Inheritance) {
411 return (MPT->isMemberFunctionPointer() &&
412 Inheritance >= MSIM_Multiple);
413}
414
415static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
416 return Inheritance >= MSIM_Virtual;
417}
418
419// Use zero for the field offset of a null data member pointer if we can
420// guarantee that zero is not a valid field offset, or if the member pointer has
421// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
422// use zero for null. If there are multiple fields, we can use zero even if it
423// is a valid field offset because null-ness testing will check the other
424// fields.
425static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
426 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
427}
428
429bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
430 // Null-ness for function memptrs only depends on the first field, which is
431 // the function pointer. The rest don't matter, so we can zero initialize.
432 if (MPT->isMemberFunctionPointer())
433 return true;
434
435 // The virtual base adjustment field is always -1 for null, so if we have one
436 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
437 // valid field offset.
438 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
439 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
440 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
441 nullFieldOffsetIsZero(Inheritance));
442}
443
444llvm::Type *
445MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
446 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
447 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
448 llvm::SmallVector<llvm::Type *, 4> fields;
449 if (MPT->isMemberFunctionPointer())
450 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
451 else
452 fields.push_back(CGM.IntTy); // FieldOffset
453
454 if (hasVBPtrOffsetField(Inheritance))
455 fields.push_back(CGM.IntTy);
456 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
457 fields.push_back(CGM.IntTy);
458 if (hasVirtualBaseAdjustmentField(Inheritance))
459 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
460
461 if (fields.size() == 1)
462 return fields[0];
463 return llvm::StructType::get(CGM.getLLVMContext(), fields);
464}
465
466void MicrosoftCXXABI::
467GetNullMemberPointerFields(const MemberPointerType *MPT,
468 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
469 assert(fields.empty());
470 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
471 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
472 if (MPT->isMemberFunctionPointer()) {
473 // FunctionPointerOrVirtualThunk
474 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
475 } else {
476 if (nullFieldOffsetIsZero(Inheritance))
477 fields.push_back(getZeroInt()); // FieldOffset
478 else
479 fields.push_back(getAllOnesInt()); // FieldOffset
Reid Klecknera8a0f762013-03-22 19:02:54 +0000480 }
Reid Klecknera3609b02013-04-11 18:13:19 +0000481
482 if (hasVBPtrOffsetField(Inheritance))
483 fields.push_back(getZeroInt());
484 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
485 fields.push_back(getZeroInt());
486 if (hasVirtualBaseAdjustmentField(Inheritance))
487 fields.push_back(getAllOnesInt());
Reid Klecknera8a0f762013-03-22 19:02:54 +0000488}
489
490llvm::Constant *
491MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +0000492 llvm::SmallVector<llvm::Constant *, 4> fields;
493 GetNullMemberPointerFields(MPT, fields);
494 if (fields.size() == 1)
495 return fields[0];
496 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
497 assert(Res->getType() == ConvertMemberPointerType(MPT));
498 return Res;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000499}
500
501llvm::Constant *
502MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
503 CharUnits offset) {
Reid Klecknera3609b02013-04-11 18:13:19 +0000504 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
505 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
506 llvm::SmallVector<llvm::Constant *, 4> fields;
507 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()));
508 if (hasVBPtrOffsetField(Inheritance)) {
509 int64_t VBPtrOffset =
510 getContext().getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
511 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset));
512 }
513 assert(!hasNonVirtualBaseAdjustmentField(MPT, Inheritance));
514 // The virtual base field starts out zero. It is adjusted by conversions to
515 // member pointer types of a more derived class. See http://llvm.org/PR15713
516 if (hasVirtualBaseAdjustmentField(Inheritance))
517 fields.push_back(getZeroInt());
518 if (fields.size() == 1)
519 return fields[0];
520 return llvm::ConstantStruct::getAnon(fields);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000521}
522
523llvm::Value *
524MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
525 llvm::Value *MemPtr,
526 const MemberPointerType *MPT) {
527 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +0000528 llvm::SmallVector<llvm::Constant *, 4> fields;
529 // We only need one field for member functions.
530 if (MPT->isMemberFunctionPointer())
531 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
532 else
533 GetNullMemberPointerFields(MPT, fields);
534 assert(!fields.empty());
535 llvm::Value *FirstField = MemPtr;
536 if (MemPtr->getType()->isStructTy())
537 FirstField = Builder.CreateExtractValue(MemPtr, 0);
538 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
Reid Klecknera8a0f762013-03-22 19:02:54 +0000539
Reid Klecknera3609b02013-04-11 18:13:19 +0000540 // For function member pointers, we only need to test the function pointer
541 // field. The other fields if any can be garbage.
542 if (MPT->isMemberFunctionPointer())
543 return Res;
544
545 // Otherwise, emit a series of compares and combine the results.
546 for (int I = 1, E = fields.size(); I < E; ++I) {
547 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
548 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
549 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
550 }
551 return Res;
552}
553
554// Returns an adjusted base cast to i8*, since we do more address arithmetic on
555// it.
556llvm::Value *
557MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
558 const CXXRecordDecl *RD, llvm::Value *Base,
559 llvm::Value *VirtualBaseAdjustmentOffset,
560 llvm::Value *VBPtrOffset) {
561 CGBuilderTy &Builder = CGF.Builder;
562 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
563 llvm::BasicBlock *OriginalBB = 0;
564 llvm::BasicBlock *SkipAdjustBB = 0;
565 llvm::BasicBlock *VBaseAdjustBB = 0;
566
567 // In the unspecified inheritance model, there might not be a vbtable at all,
568 // in which case we need to skip the virtual base lookup. If there is a
569 // vbtable, the first entry is a no-op entry that gives back the original
570 // base, so look for a virtual base adjustment offset of zero.
571 if (VBPtrOffset) {
572 OriginalBB = Builder.GetInsertBlock();
573 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
574 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
575 llvm::Value *IsVirtual =
576 Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(),
577 "memptr.is_vbase");
578 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
579 CGF.EmitBlock(VBaseAdjustBB);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000580 }
581
Reid Klecknera3609b02013-04-11 18:13:19 +0000582 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
583 // know the vbptr offset.
584 if (!VBPtrOffset) {
585 CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
586 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
587 }
588 // Load the vbtable pointer from the vbtable offset in the instance.
589 llvm::Value *VBPtr =
590 Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr");
591 llvm::Value *VBTable =
592 Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
593 VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable");
594 // Load an i32 offset from the vb-table.
595 llvm::Value *VBaseOffs =
596 Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset);
597 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
598 VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs");
599 // Add it to VBPtr. GEP will sign extend the i32 value for us.
600 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
601
602 // Merge control flow with the case where we didn't have to adjust.
603 if (VBaseAdjustBB) {
604 Builder.CreateBr(SkipAdjustBB);
605 CGF.EmitBlock(SkipAdjustBB);
606 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
607 Phi->addIncoming(Base, OriginalBB);
608 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
609 return Phi;
610 }
611 return AdjustedBase;
Reid Klecknera8a0f762013-03-22 19:02:54 +0000612}
613
614llvm::Value *
615MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
616 llvm::Value *Base,
617 llvm::Value *MemPtr,
618 const MemberPointerType *MPT) {
Reid Klecknera3609b02013-04-11 18:13:19 +0000619 assert(MPT->isMemberDataPointer());
Reid Klecknera8a0f762013-03-22 19:02:54 +0000620 unsigned AS = Base->getType()->getPointerAddressSpace();
621 llvm::Type *PType =
622 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
623 CGBuilderTy &Builder = CGF.Builder;
Reid Klecknera3609b02013-04-11 18:13:19 +0000624 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
625 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
Reid Klecknera8a0f762013-03-22 19:02:54 +0000626
Reid Klecknera3609b02013-04-11 18:13:19 +0000627 // Extract the fields we need, regardless of model. We'll apply them if we
628 // have them.
629 llvm::Value *FieldOffset = MemPtr;
630 llvm::Value *VirtualBaseAdjustmentOffset = 0;
631 llvm::Value *VBPtrOffset = 0;
632 if (MemPtr->getType()->isStructTy()) {
633 // We need to extract values.
634 unsigned I = 0;
635 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
636 if (hasVBPtrOffsetField(Inheritance))
637 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
638 if (hasVirtualBaseAdjustmentField(Inheritance))
639 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000640 }
641
Reid Klecknera3609b02013-04-11 18:13:19 +0000642 if (VirtualBaseAdjustmentOffset) {
643 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
644 VBPtrOffset);
Reid Klecknera8a0f762013-03-22 19:02:54 +0000645 }
Reid Klecknera3609b02013-04-11 18:13:19 +0000646 llvm::Value *Addr =
647 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
Reid Klecknera8a0f762013-03-22 19:02:54 +0000648
649 // Cast the address to the appropriate pointer type, adopting the address
650 // space of the base pointer.
651 return Builder.CreateBitCast(Addr, PType);
652}
653
Reid Klecknera3609b02013-04-11 18:13:19 +0000654llvm::Value *
655MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
656 llvm::Value *&This,
657 llvm::Value *MemPtr,
658 const MemberPointerType *MPT) {
659 assert(MPT->isMemberFunctionPointer());
660 const FunctionProtoType *FPT =
661 MPT->getPointeeType()->castAs<FunctionProtoType>();
662 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
663 llvm::FunctionType *FTy =
664 CGM.getTypes().GetFunctionType(
665 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
666 CGBuilderTy &Builder = CGF.Builder;
667
668 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
669
670 // Extract the fields we need, regardless of model. We'll apply them if we
671 // have them.
672 llvm::Value *FunctionPointer = MemPtr;
673 llvm::Value *NonVirtualBaseAdjustment = NULL;
674 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
675 llvm::Value *VBPtrOffset = NULL;
676 if (MemPtr->getType()->isStructTy()) {
677 // We need to extract values.
678 unsigned I = 0;
679 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
680 if (hasVBPtrOffsetField(Inheritance))
681 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
682 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
683 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
684 if (hasVirtualBaseAdjustmentField(Inheritance))
685 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
686 }
687
688 if (VirtualBaseAdjustmentOffset) {
689 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
690 VBPtrOffset);
691 }
692
693 if (NonVirtualBaseAdjustment) {
694 // Apply the adjustment and cast back to the original struct type.
695 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
696 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
697 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
698 }
699
700 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
701}
702
Charles Davis071cc7d2010-08-16 03:33:14 +0000703CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
Charles Davisc3926642010-06-09 23:25:41 +0000704 return new MicrosoftCXXABI(CGM);
705}
706