1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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 13 // of Microsoft. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "CGCXXABI.h" 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 25 using namespace clang; 26 using namespace CodeGen; 27 28 namespace { 29 30 class MicrosoftCXXABI : public CGCXXABI { 31 public: 32 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {} 33 34 bool HasThisReturn(GlobalDecl GD) const; 35 36 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const { 37 // Structures that are not C++03 PODs are always indirect. 38 return !RD->isPOD(); 39 } 40 41 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const { 42 if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor()) 43 return RAA_DirectInMemory; 44 return RAA_Default; 45 } 46 47 StringRef GetPureVirtualCallName() { return "_purecall"; } 48 // No known support for deleted functions in MSVC yet, so this choice is 49 // arbitrary. 50 StringRef GetDeletedVirtualCallName() { return "_purecall"; } 51 52 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 53 llvm::Value *ptr, 54 QualType type); 55 56 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF, 57 llvm::Value *This, 58 const CXXRecordDecl *ClassDecl, 59 const CXXRecordDecl *BaseClassDecl); 60 61 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 62 CXXCtorType Type, 63 CanQualType &ResTy, 64 SmallVectorImpl<CanQualType> &ArgTys); 65 66 llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 67 const CXXRecordDecl *RD); 68 69 void EmitCXXConstructors(const CXXConstructorDecl *D); 70 71 // Background on MSVC destructors 72 // ============================== 73 // 74 // Both Itanium and MSVC ABIs have destructor variants. The variant names 75 // roughly correspond in the following way: 76 // Itanium Microsoft 77 // Base -> no name, just ~Class 78 // Complete -> vbase destructor 79 // Deleting -> scalar deleting destructor 80 // vector deleting destructor 81 // 82 // The base and complete destructors are the same as in Itanium, although the 83 // complete destructor does not accept a VTT parameter when there are virtual 84 // bases. A separate mechanism involving vtordisps is used to ensure that 85 // virtual methods of destroyed subobjects are not called. 86 // 87 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 88 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 89 // pointer points to an array. The scalar deleting destructor assumes that 90 // bit 2 is zero, and therefore does not contain a loop. 91 // 92 // For virtual destructors, only one entry is reserved in the vftable, and it 93 // always points to the vector deleting destructor. The vector deleting 94 // destructor is the most general, so it can be used to destroy objects in 95 // place, delete single heap objects, or delete arrays. 96 // 97 // A TU defining a non-inline destructor is only guaranteed to emit a base 98 // destructor, and all of the other variants are emitted on an as-needed basis 99 // in COMDATs. Because a non-base destructor can be emitted in a TU that 100 // lacks a definition for the destructor, non-base destructors must always 101 // delegate to or alias the base destructor. 102 103 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 104 CXXDtorType Type, 105 CanQualType &ResTy, 106 SmallVectorImpl<CanQualType> &ArgTys); 107 108 /// Non-base dtors should be emitted as delegating thunks in this ABI. 109 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 110 CXXDtorType DT) const { 111 return DT != Dtor_Base; 112 } 113 114 void EmitCXXDestructors(const CXXDestructorDecl *D); 115 116 const CXXRecordDecl *getThisArgumentTypeForMethod(const CXXMethodDecl *MD) { 117 MD = MD->getCanonicalDecl(); 118 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 119 MicrosoftVFTableContext::MethodVFTableLocation ML = 120 CGM.getVFTableContext().getMethodVFTableLocation(MD); 121 // The vbases might be ordered differently in the final overrider object 122 // and the complete object, so the "this" argument may sometimes point to 123 // memory that has no particular type (e.g. past the complete object). 124 // In this case, we just use a generic pointer type. 125 // FIXME: might want to have a more precise type in the non-virtual 126 // multiple inheritance case. 127 if (ML.VBase || !ML.VFTableOffset.isZero()) 128 return 0; 129 } 130 return MD->getParent(); 131 } 132 133 llvm::Value *adjustThisArgumentForVirtualCall(CodeGenFunction &CGF, 134 GlobalDecl GD, 135 llvm::Value *This); 136 137 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 138 QualType &ResTy, 139 FunctionArgList &Params); 140 141 llvm::Value *adjustThisParameterInVirtualFunctionPrologue( 142 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This); 143 144 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 145 146 void EmitConstructorCall(CodeGenFunction &CGF, 147 const CXXConstructorDecl *D, CXXCtorType Type, 148 bool ForVirtualBase, bool Delegating, 149 llvm::Value *This, 150 CallExpr::const_arg_iterator ArgBeg, 151 CallExpr::const_arg_iterator ArgEnd); 152 153 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 154 llvm::Value *This, llvm::Type *Ty); 155 156 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 157 const CXXDestructorDecl *Dtor, 158 CXXDtorType DtorType, SourceLocation CallLoc, 159 llvm::Value *This); 160 161 void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage, 162 const CXXRecordDecl *RD); 163 164 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 165 llvm::GlobalVariable *DeclPtr, 166 bool PerformInit); 167 168 // ==== Notes on array cookies ========= 169 // 170 // MSVC seems to only use cookies when the class has a destructor; a 171 // two-argument usual array deallocation function isn't sufficient. 172 // 173 // For example, this code prints "100" and "1": 174 // struct A { 175 // char x; 176 // void *operator new[](size_t sz) { 177 // printf("%u\n", sz); 178 // return malloc(sz); 179 // } 180 // void operator delete[](void *p, size_t sz) { 181 // printf("%u\n", sz); 182 // free(p); 183 // } 184 // }; 185 // int main() { 186 // A *p = new A[100]; 187 // delete[] p; 188 // } 189 // Whereas it prints "104" and "104" if you give A a destructor. 190 191 bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType); 192 bool requiresArrayCookie(const CXXNewExpr *expr); 193 CharUnits getArrayCookieSizeImpl(QualType type); 194 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 195 llvm::Value *NewPtr, 196 llvm::Value *NumElements, 197 const CXXNewExpr *expr, 198 QualType ElementType); 199 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 200 llvm::Value *allocPtr, 201 CharUnits cookieSize); 202 203 private: 204 llvm::Constant *getZeroInt() { 205 return llvm::ConstantInt::get(CGM.IntTy, 0); 206 } 207 208 llvm::Constant *getAllOnesInt() { 209 return llvm::Constant::getAllOnesValue(CGM.IntTy); 210 } 211 212 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) { 213 return C ? C : getZeroInt(); 214 } 215 216 llvm::Value *getValueOrZeroInt(llvm::Value *C) { 217 return C ? C : getZeroInt(); 218 } 219 220 void 221 GetNullMemberPointerFields(const MemberPointerType *MPT, 222 llvm::SmallVectorImpl<llvm::Constant *> &fields); 223 224 /// \brief Finds the offset from the base of RD to the vbptr it uses, even if 225 /// it is reusing a vbptr from a non-virtual base. RD must have morally 226 /// virtual bases. 227 CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD); 228 229 /// \brief Shared code for virtual base adjustment. Returns the offset from 230 /// the vbptr to the virtual base. Optionally returns the address of the 231 /// vbptr itself. 232 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 233 llvm::Value *Base, 234 llvm::Value *VBPtrOffset, 235 llvm::Value *VBTableOffset, 236 llvm::Value **VBPtr = 0); 237 238 /// \brief Performs a full virtual base adjustment. Used to dereference 239 /// pointers to members of virtual bases. 240 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD, 241 llvm::Value *Base, 242 llvm::Value *VirtualBaseAdjustmentOffset, 243 llvm::Value *VBPtrOffset /* optional */); 244 245 /// \brief Emits a full member pointer with the fields common to data and 246 /// function member pointers. 247 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 248 bool IsMemberFunction, 249 const CXXRecordDecl *RD, 250 CharUnits NonVirtualBaseAdjustment); 251 252 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD, 253 const CXXMethodDecl *MD, 254 CharUnits NonVirtualBaseAdjustment); 255 256 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 257 llvm::Constant *MP); 258 259 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type. 260 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 261 262 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables(). 263 const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD); 264 265 public: 266 virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 267 268 virtual bool isZeroInitializable(const MemberPointerType *MPT); 269 270 virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 271 272 virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 273 CharUnits offset); 274 virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 275 virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT); 276 277 virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 278 llvm::Value *L, 279 llvm::Value *R, 280 const MemberPointerType *MPT, 281 bool Inequality); 282 283 virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 284 llvm::Value *MemPtr, 285 const MemberPointerType *MPT); 286 287 virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 288 llvm::Value *Base, 289 llvm::Value *MemPtr, 290 const MemberPointerType *MPT); 291 292 virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 293 const CastExpr *E, 294 llvm::Value *Src); 295 296 virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 297 llvm::Constant *Src); 298 299 virtual llvm::Value * 300 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 301 llvm::Value *&This, 302 llvm::Value *MemPtr, 303 const MemberPointerType *MPT); 304 305 private: 306 /// VBTables - All the vbtables which have been referenced. 307 llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap; 308 309 /// Info on the global variable used to guard initialization of static locals. 310 /// The BitIndex field is only used for externally invisible declarations. 311 struct GuardInfo { 312 GuardInfo() : Guard(0), BitIndex(0) {} 313 llvm::GlobalVariable *Guard; 314 unsigned BitIndex; 315 }; 316 317 /// Map from DeclContext to the current guard variable. We assume that the 318 /// AST is visited in source code order. 319 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 320 }; 321 322 } 323 324 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 325 llvm::Value *ptr, 326 QualType type) { 327 // FIXME: implement 328 return ptr; 329 } 330 331 /// \brief Finds the first non-virtual base of RD that has virtual bases. If RD 332 /// doesn't have a vbptr, it will reuse the vbptr of the returned class. 333 static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) { 334 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 335 E = RD->bases_end(); I != E; ++I) { 336 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 337 if (!I->isVirtual() && Base->getNumVBases() > 0) 338 return Base; 339 } 340 llvm_unreachable("RD must have an nv base with vbases"); 341 } 342 343 CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) { 344 assert(RD->getNumVBases()); 345 CharUnits Total = CharUnits::Zero(); 346 while (RD) { 347 const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD); 348 CharUnits VBPtrOffset = RDLayout.getVBPtrOffset(); 349 // -1 is the sentinel for no vbptr. 350 if (VBPtrOffset != CharUnits::fromQuantity(-1)) { 351 Total += VBPtrOffset; 352 break; 353 } 354 RD = FindFirstNVBaseWithVBases(RD); 355 Total += RDLayout.getBaseClassOffset(RD); 356 } 357 return Total; 358 } 359 360 llvm::Value * 361 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 362 llvm::Value *This, 363 const CXXRecordDecl *ClassDecl, 364 const CXXRecordDecl *BaseClassDecl) { 365 int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity(); 366 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 367 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy); 368 CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl); 369 llvm::Value *VBTableOffset = 370 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 371 372 llvm::Value *VBPtrToNewBase = 373 GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset); 374 VBPtrToNewBase = 375 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 376 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 377 } 378 379 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 380 return isa<CXXConstructorDecl>(GD.getDecl()); 381 } 382 383 void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 384 CXXCtorType Type, 385 CanQualType &ResTy, 386 SmallVectorImpl<CanQualType> &ArgTys) { 387 // 'this' parameter and 'this' return are already in place 388 389 const CXXRecordDecl *Class = Ctor->getParent(); 390 if (Class->getNumVBases()) { 391 // Constructors of classes with virtual bases take an implicit parameter. 392 ArgTys.push_back(CGM.getContext().IntTy); 393 } 394 } 395 396 llvm::BasicBlock * 397 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 398 const CXXRecordDecl *RD) { 399 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 400 assert(IsMostDerivedClass && 401 "ctor for a class with virtual bases must have an implicit parameter"); 402 llvm::Value *IsCompleteObject = 403 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 404 405 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 406 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 407 CGF.Builder.CreateCondBr(IsCompleteObject, 408 CallVbaseCtorsBB, SkipVbaseCtorsBB); 409 410 CGF.EmitBlock(CallVbaseCtorsBB); 411 412 // Fill in the vbtable pointers here. 413 EmitVBPtrStores(CGF, RD); 414 415 // CGF will put the base ctor calls in this basic block for us later. 416 417 return SkipVbaseCtorsBB; 418 } 419 420 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 421 // There's only one constructor type in this ABI. 422 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 423 } 424 425 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 426 const CXXRecordDecl *RD) { 427 llvm::Value *ThisInt8Ptr = 428 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8"); 429 430 const VBTableVector &VBTables = EnumerateVBTables(RD); 431 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end(); 432 I != E; ++I) { 433 const ASTRecordLayout &SubobjectLayout = 434 CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase()); 435 uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() + 436 SubobjectLayout.getVBPtrOffset()).getQuantity(); 437 llvm::Value *VBPtr = 438 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs); 439 VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0), 440 "vbptr." + I->ReusingBase->getName()); 441 CGF.Builder.CreateStore(I->GV, VBPtr); 442 } 443 } 444 445 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 446 CXXDtorType Type, 447 CanQualType &ResTy, 448 SmallVectorImpl<CanQualType> &ArgTys) { 449 // 'this' is already in place 450 451 // TODO: 'for base' flag 452 453 if (Type == Dtor_Deleting) { 454 // The scalar deleting destructor takes an implicit int parameter. 455 ArgTys.push_back(CGM.getContext().IntTy); 456 } 457 } 458 459 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 460 // The TU defining a dtor is only guaranteed to emit a base destructor. All 461 // other destructor variants are delegating thunks. 462 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 463 } 464 465 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualCall( 466 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 467 GD = GD.getCanonicalDecl(); 468 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 469 if (isa<CXXDestructorDecl>(MD)) 470 return This; 471 472 MicrosoftVFTableContext::MethodVFTableLocation ML = 473 CGM.getVFTableContext().getMethodVFTableLocation(GD); 474 475 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 476 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 477 if (ML.VBase) { 478 This = CGF.Builder.CreateBitCast(This, charPtrTy); 479 llvm::Value *VBaseOffset = CGM.getCXXABI() 480 .GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase); 481 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset); 482 } 483 CharUnits StaticOffset = ML.VFTableOffset; 484 if (!StaticOffset.isZero()) { 485 assert(StaticOffset.isPositive()); 486 This = CGF.Builder.CreateBitCast(This, charPtrTy); 487 This = CGF.Builder 488 .CreateConstInBoundsGEP1_64(This, StaticOffset.getQuantity()); 489 } 490 return This; 491 } 492 493 static bool IsDeletingDtor(GlobalDecl GD) { 494 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 495 if (isa<CXXDestructorDecl>(MD)) { 496 return GD.getDtorType() == Dtor_Deleting; 497 } 498 return false; 499 } 500 501 void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 502 QualType &ResTy, 503 FunctionArgList &Params) { 504 BuildThisParam(CGF, Params); 505 506 ASTContext &Context = getContext(); 507 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 508 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 509 ImplicitParamDecl *IsMostDerived 510 = ImplicitParamDecl::Create(Context, 0, 511 CGF.CurGD.getDecl()->getLocation(), 512 &Context.Idents.get("is_most_derived"), 513 Context.IntTy); 514 Params.push_back(IsMostDerived); 515 getStructorImplicitParamDecl(CGF) = IsMostDerived; 516 } else if (IsDeletingDtor(CGF.CurGD)) { 517 ImplicitParamDecl *ShouldDelete 518 = ImplicitParamDecl::Create(Context, 0, 519 CGF.CurGD.getDecl()->getLocation(), 520 &Context.Idents.get("should_call_delete"), 521 Context.IntTy); 522 Params.push_back(ShouldDelete); 523 getStructorImplicitParamDecl(CGF) = ShouldDelete; 524 } 525 } 526 527 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue( 528 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 529 GD = GD.getCanonicalDecl(); 530 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 531 if (isa<CXXDestructorDecl>(MD)) 532 return This; 533 534 // In this ABI, every virtual function takes a pointer to one of the 535 // subobjects that first defines it as the 'this' parameter, rather than a 536 // pointer to ther final overrider subobject. Thus, we need to adjust it back 537 // to the final overrider subobject before use. 538 // See comments in the MicrosoftVFTableContext implementation for the details. 539 540 MicrosoftVFTableContext::MethodVFTableLocation ML = 541 CGM.getVFTableContext().getMethodVFTableLocation(GD); 542 CharUnits Adjustment = ML.VFTableOffset; 543 if (ML.VBase) { 544 const ASTRecordLayout &DerivedLayout = 545 CGF.getContext().getASTRecordLayout(MD->getParent()); 546 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 547 } 548 549 if (Adjustment.isZero()) 550 return This; 551 552 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 553 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 554 *thisTy = This->getType(); 555 556 This = CGF.Builder.CreateBitCast(This, charPtrTy); 557 assert(Adjustment.isPositive()); 558 This = CGF.Builder.CreateConstGEP1_64(This, -Adjustment.getQuantity()); 559 return CGF.Builder.CreateBitCast(This, thisTy); 560 } 561 562 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 563 EmitThisParam(CGF); 564 565 /// If this is a function that the ABI specifies returns 'this', initialize 566 /// the return slot to 'this' at the start of the function. 567 /// 568 /// Unlike the setting of return types, this is done within the ABI 569 /// implementation instead of by clients of CGCXXABI because: 570 /// 1) getThisValue is currently protected 571 /// 2) in theory, an ABI could implement 'this' returns some other way; 572 /// HasThisReturn only specifies a contract, not the implementation 573 if (HasThisReturn(CGF.CurGD)) 574 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 575 576 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 577 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 578 assert(getStructorImplicitParamDecl(CGF) && 579 "no implicit parameter for a constructor with virtual bases?"); 580 getStructorImplicitParamValue(CGF) 581 = CGF.Builder.CreateLoad( 582 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 583 "is_most_derived"); 584 } 585 586 if (IsDeletingDtor(CGF.CurGD)) { 587 assert(getStructorImplicitParamDecl(CGF) && 588 "no implicit parameter for a deleting destructor?"); 589 getStructorImplicitParamValue(CGF) 590 = CGF.Builder.CreateLoad( 591 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 592 "should_call_delete"); 593 } 594 } 595 596 void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF, 597 const CXXConstructorDecl *D, 598 CXXCtorType Type, 599 bool ForVirtualBase, 600 bool Delegating, 601 llvm::Value *This, 602 CallExpr::const_arg_iterator ArgBeg, 603 CallExpr::const_arg_iterator ArgEnd) { 604 assert(Type == Ctor_Complete || Type == Ctor_Base); 605 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete); 606 607 llvm::Value *ImplicitParam = 0; 608 QualType ImplicitParamTy; 609 if (D->getParent()->getNumVBases()) { 610 ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 611 ImplicitParamTy = getContext().IntTy; 612 } 613 614 // FIXME: Provide a source location here. 615 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This, 616 ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd); 617 } 618 619 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 620 GlobalDecl GD, 621 llvm::Value *This, 622 llvm::Type *Ty) { 623 GD = GD.getCanonicalDecl(); 624 CGBuilderTy &Builder = CGF.Builder; 625 626 Ty = Ty->getPointerTo()->getPointerTo(); 627 llvm::Value *VPtr = adjustThisArgumentForVirtualCall(CGF, GD, This); 628 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 629 630 MicrosoftVFTableContext::MethodVFTableLocation ML = 631 CGM.getVFTableContext().getMethodVFTableLocation(GD); 632 llvm::Value *VFuncPtr = 633 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 634 return Builder.CreateLoad(VFuncPtr); 635 } 636 637 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 638 const CXXDestructorDecl *Dtor, 639 CXXDtorType DtorType, 640 SourceLocation CallLoc, 641 llvm::Value *This) { 642 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 643 644 // We have only one destructor in the vftable but can get both behaviors 645 // by passing an implicit int parameter. 646 const CGFunctionInfo *FInfo = 647 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting); 648 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 649 llvm::Value *Callee = 650 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, Dtor_Deleting), This, Ty); 651 652 ASTContext &Context = CGF.getContext(); 653 llvm::Value *ImplicitParam = 654 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 655 DtorType == Dtor_Deleting); 656 657 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 658 ImplicitParam, Context.IntTy, 0, 0); 659 } 660 661 const VBTableVector & 662 MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) { 663 // At this layer, we can key the cache off of a single class, which is much 664 // easier than caching at the GlobalVariable layer. 665 llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I; 666 bool added; 667 llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector())); 668 VBTableVector &VBTables = I->second; 669 if (!added) 670 return VBTables; 671 672 VBTableBuilder(CGM, RD).enumerateVBTables(VBTables); 673 674 return VBTables; 675 } 676 677 void MicrosoftCXXABI::EmitVirtualInheritanceTables( 678 llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) { 679 const VBTableVector &VBTables = EnumerateVBTables(RD); 680 for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end(); 681 I != E; ++I) { 682 I->EmitVBTableDefinition(CGM, RD, Linkage); 683 } 684 } 685 686 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 687 QualType elementType) { 688 // Microsoft seems to completely ignore the possibility of a 689 // two-argument usual deallocation function. 690 return elementType.isDestructedType(); 691 } 692 693 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 694 // Microsoft seems to completely ignore the possibility of a 695 // two-argument usual deallocation function. 696 return expr->getAllocatedType().isDestructedType(); 697 } 698 699 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 700 // The array cookie is always a size_t; we then pad that out to the 701 // alignment of the element type. 702 ASTContext &Ctx = getContext(); 703 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 704 Ctx.getTypeAlignInChars(type)); 705 } 706 707 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 708 llvm::Value *allocPtr, 709 CharUnits cookieSize) { 710 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 711 llvm::Value *numElementsPtr = 712 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 713 return CGF.Builder.CreateLoad(numElementsPtr); 714 } 715 716 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 717 llvm::Value *newPtr, 718 llvm::Value *numElements, 719 const CXXNewExpr *expr, 720 QualType elementType) { 721 assert(requiresArrayCookie(expr)); 722 723 // The size of the cookie. 724 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 725 726 // Compute an offset to the cookie. 727 llvm::Value *cookiePtr = newPtr; 728 729 // Write the number of elements into the appropriate slot. 730 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 731 llvm::Value *numElementsPtr 732 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 733 CGF.Builder.CreateStore(numElements, numElementsPtr); 734 735 // Finally, compute a pointer to the actual data buffer by skipping 736 // over the cookie completely. 737 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 738 cookieSize.getQuantity()); 739 } 740 741 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 742 llvm::GlobalVariable *GV, 743 bool PerformInit) { 744 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 745 // threadsafe. Since the user may be linking in inline functions compiled by 746 // cl.exe, there's no reason to provide a false sense of security by using 747 // critical sections here. 748 749 if (D.getTLSKind()) 750 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 751 752 CGBuilderTy &Builder = CGF.Builder; 753 llvm::IntegerType *GuardTy = CGF.Int32Ty; 754 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 755 756 // Get the guard variable for this function if we have one already. 757 GuardInfo &GI = GuardVariableMap[D.getDeclContext()]; 758 759 unsigned BitIndex; 760 if (D.isExternallyVisible()) { 761 // Externally visible variables have to be numbered in Sema to properly 762 // handle unreachable VarDecls. 763 BitIndex = getContext().getManglingNumber(&D); 764 assert(BitIndex > 0); 765 BitIndex--; 766 } else { 767 // Non-externally visible variables are numbered here in CodeGen. 768 BitIndex = GI.BitIndex++; 769 } 770 771 if (BitIndex >= 32) { 772 if (D.isExternallyVisible()) 773 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 774 BitIndex %= 32; 775 GI.Guard = 0; 776 } 777 778 // Lazily create the i32 bitfield for this function. 779 if (!GI.Guard) { 780 // Mangle the name for the guard. 781 SmallString<256> GuardName; 782 { 783 llvm::raw_svector_ostream Out(GuardName); 784 getMangleContext().mangleStaticGuardVariable(&D, Out); 785 Out.flush(); 786 } 787 788 // Create the guard variable with a zero-initializer. Just absorb linkage 789 // and visibility from the guarded variable. 790 GI.Guard = new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 791 GV->getLinkage(), Zero, GuardName.str()); 792 GI.Guard->setVisibility(GV->getVisibility()); 793 } else { 794 assert(GI.Guard->getLinkage() == GV->getLinkage() && 795 "static local from the same function had different linkage"); 796 } 797 798 // Pseudo code for the test: 799 // if (!(GuardVar & MyGuardBit)) { 800 // GuardVar |= MyGuardBit; 801 // ... initialize the object ...; 802 // } 803 804 // Test our bit from the guard variable. 805 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 806 llvm::LoadInst *LI = Builder.CreateLoad(GI.Guard); 807 llvm::Value *IsInitialized = 808 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 809 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 810 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 811 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 812 813 // Set our bit in the guard variable and emit the initializer and add a global 814 // destructor if appropriate. 815 CGF.EmitBlock(InitBlock); 816 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI.Guard); 817 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 818 Builder.CreateBr(EndBlock); 819 820 // Continue. 821 CGF.EmitBlock(EndBlock); 822 } 823 824 // Member pointer helpers. 825 static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) { 826 return Inheritance == MSIM_Unspecified; 827 } 828 829 static bool hasOnlyOneField(bool IsMemberFunction, 830 MSInheritanceModel Inheritance) { 831 return Inheritance <= MSIM_SinglePolymorphic || 832 (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic); 833 } 834 835 // Only member pointers to functions need a this adjustment, since it can be 836 // combined with the field offset for data pointers. 837 static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction, 838 MSInheritanceModel Inheritance) { 839 return (IsMemberFunction && Inheritance >= MSIM_Multiple); 840 } 841 842 static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) { 843 return Inheritance >= MSIM_Virtual; 844 } 845 846 // Use zero for the field offset of a null data member pointer if we can 847 // guarantee that zero is not a valid field offset, or if the member pointer has 848 // multiple fields. Polymorphic classes have a vfptr at offset zero, so we can 849 // use zero for null. If there are multiple fields, we can use zero even if it 850 // is a valid field offset because null-ness testing will check the other 851 // fields. 852 static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) { 853 return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single; 854 } 855 856 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 857 // Null-ness for function memptrs only depends on the first field, which is 858 // the function pointer. The rest don't matter, so we can zero initialize. 859 if (MPT->isMemberFunctionPointer()) 860 return true; 861 862 // The virtual base adjustment field is always -1 for null, so if we have one 863 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 864 // valid field offset. 865 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 866 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 867 return (!hasVirtualBaseAdjustmentField(Inheritance) && 868 nullFieldOffsetIsZero(Inheritance)); 869 } 870 871 llvm::Type * 872 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 873 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 874 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 875 llvm::SmallVector<llvm::Type *, 4> fields; 876 if (MPT->isMemberFunctionPointer()) 877 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 878 else 879 fields.push_back(CGM.IntTy); // FieldOffset 880 881 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(), 882 Inheritance)) 883 fields.push_back(CGM.IntTy); 884 if (hasVBPtrOffsetField(Inheritance)) 885 fields.push_back(CGM.IntTy); 886 if (hasVirtualBaseAdjustmentField(Inheritance)) 887 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 888 889 if (fields.size() == 1) 890 return fields[0]; 891 return llvm::StructType::get(CGM.getLLVMContext(), fields); 892 } 893 894 void MicrosoftCXXABI:: 895 GetNullMemberPointerFields(const MemberPointerType *MPT, 896 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 897 assert(fields.empty()); 898 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 899 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 900 if (MPT->isMemberFunctionPointer()) { 901 // FunctionPointerOrVirtualThunk 902 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 903 } else { 904 if (nullFieldOffsetIsZero(Inheritance)) 905 fields.push_back(getZeroInt()); // FieldOffset 906 else 907 fields.push_back(getAllOnesInt()); // FieldOffset 908 } 909 910 if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(), 911 Inheritance)) 912 fields.push_back(getZeroInt()); 913 if (hasVBPtrOffsetField(Inheritance)) 914 fields.push_back(getZeroInt()); 915 if (hasVirtualBaseAdjustmentField(Inheritance)) 916 fields.push_back(getAllOnesInt()); 917 } 918 919 llvm::Constant * 920 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 921 llvm::SmallVector<llvm::Constant *, 4> fields; 922 GetNullMemberPointerFields(MPT, fields); 923 if (fields.size() == 1) 924 return fields[0]; 925 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 926 assert(Res->getType() == ConvertMemberPointerType(MPT)); 927 return Res; 928 } 929 930 llvm::Constant * 931 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 932 bool IsMemberFunction, 933 const CXXRecordDecl *RD, 934 CharUnits NonVirtualBaseAdjustment) 935 { 936 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 937 938 // Single inheritance class member pointer are represented as scalars instead 939 // of aggregates. 940 if (hasOnlyOneField(IsMemberFunction, Inheritance)) 941 return FirstField; 942 943 llvm::SmallVector<llvm::Constant *, 4> fields; 944 fields.push_back(FirstField); 945 946 if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance)) 947 fields.push_back(llvm::ConstantInt::get( 948 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 949 950 if (hasVBPtrOffsetField(Inheritance)) { 951 fields.push_back(llvm::ConstantInt::get( 952 CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity())); 953 } 954 955 // The rest of the fields are adjusted by conversions to a more derived class. 956 if (hasVirtualBaseAdjustmentField(Inheritance)) 957 fields.push_back(getZeroInt()); 958 959 return llvm::ConstantStruct::getAnon(fields); 960 } 961 962 llvm::Constant * 963 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 964 CharUnits offset) { 965 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 966 llvm::Constant *FirstField = 967 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 968 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 969 CharUnits::Zero()); 970 } 971 972 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 973 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 974 } 975 976 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 977 QualType MPType) { 978 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 979 const ValueDecl *MPD = MP.getMemberPointerDecl(); 980 if (!MPD) 981 return EmitNullMemberPointer(MPT); 982 983 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 984 985 // FIXME PR15713: Support virtual inheritance paths. 986 987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 988 return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(), 989 MD, ThisAdjustment); 990 991 CharUnits FieldOffset = 992 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 993 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 994 } 995 996 llvm::Constant * 997 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 998 const CXXMethodDecl *MD, 999 CharUnits NonVirtualBaseAdjustment) { 1000 assert(MD->isInstance() && "Member function must not be static!"); 1001 MD = MD->getCanonicalDecl(); 1002 CodeGenTypes &Types = CGM.getTypes(); 1003 1004 llvm::Constant *FirstField; 1005 if (MD->isVirtual()) { 1006 // FIXME: We have to instantiate a thunk that loads the vftable and jumps to 1007 // the right offset. 1008 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1009 } else { 1010 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1011 llvm::Type *Ty; 1012 // Check whether the function has a computable LLVM signature. 1013 if (Types.isFuncTypeConvertible(FPT)) { 1014 // The function has a computable LLVM signature; use the correct type. 1015 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 1016 } else { 1017 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 1018 // function type is incomplete. 1019 Ty = CGM.PtrDiffTy; 1020 } 1021 FirstField = CGM.GetAddrOfFunction(MD, Ty); 1022 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 1023 } 1024 1025 // The rest of the fields are common with data member pointers. 1026 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 1027 NonVirtualBaseAdjustment); 1028 } 1029 1030 /// Member pointers are the same if they're either bitwise identical *or* both 1031 /// null. Null-ness for function members is determined by the first field, 1032 /// while for data member pointers we must compare all fields. 1033 llvm::Value * 1034 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 1035 llvm::Value *L, 1036 llvm::Value *R, 1037 const MemberPointerType *MPT, 1038 bool Inequality) { 1039 CGBuilderTy &Builder = CGF.Builder; 1040 1041 // Handle != comparisons by switching the sense of all boolean operations. 1042 llvm::ICmpInst::Predicate Eq; 1043 llvm::Instruction::BinaryOps And, Or; 1044 if (Inequality) { 1045 Eq = llvm::ICmpInst::ICMP_NE; 1046 And = llvm::Instruction::Or; 1047 Or = llvm::Instruction::And; 1048 } else { 1049 Eq = llvm::ICmpInst::ICMP_EQ; 1050 And = llvm::Instruction::And; 1051 Or = llvm::Instruction::Or; 1052 } 1053 1054 // If this is a single field member pointer (single inheritance), this is a 1055 // single icmp. 1056 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 1057 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 1058 if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance)) 1059 return Builder.CreateICmp(Eq, L, R); 1060 1061 // Compare the first field. 1062 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 1063 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 1064 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 1065 1066 // Compare everything other than the first field. 1067 llvm::Value *Res = 0; 1068 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 1069 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 1070 llvm::Value *LF = Builder.CreateExtractValue(L, I); 1071 llvm::Value *RF = Builder.CreateExtractValue(R, I); 1072 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 1073 if (Res) 1074 Res = Builder.CreateBinOp(And, Res, Cmp); 1075 else 1076 Res = Cmp; 1077 } 1078 1079 // Check if the first field is 0 if this is a function pointer. 1080 if (MPT->isMemberFunctionPointer()) { 1081 // (l1 == r1 && ...) || l0 == 0 1082 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 1083 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 1084 Res = Builder.CreateBinOp(Or, Res, IsZero); 1085 } 1086 1087 // Combine the comparison of the first field, which must always be true for 1088 // this comparison to succeeed. 1089 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 1090 } 1091 1092 llvm::Value * 1093 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 1094 llvm::Value *MemPtr, 1095 const MemberPointerType *MPT) { 1096 CGBuilderTy &Builder = CGF.Builder; 1097 llvm::SmallVector<llvm::Constant *, 4> fields; 1098 // We only need one field for member functions. 1099 if (MPT->isMemberFunctionPointer()) 1100 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1101 else 1102 GetNullMemberPointerFields(MPT, fields); 1103 assert(!fields.empty()); 1104 llvm::Value *FirstField = MemPtr; 1105 if (MemPtr->getType()->isStructTy()) 1106 FirstField = Builder.CreateExtractValue(MemPtr, 0); 1107 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 1108 1109 // For function member pointers, we only need to test the function pointer 1110 // field. The other fields if any can be garbage. 1111 if (MPT->isMemberFunctionPointer()) 1112 return Res; 1113 1114 // Otherwise, emit a series of compares and combine the results. 1115 for (int I = 1, E = fields.size(); I < E; ++I) { 1116 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 1117 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 1118 Res = Builder.CreateAnd(Res, Next, "memptr.tobool"); 1119 } 1120 return Res; 1121 } 1122 1123 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 1124 llvm::Constant *Val) { 1125 // Function pointers are null if the pointer in the first field is null. 1126 if (MPT->isMemberFunctionPointer()) { 1127 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 1128 Val->getAggregateElement(0U) : Val; 1129 return FirstField->isNullValue(); 1130 } 1131 1132 // If it's not a function pointer and it's zero initializable, we can easily 1133 // check zero. 1134 if (isZeroInitializable(MPT) && Val->isNullValue()) 1135 return true; 1136 1137 // Otherwise, break down all the fields for comparison. Hopefully these 1138 // little Constants are reused, while a big null struct might not be. 1139 llvm::SmallVector<llvm::Constant *, 4> Fields; 1140 GetNullMemberPointerFields(MPT, Fields); 1141 if (Fields.size() == 1) { 1142 assert(Val->getType()->isIntegerTy()); 1143 return Val == Fields[0]; 1144 } 1145 1146 unsigned I, E; 1147 for (I = 0, E = Fields.size(); I != E; ++I) { 1148 if (Val->getAggregateElement(I) != Fields[I]) 1149 break; 1150 } 1151 return I == E; 1152 } 1153 1154 llvm::Value * 1155 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 1156 llvm::Value *This, 1157 llvm::Value *VBTableOffset, 1158 llvm::Value *VBPtrOffset, 1159 llvm::Value **VBPtrOut) { 1160 CGBuilderTy &Builder = CGF.Builder; 1161 // Load the vbtable pointer from the vbptr in the instance. 1162 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 1163 llvm::Value *VBPtr = 1164 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 1165 if (VBPtrOut) *VBPtrOut = VBPtr; 1166 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 1167 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 1168 1169 // Load an i32 offset from the vb-table. 1170 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset); 1171 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 1172 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 1173 } 1174 1175 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 1176 // it. 1177 llvm::Value * 1178 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF, 1179 const CXXRecordDecl *RD, llvm::Value *Base, 1180 llvm::Value *VBTableOffset, 1181 llvm::Value *VBPtrOffset) { 1182 CGBuilderTy &Builder = CGF.Builder; 1183 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 1184 llvm::BasicBlock *OriginalBB = 0; 1185 llvm::BasicBlock *SkipAdjustBB = 0; 1186 llvm::BasicBlock *VBaseAdjustBB = 0; 1187 1188 // In the unspecified inheritance model, there might not be a vbtable at all, 1189 // in which case we need to skip the virtual base lookup. If there is a 1190 // vbtable, the first entry is a no-op entry that gives back the original 1191 // base, so look for a virtual base adjustment offset of zero. 1192 if (VBPtrOffset) { 1193 OriginalBB = Builder.GetInsertBlock(); 1194 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 1195 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 1196 llvm::Value *IsVirtual = 1197 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 1198 "memptr.is_vbase"); 1199 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 1200 CGF.EmitBlock(VBaseAdjustBB); 1201 } 1202 1203 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 1204 // know the vbptr offset. 1205 if (!VBPtrOffset) { 1206 CharUnits offs = CharUnits::Zero(); 1207 if (RD->getNumVBases()) { 1208 offs = GetVBPtrOffsetFromBases(RD); 1209 } 1210 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 1211 } 1212 llvm::Value *VBPtr = 0; 1213 llvm::Value *VBaseOffs = 1214 GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr); 1215 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 1216 1217 // Merge control flow with the case where we didn't have to adjust. 1218 if (VBaseAdjustBB) { 1219 Builder.CreateBr(SkipAdjustBB); 1220 CGF.EmitBlock(SkipAdjustBB); 1221 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 1222 Phi->addIncoming(Base, OriginalBB); 1223 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 1224 return Phi; 1225 } 1226 return AdjustedBase; 1227 } 1228 1229 llvm::Value * 1230 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 1231 llvm::Value *Base, 1232 llvm::Value *MemPtr, 1233 const MemberPointerType *MPT) { 1234 assert(MPT->isMemberDataPointer()); 1235 unsigned AS = Base->getType()->getPointerAddressSpace(); 1236 llvm::Type *PType = 1237 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 1238 CGBuilderTy &Builder = CGF.Builder; 1239 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 1240 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 1241 1242 // Extract the fields we need, regardless of model. We'll apply them if we 1243 // have them. 1244 llvm::Value *FieldOffset = MemPtr; 1245 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1246 llvm::Value *VBPtrOffset = 0; 1247 if (MemPtr->getType()->isStructTy()) { 1248 // We need to extract values. 1249 unsigned I = 0; 1250 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 1251 if (hasVBPtrOffsetField(Inheritance)) 1252 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 1253 if (hasVirtualBaseAdjustmentField(Inheritance)) 1254 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 1255 } 1256 1257 if (VirtualBaseAdjustmentOffset) { 1258 Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset, 1259 VBPtrOffset); 1260 } 1261 llvm::Value *Addr = 1262 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 1263 1264 // Cast the address to the appropriate pointer type, adopting the address 1265 // space of the base pointer. 1266 return Builder.CreateBitCast(Addr, PType); 1267 } 1268 1269 static MSInheritanceModel 1270 getInheritanceFromMemptr(const MemberPointerType *MPT) { 1271 return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel(); 1272 } 1273 1274 llvm::Value * 1275 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 1276 const CastExpr *E, 1277 llvm::Value *Src) { 1278 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 1279 E->getCastKind() == CK_BaseToDerivedMemberPointer || 1280 E->getCastKind() == CK_ReinterpretMemberPointer); 1281 1282 // Use constant emission if we can. 1283 if (isa<llvm::Constant>(Src)) 1284 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 1285 1286 // We may be adding or dropping fields from the member pointer, so we need 1287 // both types and the inheritance models of both records. 1288 const MemberPointerType *SrcTy = 1289 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1290 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1291 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy); 1292 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy); 1293 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1294 1295 // If the classes use the same null representation, reinterpret_cast is a nop. 1296 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 1297 if (IsReinterpret && (IsFunc || 1298 nullFieldOffsetIsZero(SrcInheritance) == 1299 nullFieldOffsetIsZero(DstInheritance))) 1300 return Src; 1301 1302 CGBuilderTy &Builder = CGF.Builder; 1303 1304 // Branch past the conversion if Src is null. 1305 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 1306 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 1307 1308 // C++ 5.2.10p9: The null member pointer value is converted to the null member 1309 // pointer value of the destination type. 1310 if (IsReinterpret) { 1311 // For reinterpret casts, sema ensures that src and dst are both functions 1312 // or data and have the same size, which means the LLVM types should match. 1313 assert(Src->getType() == DstNull->getType()); 1314 return Builder.CreateSelect(IsNotNull, Src, DstNull); 1315 } 1316 1317 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 1318 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 1319 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 1320 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 1321 CGF.EmitBlock(ConvertBB); 1322 1323 // Decompose src. 1324 llvm::Value *FirstField = Src; 1325 llvm::Value *NonVirtualBaseAdjustment = 0; 1326 llvm::Value *VirtualBaseAdjustmentOffset = 0; 1327 llvm::Value *VBPtrOffset = 0; 1328 if (!hasOnlyOneField(IsFunc, SrcInheritance)) { 1329 // We need to extract values. 1330 unsigned I = 0; 1331 FirstField = Builder.CreateExtractValue(Src, I++); 1332 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance)) 1333 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 1334 if (hasVBPtrOffsetField(SrcInheritance)) 1335 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 1336 if (hasVirtualBaseAdjustmentField(SrcInheritance)) 1337 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 1338 } 1339 1340 // For data pointers, we adjust the field offset directly. For functions, we 1341 // have a separate field. 1342 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1343 if (Adj) { 1344 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1345 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 1346 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1347 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1348 NVAdjustField = getZeroInt(); 1349 if (isDerivedToBase) 1350 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 1351 else 1352 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 1353 } 1354 1355 // FIXME PR15713: Support conversions through virtually derived classes. 1356 1357 // Recompose dst from the null struct and the adjusted fields from src. 1358 llvm::Value *Dst; 1359 if (hasOnlyOneField(IsFunc, DstInheritance)) { 1360 Dst = FirstField; 1361 } else { 1362 Dst = llvm::UndefValue::get(DstNull->getType()); 1363 unsigned Idx = 0; 1364 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 1365 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance)) 1366 Dst = Builder.CreateInsertValue( 1367 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 1368 if (hasVBPtrOffsetField(DstInheritance)) 1369 Dst = Builder.CreateInsertValue( 1370 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 1371 if (hasVirtualBaseAdjustmentField(DstInheritance)) 1372 Dst = Builder.CreateInsertValue( 1373 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 1374 } 1375 Builder.CreateBr(ContinueBB); 1376 1377 // In the continuation, choose between DstNull and Dst. 1378 CGF.EmitBlock(ContinueBB); 1379 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 1380 Phi->addIncoming(DstNull, OriginalBB); 1381 Phi->addIncoming(Dst, ConvertBB); 1382 return Phi; 1383 } 1384 1385 llvm::Constant * 1386 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 1387 llvm::Constant *Src) { 1388 const MemberPointerType *SrcTy = 1389 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 1390 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 1391 1392 // If src is null, emit a new null for dst. We can't return src because dst 1393 // might have a new representation. 1394 if (MemberPointerConstantIsNull(SrcTy, Src)) 1395 return EmitNullMemberPointer(DstTy); 1396 1397 // We don't need to do anything for reinterpret_casts of non-null member 1398 // pointers. We should only get here when the two type representations have 1399 // the same size. 1400 if (E->getCastKind() == CK_ReinterpretMemberPointer) 1401 return Src; 1402 1403 MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy); 1404 MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy); 1405 1406 // Decompose src. 1407 llvm::Constant *FirstField = Src; 1408 llvm::Constant *NonVirtualBaseAdjustment = 0; 1409 llvm::Constant *VirtualBaseAdjustmentOffset = 0; 1410 llvm::Constant *VBPtrOffset = 0; 1411 bool IsFunc = SrcTy->isMemberFunctionPointer(); 1412 if (!hasOnlyOneField(IsFunc, SrcInheritance)) { 1413 // We need to extract values. 1414 unsigned I = 0; 1415 FirstField = Src->getAggregateElement(I++); 1416 if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance)) 1417 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 1418 if (hasVBPtrOffsetField(SrcInheritance)) 1419 VBPtrOffset = Src->getAggregateElement(I++); 1420 if (hasVirtualBaseAdjustmentField(SrcInheritance)) 1421 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 1422 } 1423 1424 // For data pointers, we adjust the field offset directly. For functions, we 1425 // have a separate field. 1426 llvm::Constant *Adj = getMemberPointerAdjustment(E); 1427 if (Adj) { 1428 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 1429 llvm::Constant *&NVAdjustField = 1430 IsFunc ? NonVirtualBaseAdjustment : FirstField; 1431 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 1432 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 1433 NVAdjustField = getZeroInt(); 1434 if (IsDerivedToBase) 1435 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 1436 else 1437 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 1438 } 1439 1440 // FIXME PR15713: Support conversions through virtually derived classes. 1441 1442 // Recompose dst from the null struct and the adjusted fields from src. 1443 if (hasOnlyOneField(IsFunc, DstInheritance)) 1444 return FirstField; 1445 1446 llvm::SmallVector<llvm::Constant *, 4> Fields; 1447 Fields.push_back(FirstField); 1448 if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance)) 1449 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 1450 if (hasVBPtrOffsetField(DstInheritance)) 1451 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 1452 if (hasVirtualBaseAdjustmentField(DstInheritance)) 1453 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 1454 return llvm::ConstantStruct::getAnon(Fields); 1455 } 1456 1457 llvm::Value * 1458 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 1459 llvm::Value *&This, 1460 llvm::Value *MemPtr, 1461 const MemberPointerType *MPT) { 1462 assert(MPT->isMemberFunctionPointer()); 1463 const FunctionProtoType *FPT = 1464 MPT->getPointeeType()->castAs<FunctionProtoType>(); 1465 const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl(); 1466 llvm::FunctionType *FTy = 1467 CGM.getTypes().GetFunctionType( 1468 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 1469 CGBuilderTy &Builder = CGF.Builder; 1470 1471 MSInheritanceModel Inheritance = RD->getMSInheritanceModel(); 1472 1473 // Extract the fields we need, regardless of model. We'll apply them if we 1474 // have them. 1475 llvm::Value *FunctionPointer = MemPtr; 1476 llvm::Value *NonVirtualBaseAdjustment = NULL; 1477 llvm::Value *VirtualBaseAdjustmentOffset = NULL; 1478 llvm::Value *VBPtrOffset = NULL; 1479 if (MemPtr->getType()->isStructTy()) { 1480 // We need to extract values. 1481 unsigned I = 0; 1482 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 1483 if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance)) 1484 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 1485 if (hasVBPtrOffsetField(Inheritance)) 1486 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 1487 if (hasVirtualBaseAdjustmentField(Inheritance)) 1488 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 1489 } 1490 1491 if (VirtualBaseAdjustmentOffset) { 1492 This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset, 1493 VBPtrOffset); 1494 } 1495 1496 if (NonVirtualBaseAdjustment) { 1497 // Apply the adjustment and cast back to the original struct type. 1498 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 1499 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 1500 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 1501 } 1502 1503 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 1504 } 1505 1506 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 1507 return new MicrosoftCXXABI(CGM); 1508 } 1509 1510