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 "CGVTables.h"
20 #include "MicrosoftVBTables.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/VTableBuilder.h"
24 #include "llvm/ADT/StringSet.h"
26 using namespace clang;
27 using namespace CodeGen;
31 class MicrosoftCXXABI : public CGCXXABI {
33 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
35 bool HasThisReturn(GlobalDecl GD) const;
37 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
38 // Structures that are not C++03 PODs are always indirect.
42 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
43 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
44 return RAA_DirectInMemory;
48 StringRef GetPureVirtualCallName() { return "_purecall"; }
49 // No known support for deleted functions in MSVC yet, so this choice is
51 StringRef GetDeletedVirtualCallName() { return "_purecall"; }
53 bool isInlineInitializedStaticDataMemberLinkOnce() { return true; }
55 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
59 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
61 const CXXRecordDecl *ClassDecl,
62 const CXXRecordDecl *BaseClassDecl);
64 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
67 SmallVectorImpl<CanQualType> &ArgTys);
69 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
70 const CXXRecordDecl *RD);
72 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
73 const CXXRecordDecl *RD);
75 void EmitCXXConstructors(const CXXConstructorDecl *D);
77 // Background on MSVC destructors
78 // ==============================
80 // Both Itanium and MSVC ABIs have destructor variants. The variant names
81 // roughly correspond in the following way:
83 // Base -> no name, just ~Class
84 // Complete -> vbase destructor
85 // Deleting -> scalar deleting destructor
86 // vector deleting destructor
88 // The base and complete destructors are the same as in Itanium, although the
89 // complete destructor does not accept a VTT parameter when there are virtual
90 // bases. A separate mechanism involving vtordisps is used to ensure that
91 // virtual methods of destroyed subobjects are not called.
93 // The deleting destructors accept an i32 bitfield as a second parameter. Bit
94 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this
95 // pointer points to an array. The scalar deleting destructor assumes that
96 // bit 2 is zero, and therefore does not contain a loop.
98 // For virtual destructors, only one entry is reserved in the vftable, and it
99 // always points to the vector deleting destructor. The vector deleting
100 // destructor is the most general, so it can be used to destroy objects in
101 // place, delete single heap objects, or delete arrays.
103 // A TU defining a non-inline destructor is only guaranteed to emit a base
104 // destructor, and all of the other variants are emitted on an as-needed basis
105 // in COMDATs. Because a non-base destructor can be emitted in a TU that
106 // lacks a definition for the destructor, non-base destructors must always
107 // delegate to or alias the base destructor.
109 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
112 SmallVectorImpl<CanQualType> &ArgTys);
114 /// Non-base dtors should be emitted as delegating thunks in this ABI.
115 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
116 CXXDtorType DT) const {
117 return DT != Dtor_Base;
120 void EmitCXXDestructors(const CXXDestructorDecl *D);
122 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) {
123 MD = MD->getCanonicalDecl();
124 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
125 MicrosoftVTableContext::MethodVFTableLocation ML =
126 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
127 // The vbases might be ordered differently in the final overrider object
128 // and the complete object, so the "this" argument may sometimes point to
129 // memory that has no particular type (e.g. past the complete object).
130 // In this case, we just use a generic pointer type.
131 // FIXME: might want to have a more precise type in the non-virtual
132 // multiple inheritance case.
133 if (ML.VBase || !ML.VFPtrOffset.isZero())
136 return MD->getParent();
139 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF,
143 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
145 FunctionArgList &Params);
147 llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
148 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This);
150 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
152 void EmitConstructorCall(CodeGenFunction &CGF,
153 const CXXConstructorDecl *D, CXXCtorType Type,
154 bool ForVirtualBase, bool Delegating,
156 CallExpr::const_arg_iterator ArgBeg,
157 CallExpr::const_arg_iterator ArgEnd);
159 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
161 llvm::Value *getVTableAddressPointInStructor(
162 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
163 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
164 bool &NeedsVirtualOffset);
167 getVTableAddressPointForConstExpr(BaseSubobject Base,
168 const CXXRecordDecl *VTableClass);
170 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
171 CharUnits VPtrOffset);
173 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
174 llvm::Value *This, llvm::Type *Ty);
176 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
177 const CXXDestructorDecl *Dtor,
178 CXXDtorType DtorType, SourceLocation CallLoc,
181 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
182 CallArgList &CallArgs) {
183 assert(GD.getDtorType() == Dtor_Deleting &&
184 "Only deleting destructor thunks are available in this ABI");
185 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
186 CGM.getContext().IntTy);
189 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
191 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
192 Thunk->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
195 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
196 const ThisAdjustment &TA);
198 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
199 const ReturnAdjustment &RA);
201 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
202 llvm::GlobalVariable *DeclPtr,
205 // ==== Notes on array cookies =========
207 // MSVC seems to only use cookies when the class has a destructor; a
208 // two-argument usual array deallocation function isn't sufficient.
210 // For example, this code prints "100" and "1":
213 // void *operator new[](size_t sz) {
214 // printf("%u\n", sz);
215 // return malloc(sz);
217 // void operator delete[](void *p, size_t sz) {
218 // printf("%u\n", sz);
223 // A *p = new A[100];
226 // Whereas it prints "104" and "104" if you give A a destructor.
228 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
229 bool requiresArrayCookie(const CXXNewExpr *expr);
230 CharUnits getArrayCookieSizeImpl(QualType type);
231 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
233 llvm::Value *NumElements,
234 const CXXNewExpr *expr,
235 QualType ElementType);
236 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
237 llvm::Value *allocPtr,
238 CharUnits cookieSize);
241 MicrosoftMangleContext &getMangleContext() {
242 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
245 llvm::Constant *getZeroInt() {
246 return llvm::ConstantInt::get(CGM.IntTy, 0);
249 llvm::Constant *getAllOnesInt() {
250 return llvm::Constant::getAllOnesValue(CGM.IntTy);
253 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
254 return C ? C : getZeroInt();
257 llvm::Value *getValueOrZeroInt(llvm::Value *C) {
258 return C ? C : getZeroInt();
262 GetNullMemberPointerFields(const MemberPointerType *MPT,
263 llvm::SmallVectorImpl<llvm::Constant *> &fields);
265 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
266 /// it is reusing a vbptr from a non-virtual base. RD must have morally
268 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
270 /// \brief Shared code for virtual base adjustment. Returns the offset from
271 /// the vbptr to the virtual base. Optionally returns the address of the
273 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
275 llvm::Value *VBPtrOffset,
276 llvm::Value *VBTableOffset,
277 llvm::Value **VBPtr = 0);
279 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
282 int32_t VBTableOffset,
283 llvm::Value **VBPtr = 0) {
284 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
285 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
286 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
289 /// \brief Performs a full virtual base adjustment. Used to dereference
290 /// pointers to members of virtual bases.
291 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
293 llvm::Value *VirtualBaseAdjustmentOffset,
294 llvm::Value *VBPtrOffset /* optional */);
296 /// \brief Emits a full member pointer with the fields common to data and
297 /// function member pointers.
298 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
299 bool IsMemberFunction,
300 const CXXRecordDecl *RD,
301 CharUnits NonVirtualBaseAdjustment);
303 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
304 const CXXMethodDecl *MD,
305 CharUnits NonVirtualBaseAdjustment);
307 bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
310 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
311 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
313 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
314 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
316 /// \brief Generate a thunk for calling a virtual member function MD.
317 llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
318 StringRef ThunkName);
321 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
323 virtual bool isZeroInitializable(const MemberPointerType *MPT);
325 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
327 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
329 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
330 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
332 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
335 const MemberPointerType *MPT,
338 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
340 const MemberPointerType *MPT);
342 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
345 const MemberPointerType *MPT);
347 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
351 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
352 llvm::Constant *Src);
354 virtual llvm::Value *
355 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
358 const MemberPointerType *MPT);
361 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
362 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
363 /// \brief All the vftables that have been referenced.
364 VFTablesMapTy VFTablesMap;
366 /// \brief This set holds the record decls we've deferred vtable emission for.
367 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
370 /// \brief All the vbtables which have been referenced.
371 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
373 /// Info on the global variable used to guard initialization of static locals.
374 /// The BitIndex field is only used for externally invisible declarations.
376 GuardInfo() : Guard(0), BitIndex(0) {}
377 llvm::GlobalVariable *Guard;
381 /// Map from DeclContext to the current guard variable. We assume that the
382 /// AST is visited in source code order.
383 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
388 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
395 /// \brief Finds the first non-virtual base of RD that has virtual bases. If RD
396 /// doesn't have a vbptr, it will reuse the vbptr of the returned class.
397 static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
398 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
399 E = RD->bases_end(); I != E; ++I) {
400 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
401 if (!I->isVirtual() && Base->getNumVBases() > 0)
404 llvm_unreachable("RD must have an nv base with vbases");
407 CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
408 assert(RD->getNumVBases());
409 CharUnits Total = CharUnits::Zero();
411 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
412 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
413 // -1 is the sentinel for no vbptr.
414 if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
415 Total += VBPtrOffset;
418 RD = FindFirstNVBaseWithVBases(RD);
419 Total += RDLayout.getBaseClassOffset(RD);
425 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
427 const CXXRecordDecl *ClassDecl,
428 const CXXRecordDecl *BaseClassDecl) {
429 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
430 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
431 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
432 CharUnits VBTableChars =
434 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
435 llvm::Value *VBTableOffset =
436 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
438 llvm::Value *VBPtrToNewBase =
439 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
441 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
442 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
445 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
446 return isa<CXXConstructorDecl>(GD.getDecl());
449 void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
452 SmallVectorImpl<CanQualType> &ArgTys) {
453 // 'this' parameter and 'this' return are already in place
455 const CXXRecordDecl *Class = Ctor->getParent();
456 if (Class->getNumVBases()) {
457 // Constructors of classes with virtual bases take an implicit parameter.
458 ArgTys.push_back(CGM.getContext().IntTy);
463 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
464 const CXXRecordDecl *RD) {
465 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
466 assert(IsMostDerivedClass &&
467 "ctor for a class with virtual bases must have an implicit parameter");
468 llvm::Value *IsCompleteObject =
469 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
471 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
472 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
473 CGF.Builder.CreateCondBr(IsCompleteObject,
474 CallVbaseCtorsBB, SkipVbaseCtorsBB);
476 CGF.EmitBlock(CallVbaseCtorsBB);
478 // Fill in the vbtable pointers here.
479 EmitVBPtrStores(CGF, RD);
481 // CGF will put the base ctor calls in this basic block for us later.
483 return SkipVbaseCtorsBB;
486 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
487 CodeGenFunction &CGF, const CXXRecordDecl *RD) {
488 // In most cases, an override for a vbase virtual method can adjust
489 // the "this" parameter by applying a constant offset.
490 // However, this is not enough while a constructor or a destructor of some
491 // class X is being executed if all the following conditions are met:
492 // - X has virtual bases, (1)
493 // - X overrides a virtual method M of a vbase Y, (2)
494 // - X itself is a vbase of the most derived class.
496 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
497 // which holds the extra amount of "this" adjustment we must do when we use
498 // the X vftables (i.e. during X ctor or dtor).
499 // Outside the ctors and dtors, the values of vtorDisps are zero.
501 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
502 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
503 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
504 CGBuilderTy &Builder = CGF.Builder;
507 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
508 llvm::Value *Int8This = 0; // Initialize lazily.
510 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
512 if (!I->second.hasVtorDisp())
515 llvm::Value *VBaseOffset =
516 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
517 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
518 // just to Trunc back immediately.
519 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
520 uint64_t ConstantVBaseOffset =
521 Layout.getVBaseClassOffset(I->first).getQuantity();
523 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
524 llvm::Value *VtorDispValue = Builder.CreateSub(
525 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
529 Int8This = Builder.CreateBitCast(getThisValue(CGF),
530 CGF.Int8Ty->getPointerTo(AS));
531 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
532 // vtorDisp is always the 32-bits before the vbase in the class layout.
533 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
534 VtorDispPtr = Builder.CreateBitCast(
535 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
537 Builder.CreateStore(VtorDispValue, VtorDispPtr);
541 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
542 // There's only one constructor type in this ABI.
543 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
546 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
547 const CXXRecordDecl *RD) {
548 llvm::Value *ThisInt8Ptr =
549 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
551 const VBTableVector &VBTables = EnumerateVBTables(RD);
552 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
554 const ASTRecordLayout &SubobjectLayout =
555 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
556 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
557 SubobjectLayout.getVBPtrOffset()).getQuantity();
559 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
560 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
561 "vbptr." + I->ReusingBase->getName());
562 CGF.Builder.CreateStore(I->GV, VBPtr);
566 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
569 SmallVectorImpl<CanQualType> &ArgTys) {
570 // 'this' is already in place
572 // TODO: 'for base' flag
574 if (Type == Dtor_Deleting) {
575 // The scalar deleting destructor takes an implicit int parameter.
576 ArgTys.push_back(CGM.getContext().IntTy);
580 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
581 // The TU defining a dtor is only guaranteed to emit a base destructor. All
582 // other destructor variants are delegating thunks.
583 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
586 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall(
587 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
588 GD = GD.getCanonicalDecl();
589 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
590 // FIXME: consider splitting the vdtor vs regular method code into two
593 GlobalDecl LookupGD = GD;
594 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
595 // Complete dtors take a pointer to the complete object,
596 // thus don't need adjustment.
597 if (GD.getDtorType() == Dtor_Complete)
600 // There's only Dtor_Deleting in vftable but it shares the this adjustment
601 // with the base one, so look up the deleting one instead.
602 LookupGD = GlobalDecl(DD, Dtor_Deleting);
604 MicrosoftVTableContext::MethodVFTableLocation ML =
605 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
607 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
608 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
609 CharUnits StaticOffset = ML.VFPtrOffset;
611 bool AvoidVirtualOffset = false;
612 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) {
613 // A base destructor can only be called from a complete destructor of the
614 // same record type or another destructor of a more derived type;
615 // or a constructor of the same record type if an exception is thrown.
616 assert(isa<CXXDestructorDecl>(CGF.CurGD.getDecl()) ||
617 isa<CXXConstructorDecl>(CGF.CurGD.getDecl()));
618 const CXXRecordDecl *CurRD =
619 cast<CXXMethodDecl>(CGF.CurGD.getDecl())->getParent();
621 if (MD->getParent() == CurRD) {
622 if (isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
623 assert(CGF.CurGD.getDtorType() == Dtor_Complete);
624 if (isa<CXXConstructorDecl>(CGF.CurGD.getDecl()))
625 assert(CGF.CurGD.getCtorType() == Ctor_Complete);
626 // We're calling the main base dtor from a complete structor,
627 // so we know the "this" offset statically.
628 AvoidVirtualOffset = true;
630 // Let's see if we try to call a destructor of a non-virtual base.
631 for (CXXRecordDecl::base_class_const_iterator I = CurRD->bases_begin(),
632 E = CurRD->bases_end(); I != E; ++I) {
633 if (I->getType()->getAsCXXRecordDecl() != MD->getParent())
635 // If we call a base destructor for a non-virtual base, we statically
636 // know where it expects the vfptr and "this" to be.
637 // The total offset should reflect the adjustment done by
638 // adjustThisParameterInVirtualFunctionPrologue().
639 AvoidVirtualOffset = true;
645 if (AvoidVirtualOffset) {
646 const ASTRecordLayout &Layout =
647 CGF.getContext().getASTRecordLayout(MD->getParent());
648 StaticOffset += Layout.getVBaseClassOffset(ML.VBase);
650 This = CGF.Builder.CreateBitCast(This, charPtrTy);
651 llvm::Value *VBaseOffset =
652 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
653 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
656 if (!StaticOffset.isZero()) {
657 assert(StaticOffset.isPositive());
658 This = CGF.Builder.CreateBitCast(This, charPtrTy);
660 // Non-virtual adjustment might result in a pointer outside the allocated
661 // object, e.g. if the final overrider class is laid out after the virtual
662 // base that declares a method in the most derived class.
663 // FIXME: Update the code that emits this adjustment in thunks prologues.
664 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
666 This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
667 StaticOffset.getQuantity());
673 static bool IsDeletingDtor(GlobalDecl GD) {
674 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
675 if (isa<CXXDestructorDecl>(MD)) {
676 return GD.getDtorType() == Dtor_Deleting;
681 void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
683 FunctionArgList &Params) {
684 BuildThisParam(CGF, Params);
686 ASTContext &Context = getContext();
687 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
688 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
689 ImplicitParamDecl *IsMostDerived
690 = ImplicitParamDecl::Create(Context, 0,
691 CGF.CurGD.getDecl()->getLocation(),
692 &Context.Idents.get("is_most_derived"),
694 Params.push_back(IsMostDerived);
695 getStructorImplicitParamDecl(CGF) = IsMostDerived;
696 } else if (IsDeletingDtor(CGF.CurGD)) {
697 ImplicitParamDecl *ShouldDelete
698 = ImplicitParamDecl::Create(Context, 0,
699 CGF.CurGD.getDecl()->getLocation(),
700 &Context.Idents.get("should_call_delete"),
702 Params.push_back(ShouldDelete);
703 getStructorImplicitParamDecl(CGF) = ShouldDelete;
707 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
708 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
709 GD = GD.getCanonicalDecl();
710 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
712 GlobalDecl LookupGD = GD;
713 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
714 // Complete destructors take a pointer to the complete object as a
715 // parameter, thus don't need this adjustment.
716 if (GD.getDtorType() == Dtor_Complete)
719 // There's no Dtor_Base in vftable but it shares the this adjustment with
720 // the deleting one, so look it up instead.
721 LookupGD = GlobalDecl(DD, Dtor_Deleting);
724 // In this ABI, every virtual function takes a pointer to one of the
725 // subobjects that first defines it as the 'this' parameter, rather than a
726 // pointer to ther final overrider subobject. Thus, we need to adjust it back
727 // to the final overrider subobject before use.
728 // See comments in the MicrosoftVFTableContext implementation for the details.
730 MicrosoftVTableContext::MethodVFTableLocation ML =
731 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
732 CharUnits Adjustment = ML.VFPtrOffset;
734 const ASTRecordLayout &DerivedLayout =
735 CGF.getContext().getASTRecordLayout(MD->getParent());
736 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
739 if (Adjustment.isZero())
742 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
743 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
744 *thisTy = This->getType();
746 This = CGF.Builder.CreateBitCast(This, charPtrTy);
747 assert(Adjustment.isPositive());
749 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
750 return CGF.Builder.CreateBitCast(This, thisTy);
753 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
756 /// If this is a function that the ABI specifies returns 'this', initialize
757 /// the return slot to 'this' at the start of the function.
759 /// Unlike the setting of return types, this is done within the ABI
760 /// implementation instead of by clients of CGCXXABI because:
761 /// 1) getThisValue is currently protected
762 /// 2) in theory, an ABI could implement 'this' returns some other way;
763 /// HasThisReturn only specifies a contract, not the implementation
764 if (HasThisReturn(CGF.CurGD))
765 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
767 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
768 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
769 assert(getStructorImplicitParamDecl(CGF) &&
770 "no implicit parameter for a constructor with virtual bases?");
771 getStructorImplicitParamValue(CGF)
772 = CGF.Builder.CreateLoad(
773 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
777 if (IsDeletingDtor(CGF.CurGD)) {
778 assert(getStructorImplicitParamDecl(CGF) &&
779 "no implicit parameter for a deleting destructor?");
780 getStructorImplicitParamValue(CGF)
781 = CGF.Builder.CreateLoad(
782 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
783 "should_call_delete");
787 void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
788 const CXXConstructorDecl *D,
793 CallExpr::const_arg_iterator ArgBeg,
794 CallExpr::const_arg_iterator ArgEnd) {
795 assert(Type == Ctor_Complete || Type == Ctor_Base);
796 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
798 llvm::Value *ImplicitParam = 0;
799 QualType ImplicitParamTy;
800 if (D->getParent()->getNumVBases()) {
801 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
802 ImplicitParamTy = getContext().IntTy;
805 // FIXME: Provide a source location here.
806 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
807 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
810 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
811 const CXXRecordDecl *RD) {
812 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
813 MicrosoftVTableContext::VFPtrListTy VFPtrs = VFTContext.getVFPtrOffsets(RD);
814 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
816 for (MicrosoftVTableContext::VFPtrListTy::iterator I = VFPtrs.begin(),
817 E = VFPtrs.end(); I != E; ++I) {
818 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, I->VFPtrFullOffset);
819 if (VTable->hasInitializer())
822 const VTableLayout &VTLayout =
823 VFTContext.getVFTableLayout(RD, I->VFPtrFullOffset);
824 llvm::Constant *Init = CGVT.CreateVTableInitializer(
825 RD, VTLayout.vtable_component_begin(),
826 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
827 VTLayout.getNumVTableThunks());
828 VTable->setInitializer(Init);
830 VTable->setLinkage(Linkage);
831 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
835 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
836 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
837 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
838 NeedsVirtualOffset = (NearestVBase != 0);
840 llvm::Value *VTableAddressPoint =
841 getAddrOfVTable(VTableClass, Base.getBaseOffset());
842 if (!VTableAddressPoint) {
843 assert(Base.getBase()->getNumVBases() &&
844 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
846 return VTableAddressPoint;
849 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
850 const CXXRecordDecl *RD, const VFPtrInfo &VFPtr,
851 SmallString<256> &Name) {
852 llvm::raw_svector_ostream Out(Name);
853 MangleContext.mangleCXXVFTable(RD, VFPtr.PathToMangle, Out);
856 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
857 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
858 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
859 assert(VTable && "Couldn't find a vftable for the given base?");
863 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
864 CharUnits VPtrOffset) {
865 // getAddrOfVTable may return 0 if asked to get an address of a vtable which
866 // shouldn't be used in the given record type. We want to cache this result in
867 // VFTablesMap, thus a simple zero check is not sufficient.
868 VFTableIdTy ID(RD, VPtrOffset);
869 VFTablesMapTy::iterator I;
871 llvm::tie(I, Inserted) = VFTablesMap.insert(
872 std::make_pair(ID, static_cast<llvm::GlobalVariable *>(0)));
876 llvm::GlobalVariable *&VTable = I->second;
878 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
879 const MicrosoftVTableContext::VFPtrListTy &VFPtrs =
880 VTContext.getVFPtrOffsets(RD);
882 if (DeferredVFTables.insert(RD)) {
883 // We haven't processed this record type before.
884 // Queue up this v-table for possible deferred emission.
885 CGM.addDeferredVTable(RD);
888 // Create all the vftables at once in order to make sure each vftable has
889 // a unique mangled name.
890 llvm::StringSet<> ObservedMangledNames;
891 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
892 SmallString<256> Name;
893 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
894 if (!ObservedMangledNames.insert(Name.str()))
895 llvm_unreachable("Already saw this mangling before?");
900 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
901 if (VFPtrs[J].VFPtrFullOffset != VPtrOffset)
904 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
906 VTContext.getVFTableLayout(RD, VFPtrs[J].VFPtrFullOffset)
907 .getNumVTableComponents());
909 SmallString<256> Name;
910 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
911 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
912 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
913 VTable->setUnnamedAddr(true);
920 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
924 GD = GD.getCanonicalDecl();
925 CGBuilderTy &Builder = CGF.Builder;
927 Ty = Ty->getPointerTo()->getPointerTo();
928 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This);
929 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
931 MicrosoftVTableContext::MethodVFTableLocation ML =
932 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
933 llvm::Value *VFuncPtr =
934 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
935 return Builder.CreateLoad(VFuncPtr);
938 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
939 const CXXDestructorDecl *Dtor,
940 CXXDtorType DtorType,
941 SourceLocation CallLoc,
943 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
945 // We have only one destructor in the vftable but can get both behaviors
946 // by passing an implicit int parameter.
947 GlobalDecl GD(Dtor, Dtor_Deleting);
948 const CGFunctionInfo *FInfo =
949 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
950 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
951 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
953 ASTContext &Context = CGF.getContext();
954 llvm::Value *ImplicitParam =
955 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
956 DtorType == Dtor_Deleting);
958 This = adjustThisArgumentForVirtualCall(CGF, GD, This);
959 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
960 ImplicitParam, Context.IntTy, 0, 0);
963 const VBTableVector &
964 MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
965 // At this layer, we can key the cache off of a single class, which is much
966 // easier than caching at the GlobalVariable layer.
967 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
969 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
970 VBTableVector &VBTables = I->second;
974 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
980 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
981 StringRef ThunkName) {
982 // If the thunk has been generated previously, just return it.
983 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
984 return cast<llvm::Function>(GV);
986 // Create the llvm::Function.
987 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
988 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
989 llvm::Function *ThunkFn =
990 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
991 ThunkName.str(), &CGM.getModule());
992 assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
994 ThunkFn->setLinkage(MD->isExternallyVisible()
995 ? llvm::GlobalValue::LinkOnceODRLinkage
996 : llvm::GlobalValue::InternalLinkage);
998 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
999 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1002 CodeGenFunction CGF(CGM);
1003 CGF.StartThunk(ThunkFn, MD, FnInfo);
1005 // Get to the Callee.
1006 llvm::Value *This = CGF.LoadCXXThis();
1007 llvm::Value *Callee = getVirtualFunctionPointer(CGF, MD, This, ThunkTy);
1009 // Make the call and return the result.
1010 CGF.EmitCallAndReturnForThunk(MD, Callee, 0);
1015 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1016 const VBTableVector &VBTables = EnumerateVBTables(RD);
1017 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1019 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
1021 I->EmitVBTableDefinition(CGM, RD, Linkage);
1025 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1027 const ThisAdjustment &TA) {
1031 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1033 if (!TA.Virtual.isEmpty()) {
1034 assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1035 // Adjust the this argument based on the vtordisp value.
1036 llvm::Value *VtorDispPtr =
1037 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1039 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1040 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1041 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1043 if (TA.Virtual.Microsoft.VBPtrOffset) {
1044 // If the final overrider is defined in a virtual base other than the one
1045 // that holds the vfptr, we have to use a vtordispex thunk which looks up
1046 // the vbtable of the derived class.
1047 assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1048 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1050 llvm::Value *VBaseOffset =
1051 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1052 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1053 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1057 if (TA.NonVirtual) {
1058 // Non-virtual adjustment might result in a pointer outside the allocated
1059 // object, e.g. if the final overrider class is laid out after the virtual
1060 // base that declares a method in the most derived class.
1061 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1064 // Don't need to bitcast back, the call CodeGen will handle this.
1069 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1070 const ReturnAdjustment &RA) {
1074 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1076 if (RA.Virtual.Microsoft.VBIndex) {
1077 assert(RA.Virtual.Microsoft.VBIndex > 0);
1079 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1081 llvm::Value *VBaseOffset =
1082 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1083 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1084 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1088 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1090 // Cast back to the original type.
1091 return CGF.Builder.CreateBitCast(V, Ret->getType());
1094 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1095 QualType elementType) {
1096 // Microsoft seems to completely ignore the possibility of a
1097 // two-argument usual deallocation function.
1098 return elementType.isDestructedType();
1101 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1102 // Microsoft seems to completely ignore the possibility of a
1103 // two-argument usual deallocation function.
1104 return expr->getAllocatedType().isDestructedType();
1107 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1108 // The array cookie is always a size_t; we then pad that out to the
1109 // alignment of the element type.
1110 ASTContext &Ctx = getContext();
1111 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1112 Ctx.getTypeAlignInChars(type));
1115 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1116 llvm::Value *allocPtr,
1117 CharUnits cookieSize) {
1118 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1119 llvm::Value *numElementsPtr =
1120 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1121 return CGF.Builder.CreateLoad(numElementsPtr);
1124 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1125 llvm::Value *newPtr,
1126 llvm::Value *numElements,
1127 const CXXNewExpr *expr,
1128 QualType elementType) {
1129 assert(requiresArrayCookie(expr));
1131 // The size of the cookie.
1132 CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1134 // Compute an offset to the cookie.
1135 llvm::Value *cookiePtr = newPtr;
1137 // Write the number of elements into the appropriate slot.
1138 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1139 llvm::Value *numElementsPtr
1140 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1141 CGF.Builder.CreateStore(numElements, numElementsPtr);
1143 // Finally, compute a pointer to the actual data buffer by skipping
1144 // over the cookie completely.
1145 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1146 cookieSize.getQuantity());
1149 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1150 llvm::GlobalVariable *GV,
1152 // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1153 // threadsafe. Since the user may be linking in inline functions compiled by
1154 // cl.exe, there's no reason to provide a false sense of security by using
1155 // critical sections here.
1158 CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1160 CGBuilderTy &Builder = CGF.Builder;
1161 llvm::IntegerType *GuardTy = CGF.Int32Ty;
1162 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1164 // Get the guard variable for this function if we have one already.
1165 GuardInfo &GI = GuardVariableMap[D.getDeclContext()];
1168 if (D.isExternallyVisible()) {
1169 // Externally visible variables have to be numbered in Sema to properly
1170 // handle unreachable VarDecls.
1171 BitIndex = getContext().getManglingNumber(&D);
1172 assert(BitIndex > 0);
1175 // Non-externally visible variables are numbered here in CodeGen.
1176 BitIndex = GI.BitIndex++;
1179 if (BitIndex >= 32) {
1180 if (D.isExternallyVisible())
1181 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1186 // Lazily create the i32 bitfield for this function.
1188 // Mangle the name for the guard.
1189 SmallString<256> GuardName;
1191 llvm::raw_svector_ostream Out(GuardName);
1192 getMangleContext().mangleStaticGuardVariable(&D, Out);
1196 // Create the guard variable with a zero-initializer. Just absorb linkage
1197 // and visibility from the guarded variable.
1198 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1199 GV->getLinkage(), Zero, GuardName.str());
1200 GI.Guard->setVisibility(GV->getVisibility());
1202 assert(GI.Guard->getLinkage() == GV->getLinkage() &&
1203 "static local from the same function had different linkage");
1206 // Pseudo code for the test:
1207 // if (!(GuardVar & MyGuardBit)) {
1208 // GuardVar |= MyGuardBit;
1209 // ... initialize the object ...;
1212 // Test our bit from the guard variable.
1213 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1214 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard);
1215 llvm::Value *IsInitialized =
1216 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1217 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1218 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1219 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1221 // Set our bit in the guard variable and emit the initializer and add a global
1222 // destructor if appropriate.
1223 CGF.EmitBlock(InitBlock);
1224 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard);
1225 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1226 Builder.CreateBr(EndBlock);
1229 CGF.EmitBlock(EndBlock);
1232 // Member pointer helpers.
1233 static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
1234 return Inheritance == MSIM_Unspecified;
1237 static bool hasOnlyOneField(bool IsMemberFunction,
1238 MSInheritanceModel Inheritance) {
1239 return Inheritance <= MSIM_SinglePolymorphic ||
1240 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
1243 // Only member pointers to functions need a this adjustment, since it can be
1244 // combined with the field offset for data pointers.
1245 static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
1246 MSInheritanceModel Inheritance) {
1247 return (IsMemberFunction && Inheritance >= MSIM_Multiple);
1250 static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
1251 return Inheritance >= MSIM_Virtual;
1254 // Use zero for the field offset of a null data member pointer if we can
1255 // guarantee that zero is not a valid field offset, or if the member pointer has
1256 // multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
1257 // use zero for null. If there are multiple fields, we can use zero even if it
1258 // is a valid field offset because null-ness testing will check the other
1260 static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
1261 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
1264 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1265 // Null-ness for function memptrs only depends on the first field, which is
1266 // the function pointer. The rest don't matter, so we can zero initialize.
1267 if (MPT->isMemberFunctionPointer())
1270 // The virtual base adjustment field is always -1 for null, so if we have one
1271 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
1272 // valid field offset.
1273 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1274 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1275 return (!hasVirtualBaseAdjustmentField(Inheritance) &&
1276 nullFieldOffsetIsZero(Inheritance));
1280 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1281 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1282 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1283 llvm::SmallVector<llvm::Type *, 4> fields;
1284 if (MPT->isMemberFunctionPointer())
1285 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
1287 fields.push_back(CGM.IntTy); // FieldOffset
1289 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1291 fields.push_back(CGM.IntTy);
1292 if (hasVBPtrOffsetField(Inheritance))
1293 fields.push_back(CGM.IntTy);
1294 if (hasVirtualBaseAdjustmentField(Inheritance))
1295 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
1297 if (fields.size() == 1)
1299 return llvm::StructType::get(CGM.getLLVMContext(), fields);
1302 void MicrosoftCXXABI::
1303 GetNullMemberPointerFields(const MemberPointerType *MPT,
1304 llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1305 assert(fields.empty());
1306 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1307 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1308 if (MPT->isMemberFunctionPointer()) {
1309 // FunctionPointerOrVirtualThunk
1310 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1312 if (nullFieldOffsetIsZero(Inheritance))
1313 fields.push_back(getZeroInt()); // FieldOffset
1315 fields.push_back(getAllOnesInt()); // FieldOffset
1318 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
1320 fields.push_back(getZeroInt());
1321 if (hasVBPtrOffsetField(Inheritance))
1322 fields.push_back(getZeroInt());
1323 if (hasVirtualBaseAdjustmentField(Inheritance))
1324 fields.push_back(getAllOnesInt());
1328 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1329 llvm::SmallVector<llvm::Constant *, 4> fields;
1330 GetNullMemberPointerFields(MPT, fields);
1331 if (fields.size() == 1)
1333 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1334 assert(Res->getType() == ConvertMemberPointerType(MPT));
1339 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1340 bool IsMemberFunction,
1341 const CXXRecordDecl *RD,
1342 CharUnits NonVirtualBaseAdjustment)
1344 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1346 // Single inheritance class member pointer are represented as scalars instead
1348 if (hasOnlyOneField(IsMemberFunction, Inheritance))
1351 llvm::SmallVector<llvm::Constant *, 4> fields;
1352 fields.push_back(FirstField);
1354 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
1355 fields.push_back(llvm::ConstantInt::get(
1356 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
1358 if (hasVBPtrOffsetField(Inheritance)) {
1359 CharUnits Offs = CharUnits::Zero();
1360 if (RD->getNumVBases())
1361 Offs = GetVBPtrOffsetFromBases(RD);
1362 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
1365 // The rest of the fields are adjusted by conversions to a more derived class.
1366 if (hasVirtualBaseAdjustmentField(Inheritance))
1367 fields.push_back(getZeroInt());
1369 return llvm::ConstantStruct::getAnon(fields);
1373 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1375 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1376 llvm::Constant *FirstField =
1377 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
1378 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1382 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1383 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1386 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1388 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1389 const ValueDecl *MPD = MP.getMemberPointerDecl();
1391 return EmitNullMemberPointer(MPT);
1393 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1395 // FIXME PR15713: Support virtual inheritance paths.
1397 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1398 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
1399 MD, ThisAdjustment);
1401 CharUnits FieldOffset =
1402 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1403 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1407 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1408 const CXXMethodDecl *MD,
1409 CharUnits NonVirtualBaseAdjustment) {
1410 assert(MD->isInstance() && "Member function must not be static!");
1411 MD = MD->getCanonicalDecl();
1412 CodeGenTypes &Types = CGM.getTypes();
1414 llvm::Constant *FirstField;
1415 if (!MD->isVirtual()) {
1416 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1418 // Check whether the function has a computable LLVM signature.
1419 if (Types.isFuncTypeConvertible(FPT)) {
1420 // The function has a computable LLVM signature; use the correct type.
1421 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1423 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1424 // function type is incomplete.
1427 FirstField = CGM.GetAddrOfFunction(MD, Ty);
1428 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1430 MicrosoftVTableContext::MethodVFTableLocation ML =
1431 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1432 if (MD->isVariadic()) {
1433 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1434 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1435 } else if (!CGM.getTypes().isFuncTypeConvertible(
1436 MD->getType()->castAs<FunctionType>())) {
1437 CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1438 "incomplete return or parameter type");
1439 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1440 } else if (ML.VBase) {
1441 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1442 "member function in virtual base class");
1443 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1445 SmallString<256> ThunkName;
1446 CharUnits PointerWidth = getContext().toCharUnitsFromBits(
1447 getContext().getTargetInfo().getPointerWidth(0));
1448 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
1449 llvm::raw_svector_ostream Out(ThunkName);
1450 getMangleContext().mangleVirtualMemPtrThunk(MD, OffsetInVFTable, Out);
1453 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ThunkName.str());
1454 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1458 // The rest of the fields are common with data member pointers.
1459 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1460 NonVirtualBaseAdjustment);
1463 /// Member pointers are the same if they're either bitwise identical *or* both
1464 /// null. Null-ness for function members is determined by the first field,
1465 /// while for data member pointers we must compare all fields.
1467 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1470 const MemberPointerType *MPT,
1472 CGBuilderTy &Builder = CGF.Builder;
1474 // Handle != comparisons by switching the sense of all boolean operations.
1475 llvm::ICmpInst::Predicate Eq;
1476 llvm::Instruction::BinaryOps And, Or;
1478 Eq = llvm::ICmpInst::ICMP_NE;
1479 And = llvm::Instruction::Or;
1480 Or = llvm::Instruction::And;
1482 Eq = llvm::ICmpInst::ICMP_EQ;
1483 And = llvm::Instruction::And;
1484 Or = llvm::Instruction::Or;
1487 // If this is a single field member pointer (single inheritance), this is a
1489 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1490 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1491 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
1492 return Builder.CreateICmp(Eq, L, R);
1494 // Compare the first field.
1495 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1496 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1497 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1499 // Compare everything other than the first field.
1500 llvm::Value *Res = 0;
1501 llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1502 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1503 llvm::Value *LF = Builder.CreateExtractValue(L, I);
1504 llvm::Value *RF = Builder.CreateExtractValue(R, I);
1505 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1507 Res = Builder.CreateBinOp(And, Res, Cmp);
1512 // Check if the first field is 0 if this is a function pointer.
1513 if (MPT->isMemberFunctionPointer()) {
1514 // (l1 == r1 && ...) || l0 == 0
1515 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1516 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1517 Res = Builder.CreateBinOp(Or, Res, IsZero);
1520 // Combine the comparison of the first field, which must always be true for
1521 // this comparison to succeeed.
1522 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1526 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1527 llvm::Value *MemPtr,
1528 const MemberPointerType *MPT) {
1529 CGBuilderTy &Builder = CGF.Builder;
1530 llvm::SmallVector<llvm::Constant *, 4> fields;
1531 // We only need one field for member functions.
1532 if (MPT->isMemberFunctionPointer())
1533 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1535 GetNullMemberPointerFields(MPT, fields);
1536 assert(!fields.empty());
1537 llvm::Value *FirstField = MemPtr;
1538 if (MemPtr->getType()->isStructTy())
1539 FirstField = Builder.CreateExtractValue(MemPtr, 0);
1540 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
1542 // For function member pointers, we only need to test the function pointer
1543 // field. The other fields if any can be garbage.
1544 if (MPT->isMemberFunctionPointer())
1547 // Otherwise, emit a series of compares and combine the results.
1548 for (int I = 1, E = fields.size(); I < E; ++I) {
1549 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1550 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1551 Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
1556 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1557 llvm::Constant *Val) {
1558 // Function pointers are null if the pointer in the first field is null.
1559 if (MPT->isMemberFunctionPointer()) {
1560 llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1561 Val->getAggregateElement(0U) : Val;
1562 return FirstField->isNullValue();
1565 // If it's not a function pointer and it's zero initializable, we can easily
1567 if (isZeroInitializable(MPT) && Val->isNullValue())
1570 // Otherwise, break down all the fields for comparison. Hopefully these
1571 // little Constants are reused, while a big null struct might not be.
1572 llvm::SmallVector<llvm::Constant *, 4> Fields;
1573 GetNullMemberPointerFields(MPT, Fields);
1574 if (Fields.size() == 1) {
1575 assert(Val->getType()->isIntegerTy());
1576 return Val == Fields[0];
1580 for (I = 0, E = Fields.size(); I != E; ++I) {
1581 if (Val->getAggregateElement(I) != Fields[I])
1588 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1590 llvm::Value *VBPtrOffset,
1591 llvm::Value *VBTableOffset,
1592 llvm::Value **VBPtrOut) {
1593 CGBuilderTy &Builder = CGF.Builder;
1594 // Load the vbtable pointer from the vbptr in the instance.
1595 This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1596 llvm::Value *VBPtr =
1597 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1598 if (VBPtrOut) *VBPtrOut = VBPtr;
1599 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1600 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1602 // Load an i32 offset from the vb-table.
1603 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1604 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1605 return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1608 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
1611 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
1612 const CXXRecordDecl *RD, llvm::Value *Base,
1613 llvm::Value *VBTableOffset,
1614 llvm::Value *VBPtrOffset) {
1615 CGBuilderTy &Builder = CGF.Builder;
1616 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1617 llvm::BasicBlock *OriginalBB = 0;
1618 llvm::BasicBlock *SkipAdjustBB = 0;
1619 llvm::BasicBlock *VBaseAdjustBB = 0;
1621 // In the unspecified inheritance model, there might not be a vbtable at all,
1622 // in which case we need to skip the virtual base lookup. If there is a
1623 // vbtable, the first entry is a no-op entry that gives back the original
1624 // base, so look for a virtual base adjustment offset of zero.
1626 OriginalBB = Builder.GetInsertBlock();
1627 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1628 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1629 llvm::Value *IsVirtual =
1630 Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
1632 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1633 CGF.EmitBlock(VBaseAdjustBB);
1636 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1637 // know the vbptr offset.
1639 CharUnits offs = CharUnits::Zero();
1640 if (RD->getNumVBases()) {
1641 offs = GetVBPtrOffsetFromBases(RD);
1643 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1645 llvm::Value *VBPtr = 0;
1646 llvm::Value *VBaseOffs =
1647 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
1648 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1650 // Merge control flow with the case where we didn't have to adjust.
1651 if (VBaseAdjustBB) {
1652 Builder.CreateBr(SkipAdjustBB);
1653 CGF.EmitBlock(SkipAdjustBB);
1654 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1655 Phi->addIncoming(Base, OriginalBB);
1656 Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1659 return AdjustedBase;
1663 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1665 llvm::Value *MemPtr,
1666 const MemberPointerType *MPT) {
1667 assert(MPT->isMemberDataPointer());
1668 unsigned AS = Base->getType()->getPointerAddressSpace();
1670 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1671 CGBuilderTy &Builder = CGF.Builder;
1672 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1673 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1675 // Extract the fields we need, regardless of model. We'll apply them if we
1677 llvm::Value *FieldOffset = MemPtr;
1678 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1679 llvm::Value *VBPtrOffset = 0;
1680 if (MemPtr->getType()->isStructTy()) {
1681 // We need to extract values.
1683 FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1684 if (hasVBPtrOffsetField(Inheritance))
1685 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1686 if (hasVirtualBaseAdjustmentField(Inheritance))
1687 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1690 if (VirtualBaseAdjustmentOffset) {
1691 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1695 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
1697 // Cast the address to the appropriate pointer type, adopting the address
1698 // space of the base pointer.
1699 return Builder.CreateBitCast(Addr, PType);
1702 static MSInheritanceModel
1703 getInheritanceFromMemptr(const MemberPointerType *MPT) {
1704 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1708 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1711 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1712 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1713 E->getCastKind() == CK_ReinterpretMemberPointer);
1715 // Use constant emission if we can.
1716 if (isa<llvm::Constant>(Src))
1717 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1719 // We may be adding or dropping fields from the member pointer, so we need
1720 // both types and the inheritance models of both records.
1721 const MemberPointerType *SrcTy =
1722 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1723 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1724 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1725 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1726 bool IsFunc = SrcTy->isMemberFunctionPointer();
1728 // If the classes use the same null representation, reinterpret_cast is a nop.
1729 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1730 if (IsReinterpret && (IsFunc ||
1731 nullFieldOffsetIsZero(SrcInheritance) ==
1732 nullFieldOffsetIsZero(DstInheritance)))
1735 CGBuilderTy &Builder = CGF.Builder;
1737 // Branch past the conversion if Src is null.
1738 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1739 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1741 // C++ 5.2.10p9: The null member pointer value is converted to the null member
1742 // pointer value of the destination type.
1743 if (IsReinterpret) {
1744 // For reinterpret casts, sema ensures that src and dst are both functions
1745 // or data and have the same size, which means the LLVM types should match.
1746 assert(Src->getType() == DstNull->getType());
1747 return Builder.CreateSelect(IsNotNull, Src, DstNull);
1750 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1751 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1752 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1753 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1754 CGF.EmitBlock(ConvertBB);
1757 llvm::Value *FirstField = Src;
1758 llvm::Value *NonVirtualBaseAdjustment = 0;
1759 llvm::Value *VirtualBaseAdjustmentOffset = 0;
1760 llvm::Value *VBPtrOffset = 0;
1761 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1762 // We need to extract values.
1764 FirstField = Builder.CreateExtractValue(Src, I++);
1765 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1766 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1767 if (hasVBPtrOffsetField(SrcInheritance))
1768 VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1769 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1770 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1773 // For data pointers, we adjust the field offset directly. For functions, we
1774 // have a separate field.
1775 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1777 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1778 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1779 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1780 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1781 NVAdjustField = getZeroInt();
1782 if (isDerivedToBase)
1783 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1785 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1788 // FIXME PR15713: Support conversions through virtually derived classes.
1790 // Recompose dst from the null struct and the adjusted fields from src.
1792 if (hasOnlyOneField(IsFunc, DstInheritance)) {
1795 Dst = llvm::UndefValue::get(DstNull->getType());
1797 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1798 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1799 Dst = Builder.CreateInsertValue(
1800 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1801 if (hasVBPtrOffsetField(DstInheritance))
1802 Dst = Builder.CreateInsertValue(
1803 Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1804 if (hasVirtualBaseAdjustmentField(DstInheritance))
1805 Dst = Builder.CreateInsertValue(
1806 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1808 Builder.CreateBr(ContinueBB);
1810 // In the continuation, choose between DstNull and Dst.
1811 CGF.EmitBlock(ContinueBB);
1812 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1813 Phi->addIncoming(DstNull, OriginalBB);
1814 Phi->addIncoming(Dst, ConvertBB);
1819 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1820 llvm::Constant *Src) {
1821 const MemberPointerType *SrcTy =
1822 E->getSubExpr()->getType()->castAs<MemberPointerType>();
1823 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1825 // If src is null, emit a new null for dst. We can't return src because dst
1826 // might have a new representation.
1827 if (MemberPointerConstantIsNull(SrcTy, Src))
1828 return EmitNullMemberPointer(DstTy);
1830 // We don't need to do anything for reinterpret_casts of non-null member
1831 // pointers. We should only get here when the two type representations have
1833 if (E->getCastKind() == CK_ReinterpretMemberPointer)
1836 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1837 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1840 llvm::Constant *FirstField = Src;
1841 llvm::Constant *NonVirtualBaseAdjustment = 0;
1842 llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1843 llvm::Constant *VBPtrOffset = 0;
1844 bool IsFunc = SrcTy->isMemberFunctionPointer();
1845 if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1846 // We need to extract values.
1848 FirstField = Src->getAggregateElement(I++);
1849 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1850 NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1851 if (hasVBPtrOffsetField(SrcInheritance))
1852 VBPtrOffset = Src->getAggregateElement(I++);
1853 if (hasVirtualBaseAdjustmentField(SrcInheritance))
1854 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1857 // For data pointers, we adjust the field offset directly. For functions, we
1858 // have a separate field.
1859 llvm::Constant *Adj = getMemberPointerAdjustment(E);
1861 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1862 llvm::Constant *&NVAdjustField =
1863 IsFunc ? NonVirtualBaseAdjustment : FirstField;
1864 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1865 if (!NVAdjustField) // If this field didn't exist in src, it's zero.
1866 NVAdjustField = getZeroInt();
1867 if (IsDerivedToBase)
1868 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1870 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1873 // FIXME PR15713: Support conversions through virtually derived classes.
1875 // Recompose dst from the null struct and the adjusted fields from src.
1876 if (hasOnlyOneField(IsFunc, DstInheritance))
1879 llvm::SmallVector<llvm::Constant *, 4> Fields;
1880 Fields.push_back(FirstField);
1881 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1882 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1883 if (hasVBPtrOffsetField(DstInheritance))
1884 Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1885 if (hasVirtualBaseAdjustmentField(DstInheritance))
1886 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1887 return llvm::ConstantStruct::getAnon(Fields);
1891 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1893 llvm::Value *MemPtr,
1894 const MemberPointerType *MPT) {
1895 assert(MPT->isMemberFunctionPointer());
1896 const FunctionProtoType *FPT =
1897 MPT->getPointeeType()->castAs<FunctionProtoType>();
1898 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1899 llvm::FunctionType *FTy =
1900 CGM.getTypes().GetFunctionType(
1901 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1902 CGBuilderTy &Builder = CGF.Builder;
1904 MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1906 // Extract the fields we need, regardless of model. We'll apply them if we
1908 llvm::Value *FunctionPointer = MemPtr;
1909 llvm::Value *NonVirtualBaseAdjustment = NULL;
1910 llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1911 llvm::Value *VBPtrOffset = NULL;
1912 if (MemPtr->getType()->isStructTy()) {
1913 // We need to extract values.
1915 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
1916 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1917 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
1918 if (hasVBPtrOffsetField(Inheritance))
1919 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1920 if (hasVirtualBaseAdjustmentField(Inheritance))
1921 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1924 if (VirtualBaseAdjustmentOffset) {
1925 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1929 if (NonVirtualBaseAdjustment) {
1930 // Apply the adjustment and cast back to the original struct type.
1931 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1932 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1933 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1936 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1939 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
1940 return new MicrosoftCXXABI(CGM);