1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
11 // 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
15 //===----------------------------------------------------------------------===//
18 #include "CodeGenModule.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
22 using namespace clang;
23 using namespace CodeGen;
27 class MicrosoftCXXABI : public CGCXXABI {
29 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
31 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
32 // Structures that are not C++03 PODs are always indirect.
36 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
37 if (RD->hasNonTrivialCopyConstructor())
38 return RAA_DirectInMemory;
42 StringRef GetPureVirtualCallName() { return "_purecall"; }
43 // No known support for deleted functions in MSVC yet, so this choice is
45 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
47 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
51 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
54 SmallVectorImpl<CanQualType> &ArgTys);
56 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF);
58 void BuildDestructorSignature(const CXXDestructorDecl *Ctor,
61 SmallVectorImpl<CanQualType> &ArgTys);
63 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
65 FunctionArgList &Params);
67 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
69 llvm::Value *EmitConstructorCall(CodeGenFunction &CGF,
70 const CXXConstructorDecl *D,
71 CXXCtorType Type, bool ForVirtualBase,
74 CallExpr::const_arg_iterator ArgBeg,
75 CallExpr::const_arg_iterator ArgEnd);
77 RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
78 const CXXDestructorDecl *Dtor,
80 SourceLocation CallLoc,
81 ReturnValueSlot ReturnValue,
84 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
85 llvm::GlobalVariable *DeclPtr,
88 // ==== Notes on array cookies =========
90 // MSVC seems to only use cookies when the class has a destructor; a
91 // two-argument usual array deallocation function isn't sufficient.
93 // For example, this code prints "100" and "1":
96 // void *operator new[](size_t sz) {
97 // printf("%u\n", sz);
100 // void operator delete[](void *p, size_t sz) {
101 // printf("%u\n", sz);
106 // A *p = new A[100];
109 // Whereas it prints "104" and "104" if you give A a destructor.
111 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
112 bool requiresArrayCookie(const CXXNewExpr *expr);
113 CharUnits getArrayCookieSizeImpl(QualType type);
114 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
116 llvm::Value *NumElements,
117 const CXXNewExpr *expr,
118 QualType ElementType);
119 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
120 llvm::Value *allocPtr,
121 CharUnits cookieSize);
122 static bool needThisReturn(GlobalDecl GD);
125 llvm::Constant *getZeroInt() {
126 return llvm::ConstantInt::get(CGM.IntTy, 0);
129 llvm::Constant *getAllOnesInt() {
130 return llvm::Constant::getAllOnesValue(CGM.IntTy);
134 GetNullMemberPointerFields(const MemberPointerType *MPT,
135 llvm::SmallVectorImpl<llvm::Constant *> &fields);
137 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
139 llvm::Value *VirtualBaseAdjustmentOffset,
140 llvm::Value *VBPtrOffset /* optional */);
142 /// \brief Emits a full member pointer with the fields common to data and
143 /// function member pointers.
144 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
145 bool IsMemberFunction,
146 const CXXRecordDecl *RD);
149 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
151 virtual bool isZeroInitializable(const MemberPointerType *MPT);
153 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
155 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
157 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
158 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
160 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
163 const MemberPointerType *MPT,
166 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
168 const MemberPointerType *MPT);
170 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
173 const MemberPointerType *MPT);
175 virtual llvm::Value *
176 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
179 const MemberPointerType *MPT);
185 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
192 bool MicrosoftCXXABI::needThisReturn(GlobalDecl GD) {
193 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
194 return isa<CXXConstructorDecl>(MD);
197 void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
200 SmallVectorImpl<CanQualType> &ArgTys) {
201 // 'this' is already in place
203 // Ctor returns this ptr
206 const CXXRecordDecl *Class = Ctor->getParent();
207 if (Class->getNumVBases()) {
208 // Constructors of classes with virtual bases take an implicit parameter.
209 ArgTys.push_back(CGM.getContext().IntTy);
213 llvm::BasicBlock *MicrosoftCXXABI::EmitCtorCompleteObjectHandler(
214 CodeGenFunction &CGF) {
215 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
216 assert(IsMostDerivedClass &&
217 "ctor for a class with virtual bases must have an implicit parameter");
218 llvm::Value *IsCompleteObject
219 = CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
221 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
222 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
223 CGF.Builder.CreateCondBr(IsCompleteObject,
224 CallVbaseCtorsBB, SkipVbaseCtorsBB);
226 CGF.EmitBlock(CallVbaseCtorsBB);
227 // FIXME: emit vbtables somewhere around here.
229 // CGF will put the base ctor calls in this basic block for us later.
231 return SkipVbaseCtorsBB;
234 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
237 SmallVectorImpl<CanQualType> &ArgTys) {
238 // 'this' is already in place
239 // TODO: 'for base' flag
241 if (Type == Dtor_Deleting) {
242 // The scalar deleting destructor takes an implicit bool parameter.
243 ArgTys.push_back(CGM.getContext().BoolTy);
247 static bool IsDeletingDtor(GlobalDecl GD) {
248 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
249 if (isa<CXXDestructorDecl>(MD)) {
250 return GD.getDtorType() == Dtor_Deleting;
255 void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
257 FunctionArgList &Params) {
258 BuildThisParam(CGF, Params);
259 if (needThisReturn(CGF.CurGD)) {
260 ResTy = Params[0]->getType();
263 ASTContext &Context = getContext();
264 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
265 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
266 ImplicitParamDecl *IsMostDerived
267 = ImplicitParamDecl::Create(Context, 0,
268 CGF.CurGD.getDecl()->getLocation(),
269 &Context.Idents.get("is_most_derived"),
271 Params.push_back(IsMostDerived);
272 getStructorImplicitParamDecl(CGF) = IsMostDerived;
273 } else if (IsDeletingDtor(CGF.CurGD)) {
274 ImplicitParamDecl *ShouldDelete
275 = ImplicitParamDecl::Create(Context, 0,
276 CGF.CurGD.getDecl()->getLocation(),
277 &Context.Idents.get("should_call_delete"),
279 Params.push_back(ShouldDelete);
280 getStructorImplicitParamDecl(CGF) = ShouldDelete;
284 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
286 if (needThisReturn(CGF.CurGD)) {
287 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
290 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
291 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
292 assert(getStructorImplicitParamDecl(CGF) &&
293 "no implicit parameter for a constructor with virtual bases?");
294 getStructorImplicitParamValue(CGF)
295 = CGF.Builder.CreateLoad(
296 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
300 if (IsDeletingDtor(CGF.CurGD)) {
301 assert(getStructorImplicitParamDecl(CGF) &&
302 "no implicit parameter for a deleting destructor?");
303 getStructorImplicitParamValue(CGF)
304 = CGF.Builder.CreateLoad(
305 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
306 "should_call_delete");
310 llvm::Value *MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
311 const CXXConstructorDecl *D,
312 CXXCtorType Type, bool ForVirtualBase,
315 CallExpr::const_arg_iterator ArgBeg,
316 CallExpr::const_arg_iterator ArgEnd) {
317 assert(Type == Ctor_Complete || Type == Ctor_Base);
318 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
320 llvm::Value *ImplicitParam = 0;
321 QualType ImplicitParamTy;
322 if (D->getParent()->getNumVBases()) {
323 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
324 ImplicitParamTy = getContext().IntTy;
327 // FIXME: Provide a source location here.
328 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
329 ImplicitParam, ImplicitParamTy,
334 RValue MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
335 const CXXDestructorDecl *Dtor,
336 CXXDtorType DtorType,
337 SourceLocation CallLoc,
338 ReturnValueSlot ReturnValue,
340 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
342 // We have only one destructor in the vftable but can get both behaviors
343 // by passing an implicit bool parameter.
344 const CGFunctionInfo *FInfo
345 = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
346 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
347 llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, This, Ty);
349 ASTContext &Context = CGF.getContext();
350 llvm::Value *ImplicitParam
351 = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()),
352 DtorType == Dtor_Deleting);
354 return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
355 ImplicitParam, Context.BoolTy, 0, 0);
358 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
359 QualType elementType) {
360 // Microsoft seems to completely ignore the possibility of a
361 // two-argument usual deallocation function.
362 return elementType.isDestructedType();
365 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
366 // Microsoft seems to completely ignore the possibility of a
367 // two-argument usual deallocation function.
368 return expr->getAllocatedType().isDestructedType();
371 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
372 // The array cookie is always a size_t; we then pad that out to the
373 // alignment of the element type.
374 ASTContext &Ctx = getContext();
375 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
376 Ctx.getTypeAlignInChars(type));
379 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
380 llvm::Value *allocPtr,
381 CharUnits cookieSize) {
382 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
383 llvm::Value *numElementsPtr =
384 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
385 return CGF.Builder.CreateLoad(numElementsPtr);
388 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
390 llvm::Value *numElements,
391 const CXXNewExpr *expr,
392 QualType elementType) {
393 assert(requiresArrayCookie(expr));
395 // The size of the cookie.
396 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
398 // Compute an offset to the cookie.
399 llvm::Value *cookiePtr = newPtr;
401 // Write the number of elements into the appropriate slot.
402 unsigned AS = newPtr->getType()->getPointerAddressSpace();
403 llvm::Value *numElementsPtr
404 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
405 CGF.Builder.CreateStore(numElements, numElementsPtr);
407 // Finally, compute a pointer to the actual data buffer by skipping
408 // over the cookie completely.
409 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
410 cookieSize.getQuantity());
413 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
414 llvm::GlobalVariable *DeclPtr,
416 // FIXME: this code was only tested for global initialization.
417 // Not sure whether we want thread-safe static local variables as VS
418 // doesn't make them thread-safe.
421 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
423 // Emit the initializer and add a global destructor if appropriate.
424 CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
427 // Member pointer helpers.
428 static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
429 return Inheritance == MSIM_Unspecified;
432 static bool hasOnlyOneField(MSInheritanceModel Inheritance) {
433 return Inheritance <= MSIM_SinglePolymorphic;
436 // Only member pointers to functions need a this adjustment, since it can be
437 // combined with the field offset for data pointers.
438 static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
439 MSInheritanceModel Inheritance) {
440 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
443 static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
444 return Inheritance >= MSIM_Virtual;
447 // Use zero for the field offset of a null data member pointer if we can
448 // guarantee that zero is not a valid field offset, or if the member pointer has
449 // multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
450 // use zero for null. If there are multiple fields, we can use zero even if it
451 // is a valid field offset because null-ness testing will check the other
453 static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
454 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
457 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
458 // Null-ness for function memptrs only depends on the first field, which is
459 // the function pointer. The rest don't matter, so we can zero initialize.
460 if (MPT->isMemberFunctionPointer())
463 // The virtual base adjustment field is always -1 for null, so if we have one
464 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
465 // valid field offset.
466 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
467 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
468 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
469 nullFieldOffsetIsZero(Inheritance));
473 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
474 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
475 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
476 llvm::SmallVector<llvm::Type *, 4> fields;
477 if (MPT->isMemberFunctionPointer())
478 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
480 fields.push_back(CGM.IntTy); // FieldOffset
482 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
484 fields.push_back(CGM.IntTy);
485 if (hasVBPtrOffsetField(Inheritance))
486 fields.push_back(CGM.IntTy);
487 if (hasVirtualBaseAdjustmentField(Inheritance))
488 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
490 if (fields.size() == 1)
492 return llvm::StructType::get(CGM.getLLVMContext(), fields);
495 void MicrosoftCXXABI::
496 GetNullMemberPointerFields(const MemberPointerType *MPT,
497 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
498 assert(fields.empty());
499 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
500 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
501 if (MPT->isMemberFunctionPointer()) {
502 // FunctionPointerOrVirtualThunk
503 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
505 if (nullFieldOffsetIsZero(Inheritance))
506 fields.push_back(getZeroInt()); // FieldOffset
508 fields.push_back(getAllOnesInt()); // FieldOffset
511 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
513 fields.push_back(getZeroInt());
514 if (hasVBPtrOffsetField(Inheritance))
515 fields.push_back(getZeroInt());
516 if (hasVirtualBaseAdjustmentField(Inheritance))
517 fields.push_back(getAllOnesInt());
521 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
522 llvm::SmallVector<llvm::Constant *, 4> fields;
523 GetNullMemberPointerFields(MPT, fields);
524 if (fields.size() == 1)
526 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
527 assert(Res->getType() == ConvertMemberPointerType(MPT));
532 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
533 bool IsMemberFunction,
534 const CXXRecordDecl *RD)
536 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
538 // Single inheritance class member pointer are represented as scalars instead
540 if (hasOnlyOneField(Inheritance))
543 llvm::SmallVector<llvm::Constant *, 4> fields;
544 fields.push_back(FirstField);
546 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
547 fields.push_back(getZeroInt());
549 if (hasVBPtrOffsetField(Inheritance)) {
550 int64_t VBPtrOffset =
551 getContext().getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
552 if (VBPtrOffset == -1)
554 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset));
557 // The rest of the fields are adjusted by conversions to a more derived class.
558 if (hasVirtualBaseAdjustmentField(Inheritance))
559 fields.push_back(getZeroInt());
561 return llvm::ConstantStruct::getAnon(fields);
565 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
567 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
568 llvm::Constant *FirstField =
569 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
570 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD);
574 MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
575 assert(MD->isInstance() && "Member function must not be static!");
576 MD = MD->getCanonicalDecl();
577 const CXXRecordDecl *RD = MD->getParent();
578 CodeGenTypes &Types = CGM.getTypes();
580 llvm::Constant *FirstField;
581 if (MD->isVirtual()) {
582 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
584 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
586 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
588 // Check whether the function has a computable LLVM signature.
589 if (Types.isFuncTypeConvertible(FPT)) {
590 // The function has a computable LLVM signature; use the correct type.
591 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
593 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
594 // function type is incomplete.
597 FirstField = CGM.GetAddrOfFunction(MD, Ty);
598 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
601 // The rest of the fields are common with data member pointers.
602 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD);
606 MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {
607 // FIXME PR15875: Implement member pointer conversions for Constants.
608 const CXXRecordDecl *RD = MPT->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl();
609 return EmitFullMemberPointer(llvm::Constant::getNullValue(CGM.VoidPtrTy),
610 /*IsMemberFunction=*/true, RD);
613 /// Member pointers are the same if they're either bitwise identical *or* both
614 /// null. Null-ness for function members is determined by the first field,
615 /// while for data member pointers we must compare all fields.
617 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
620 const MemberPointerType *MPT,
622 CGBuilderTy &Builder = CGF.Builder;
624 // Handle != comparisons by switching the sense of all boolean operations.
625 llvm::ICmpInst::Predicate Eq;
626 llvm::Instruction::BinaryOps And, Or;
628 Eq = llvm::ICmpInst::ICMP_NE;
629 And = llvm::Instruction::Or;
630 Or = llvm::Instruction::And;
632 Eq = llvm::ICmpInst::ICMP_EQ;
633 And = llvm::Instruction::And;
634 Or = llvm::Instruction::Or;
637 // If this is a single field member pointer (single inheritance), this is a
639 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
640 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
641 if (hasOnlyOneField(Inheritance))
642 return Builder.CreateICmp(Eq, L, R);
644 // Compare the first field.
645 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
646 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
647 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
649 // Compare everything other than the first field.
650 llvm::Value *Res = 0;
651 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
652 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
653 llvm::Value *LF = Builder.CreateExtractValue(L, I);
654 llvm::Value *RF = Builder.CreateExtractValue(R, I);
655 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
657 Res = Builder.CreateBinOp(And, Res, Cmp);
662 // Check if the first field is 0 if this is a function pointer.
663 if (MPT->isMemberFunctionPointer()) {
664 // (l1 == r1 && ...) || l0 == 0
665 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
666 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
667 Res = Builder.CreateBinOp(Or, Res, IsZero);
670 // Combine the comparison of the first field, which must always be true for
671 // this comparison to succeeed.
672 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
676 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
678 const MemberPointerType *MPT) {
679 CGBuilderTy &Builder = CGF.Builder;
680 llvm::SmallVector<llvm::Constant *, 4> fields;
681 // We only need one field for member functions.
682 if (MPT->isMemberFunctionPointer())
683 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
685 GetNullMemberPointerFields(MPT, fields);
686 assert(!fields.empty());
687 llvm::Value *FirstField = MemPtr;
688 if (MemPtr->getType()->isStructTy())
689 FirstField = Builder.CreateExtractValue(MemPtr, 0);
690 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
692 // For function member pointers, we only need to test the function pointer
693 // field. The other fields if any can be garbage.
694 if (MPT->isMemberFunctionPointer())
697 // Otherwise, emit a series of compares and combine the results.
698 for (int I = 1, E = fields.size(); I < E; ++I) {
699 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
700 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
701 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
706 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
709 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
710 const CXXRecordDecl *RD, llvm::Value *Base,
711 llvm::Value *VirtualBaseAdjustmentOffset,
712 llvm::Value *VBPtrOffset) {
713 CGBuilderTy &Builder = CGF.Builder;
714 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
715 llvm::BasicBlock *OriginalBB = 0;
716 llvm::BasicBlock *SkipAdjustBB = 0;
717 llvm::BasicBlock *VBaseAdjustBB = 0;
719 // In the unspecified inheritance model, there might not be a vbtable at all,
720 // in which case we need to skip the virtual base lookup. If there is a
721 // vbtable, the first entry is a no-op entry that gives back the original
722 // base, so look for a virtual base adjustment offset of zero.
724 OriginalBB = Builder.GetInsertBlock();
725 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
726 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
727 llvm::Value *IsVirtual =
728 Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(),
730 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
731 CGF.EmitBlock(VBaseAdjustBB);
734 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
735 // know the vbptr offset.
737 CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
738 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
740 // Load the vbtable pointer from the vbtable offset in the instance.
742 Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr");
743 llvm::Value *VBTable =
744 Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
745 VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable");
746 // Load an i32 offset from the vb-table.
747 llvm::Value *VBaseOffs =
748 Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset);
749 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
750 VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs");
751 // Add it to VBPtr. GEP will sign extend the i32 value for us.
752 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
754 // Merge control flow with the case where we didn't have to adjust.
756 Builder.CreateBr(SkipAdjustBB);
757 CGF.EmitBlock(SkipAdjustBB);
758 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
759 Phi->addIncoming(Base, OriginalBB);
760 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
767 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
770 const MemberPointerType *MPT) {
771 assert(MPT->isMemberDataPointer());
772 unsigned AS = Base->getType()->getPointerAddressSpace();
774 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
775 CGBuilderTy &Builder = CGF.Builder;
776 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
777 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
779 // Extract the fields we need, regardless of model. We'll apply them if we
781 llvm::Value *FieldOffset = MemPtr;
782 llvm::Value *VirtualBaseAdjustmentOffset = 0;
783 llvm::Value *VBPtrOffset = 0;
784 if (MemPtr->getType()->isStructTy()) {
785 // We need to extract values.
787 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
788 if (hasVBPtrOffsetField(Inheritance))
789 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
790 if (hasVirtualBaseAdjustmentField(Inheritance))
791 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
794 if (VirtualBaseAdjustmentOffset) {
795 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
799 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
801 // Cast the address to the appropriate pointer type, adopting the address
802 // space of the base pointer.
803 return Builder.CreateBitCast(Addr, PType);
807 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
810 const MemberPointerType *MPT) {
811 assert(MPT->isMemberFunctionPointer());
812 const FunctionProtoType *FPT =
813 MPT->getPointeeType()->castAs<FunctionProtoType>();
814 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
815 llvm::FunctionType *FTy =
816 CGM.getTypes().GetFunctionType(
817 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
818 CGBuilderTy &Builder = CGF.Builder;
820 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
822 // Extract the fields we need, regardless of model. We'll apply them if we
824 llvm::Value *FunctionPointer = MemPtr;
825 llvm::Value *NonVirtualBaseAdjustment = NULL;
826 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
827 llvm::Value *VBPtrOffset = NULL;
828 if (MemPtr->getType()->isStructTy()) {
829 // We need to extract values.
831 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
832 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
833 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
834 if (hasVBPtrOffsetField(Inheritance))
835 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
836 if (hasVirtualBaseAdjustmentField(Inheritance))
837 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
840 if (VirtualBaseAdjustmentOffset) {
841 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
845 if (NonVirtualBaseAdjustment) {
846 // Apply the adjustment and cast back to the original struct type.
847 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
848 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
849 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
852 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
855 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
856 return new MicrosoftCXXABI(CGM);