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 "CGVTables.h" 19 #include "CodeGenModule.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/VTableBuilder.h" 23 #include "llvm/ADT/StringSet.h" 24 #include "llvm/IR/CallSite.h" 25 26 using namespace clang; 27 using namespace CodeGen; 28 29 namespace { 30 31 /// Holds all the vbtable globals for a given class. 32 struct VBTableGlobals { 33 const VPtrInfoVector *VBTables; 34 SmallVector<llvm::GlobalVariable *, 2> Globals; 35 }; 36 37 class MicrosoftCXXABI : public CGCXXABI { 38 public: 39 MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {} 40 41 bool HasThisReturn(GlobalDecl GD) const override; 42 43 bool classifyReturnType(CGFunctionInfo &FI) const override; 44 45 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override; 46 47 bool isSRetParameterAfterThis() const override { return true; } 48 49 StringRef GetPureVirtualCallName() override { return "_purecall"; } 50 // No known support for deleted functions in MSVC yet, so this choice is 51 // arbitrary. 52 StringRef GetDeletedVirtualCallName() override { return "_purecall"; } 53 54 bool isInlineInitializedStaticDataMemberLinkOnce() override { return true; } 55 56 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 57 llvm::Value *ptr, 58 QualType type) override; 59 60 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 61 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 62 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 63 llvm::Value *ThisPtr, 64 llvm::Type *StdTypeInfoPtrTy) override; 65 66 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 67 QualType SrcRecordTy) override; 68 69 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 70 QualType SrcRecordTy, QualType DestTy, 71 QualType DestRecordTy, 72 llvm::BasicBlock *CastEnd) override; 73 74 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 75 QualType SrcRecordTy, 76 QualType DestTy) override; 77 78 bool EmitBadCastCall(CodeGenFunction &CGF) override; 79 80 llvm::Value * 81 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This, 82 const CXXRecordDecl *ClassDecl, 83 const CXXRecordDecl *BaseClassDecl) override; 84 85 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 86 CXXCtorType Type, CanQualType &ResTy, 87 SmallVectorImpl<CanQualType> &ArgTys) override; 88 89 llvm::BasicBlock * 90 EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 91 const CXXRecordDecl *RD) override; 92 93 void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, 94 const CXXRecordDecl *RD) override; 95 96 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 97 98 // Background on MSVC destructors 99 // ============================== 100 // 101 // Both Itanium and MSVC ABIs have destructor variants. The variant names 102 // roughly correspond in the following way: 103 // Itanium Microsoft 104 // Base -> no name, just ~Class 105 // Complete -> vbase destructor 106 // Deleting -> scalar deleting destructor 107 // vector deleting destructor 108 // 109 // The base and complete destructors are the same as in Itanium, although the 110 // complete destructor does not accept a VTT parameter when there are virtual 111 // bases. A separate mechanism involving vtordisps is used to ensure that 112 // virtual methods of destroyed subobjects are not called. 113 // 114 // The deleting destructors accept an i32 bitfield as a second parameter. Bit 115 // 1 indicates if the memory should be deleted. Bit 2 indicates if the this 116 // pointer points to an array. The scalar deleting destructor assumes that 117 // bit 2 is zero, and therefore does not contain a loop. 118 // 119 // For virtual destructors, only one entry is reserved in the vftable, and it 120 // always points to the vector deleting destructor. The vector deleting 121 // destructor is the most general, so it can be used to destroy objects in 122 // place, delete single heap objects, or delete arrays. 123 // 124 // A TU defining a non-inline destructor is only guaranteed to emit a base 125 // destructor, and all of the other variants are emitted on an as-needed basis 126 // in COMDATs. Because a non-base destructor can be emitted in a TU that 127 // lacks a definition for the destructor, non-base destructors must always 128 // delegate to or alias the base destructor. 129 130 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 131 CXXDtorType Type, 132 CanQualType &ResTy, 133 SmallVectorImpl<CanQualType> &ArgTys) override; 134 135 /// Non-base dtors should be emitted as delegating thunks in this ABI. 136 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 137 CXXDtorType DT) const override { 138 return DT != Dtor_Base; 139 } 140 141 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 142 143 const CXXRecordDecl * 144 getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override { 145 MD = MD->getCanonicalDecl(); 146 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) { 147 MicrosoftVTableContext::MethodVFTableLocation ML = 148 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 149 // The vbases might be ordered differently in the final overrider object 150 // and the complete object, so the "this" argument may sometimes point to 151 // memory that has no particular type (e.g. past the complete object). 152 // In this case, we just use a generic pointer type. 153 // FIXME: might want to have a more precise type in the non-virtual 154 // multiple inheritance case. 155 if (ML.VBase || !ML.VFPtrOffset.isZero()) 156 return nullptr; 157 } 158 return MD->getParent(); 159 } 160 161 llvm::Value * 162 adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, 163 llvm::Value *This, 164 bool VirtualCall) override; 165 166 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 167 FunctionArgList &Params) override; 168 169 llvm::Value *adjustThisParameterInVirtualFunctionPrologue( 170 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override; 171 172 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 173 174 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 175 const CXXConstructorDecl *D, 176 CXXCtorType Type, bool ForVirtualBase, 177 bool Delegating, 178 CallArgList &Args) override; 179 180 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 181 CXXDtorType Type, bool ForVirtualBase, 182 bool Delegating, llvm::Value *This) override; 183 184 void emitVTableDefinitions(CodeGenVTables &CGVT, 185 const CXXRecordDecl *RD) override; 186 187 llvm::Value *getVTableAddressPointInStructor( 188 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 189 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 190 bool &NeedsVirtualOffset) override; 191 192 llvm::Constant * 193 getVTableAddressPointForConstExpr(BaseSubobject Base, 194 const CXXRecordDecl *VTableClass) override; 195 196 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 197 CharUnits VPtrOffset) override; 198 199 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 200 llvm::Value *This, 201 llvm::Type *Ty) override; 202 203 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 204 const CXXDestructorDecl *Dtor, 205 CXXDtorType DtorType, SourceLocation CallLoc, 206 llvm::Value *This) override; 207 208 void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD, 209 CallArgList &CallArgs) override { 210 assert(GD.getDtorType() == Dtor_Deleting && 211 "Only deleting destructor thunks are available in this ABI"); 212 CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)), 213 CGM.getContext().IntTy); 214 } 215 216 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 217 218 llvm::GlobalVariable * 219 getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 220 llvm::GlobalVariable::LinkageTypes Linkage); 221 222 void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD, 223 llvm::GlobalVariable *GV) const; 224 225 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, 226 GlobalDecl GD, bool ReturnAdjustment) override { 227 // Never dllimport/dllexport thunks. 228 Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 229 230 GVALinkage Linkage = 231 getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl())); 232 233 if (Linkage == GVA_Internal) 234 Thunk->setLinkage(llvm::GlobalValue::InternalLinkage); 235 else if (ReturnAdjustment) 236 Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage); 237 else 238 Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 239 } 240 241 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 242 const ThisAdjustment &TA) override; 243 244 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 245 const ReturnAdjustment &RA) override; 246 247 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 248 llvm::GlobalVariable *DeclPtr, 249 bool PerformInit) override; 250 251 // ==== Notes on array cookies ========= 252 // 253 // MSVC seems to only use cookies when the class has a destructor; a 254 // two-argument usual array deallocation function isn't sufficient. 255 // 256 // For example, this code prints "100" and "1": 257 // struct A { 258 // char x; 259 // void *operator new[](size_t sz) { 260 // printf("%u\n", sz); 261 // return malloc(sz); 262 // } 263 // void operator delete[](void *p, size_t sz) { 264 // printf("%u\n", sz); 265 // free(p); 266 // } 267 // }; 268 // int main() { 269 // A *p = new A[100]; 270 // delete[] p; 271 // } 272 // Whereas it prints "104" and "104" if you give A a destructor. 273 274 bool requiresArrayCookie(const CXXDeleteExpr *expr, 275 QualType elementType) override; 276 bool requiresArrayCookie(const CXXNewExpr *expr) override; 277 CharUnits getArrayCookieSizeImpl(QualType type) override; 278 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 279 llvm::Value *NewPtr, 280 llvm::Value *NumElements, 281 const CXXNewExpr *expr, 282 QualType ElementType) override; 283 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 284 llvm::Value *allocPtr, 285 CharUnits cookieSize) override; 286 287 private: 288 MicrosoftMangleContext &getMangleContext() { 289 return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 290 } 291 292 llvm::Constant *getZeroInt() { 293 return llvm::ConstantInt::get(CGM.IntTy, 0); 294 } 295 296 llvm::Constant *getAllOnesInt() { 297 return llvm::Constant::getAllOnesValue(CGM.IntTy); 298 } 299 300 llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) { 301 return C ? C : getZeroInt(); 302 } 303 304 llvm::Value *getValueOrZeroInt(llvm::Value *C) { 305 return C ? C : getZeroInt(); 306 } 307 308 CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD); 309 310 void 311 GetNullMemberPointerFields(const MemberPointerType *MPT, 312 llvm::SmallVectorImpl<llvm::Constant *> &fields); 313 314 /// \brief Shared code for virtual base adjustment. Returns the offset from 315 /// the vbptr to the virtual base. Optionally returns the address of the 316 /// vbptr itself. 317 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 318 llvm::Value *Base, 319 llvm::Value *VBPtrOffset, 320 llvm::Value *VBTableOffset, 321 llvm::Value **VBPtr = nullptr); 322 323 llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 324 llvm::Value *Base, 325 int32_t VBPtrOffset, 326 int32_t VBTableOffset, 327 llvm::Value **VBPtr = nullptr) { 328 llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), 329 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset); 330 return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr); 331 } 332 333 /// \brief Performs a full virtual base adjustment. Used to dereference 334 /// pointers to members of virtual bases. 335 llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E, 336 const CXXRecordDecl *RD, llvm::Value *Base, 337 llvm::Value *VirtualBaseAdjustmentOffset, 338 llvm::Value *VBPtrOffset /* optional */); 339 340 /// \brief Emits a full member pointer with the fields common to data and 341 /// function member pointers. 342 llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField, 343 bool IsMemberFunction, 344 const CXXRecordDecl *RD, 345 CharUnits NonVirtualBaseAdjustment); 346 347 llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD, 348 const CXXMethodDecl *MD, 349 CharUnits NonVirtualBaseAdjustment); 350 351 bool MemberPointerConstantIsNull(const MemberPointerType *MPT, 352 llvm::Constant *MP); 353 354 /// \brief - Initialize all vbptrs of 'this' with RD as the complete type. 355 void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD); 356 357 /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables(). 358 const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD); 359 360 /// \brief Generate a thunk for calling a virtual member function MD. 361 llvm::Function *EmitVirtualMemPtrThunk( 362 const CXXMethodDecl *MD, 363 const MicrosoftVTableContext::MethodVFTableLocation &ML); 364 365 public: 366 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 367 368 bool isZeroInitializable(const MemberPointerType *MPT) override; 369 370 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 371 372 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 373 CharUnits offset) override; 374 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override; 375 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 376 377 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 378 llvm::Value *L, 379 llvm::Value *R, 380 const MemberPointerType *MPT, 381 bool Inequality) override; 382 383 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 384 llvm::Value *MemPtr, 385 const MemberPointerType *MPT) override; 386 387 llvm::Value * 388 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 389 llvm::Value *Base, llvm::Value *MemPtr, 390 const MemberPointerType *MPT) override; 391 392 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 393 const CastExpr *E, 394 llvm::Value *Src) override; 395 396 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 397 llvm::Constant *Src) override; 398 399 llvm::Value * 400 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, 401 llvm::Value *&This, llvm::Value *MemPtr, 402 const MemberPointerType *MPT) override; 403 404 private: 405 typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy; 406 typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy; 407 /// \brief All the vftables that have been referenced. 408 VFTablesMapTy VFTablesMap; 409 410 /// \brief This set holds the record decls we've deferred vtable emission for. 411 llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables; 412 413 414 /// \brief All the vbtables which have been referenced. 415 llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap; 416 417 /// Info on the global variable used to guard initialization of static locals. 418 /// The BitIndex field is only used for externally invisible declarations. 419 struct GuardInfo { 420 GuardInfo() : Guard(nullptr), BitIndex(0) {} 421 llvm::GlobalVariable *Guard; 422 unsigned BitIndex; 423 }; 424 425 /// Map from DeclContext to the current guard variable. We assume that the 426 /// AST is visited in source code order. 427 llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap; 428 }; 429 430 } 431 432 CGCXXABI::RecordArgABI 433 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const { 434 switch (CGM.getTarget().getTriple().getArch()) { 435 default: 436 // FIXME: Implement for other architectures. 437 return RAA_Default; 438 439 case llvm::Triple::x86: 440 // All record arguments are passed in memory on x86. Decide whether to 441 // construct the object directly in argument memory, or to construct the 442 // argument elsewhere and copy the bytes during the call. 443 444 // If C++ prohibits us from making a copy, construct the arguments directly 445 // into argument memory. 446 if (!canCopyArgument(RD)) 447 return RAA_DirectInMemory; 448 449 // Otherwise, construct the argument into a temporary and copy the bytes 450 // into the outgoing argument memory. 451 return RAA_Default; 452 453 case llvm::Triple::x86_64: 454 // Win64 passes objects with non-trivial copy ctors indirectly. 455 if (RD->hasNonTrivialCopyConstructor()) 456 return RAA_Indirect; 457 458 // Win64 passes objects larger than 8 bytes indirectly. 459 if (getContext().getTypeSize(RD->getTypeForDecl()) > 64) 460 return RAA_Indirect; 461 462 // We have a trivial copy constructor or no copy constructors, but we have 463 // to make sure it isn't deleted. 464 bool CopyDeleted = false; 465 for (const CXXConstructorDecl *CD : RD->ctors()) { 466 if (CD->isCopyConstructor()) { 467 assert(CD->isTrivial()); 468 // We had at least one undeleted trivial copy ctor. Return directly. 469 if (!CD->isDeleted()) 470 return RAA_Default; 471 CopyDeleted = true; 472 } 473 } 474 475 // The trivial copy constructor was deleted. Return indirectly. 476 if (CopyDeleted) 477 return RAA_Indirect; 478 479 // There were no copy ctors. Return in RAX. 480 return RAA_Default; 481 } 482 483 llvm_unreachable("invalid enum"); 484 } 485 486 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 487 llvm::Value *ptr, 488 QualType type) { 489 // FIXME: implement 490 return ptr; 491 } 492 493 /// \brief Gets the offset to the virtual base that contains the vfptr for 494 /// MS-ABI polymorphic types. 495 static llvm::Value *getPolymorphicOffset(CodeGenFunction &CGF, 496 const CXXRecordDecl *RD, 497 llvm::Value *Value) { 498 const ASTContext &Context = RD->getASTContext(); 499 for (const CXXBaseSpecifier &Base : RD->vbases()) 500 if (Context.getASTRecordLayout(Base.getType()->getAsCXXRecordDecl()) 501 .hasExtendableVFPtr()) 502 return CGF.CGM.getCXXABI().GetVirtualBaseClassOffset( 503 CGF, Value, RD, Base.getType()->getAsCXXRecordDecl()); 504 llvm_unreachable("One of our vbases should be polymorphic."); 505 } 506 507 static std::pair<llvm::Value *, llvm::Value *> 508 performBaseAdjustment(CodeGenFunction &CGF, llvm::Value *Value, 509 QualType SrcRecordTy) { 510 Value = CGF.Builder.CreateBitCast(Value, CGF.Int8PtrTy); 511 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 512 513 if (CGF.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr()) 514 return std::make_pair(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 515 516 // Perform a base adjustment. 517 llvm::Value *Offset = getPolymorphicOffset(CGF, SrcDecl, Value); 518 Value = CGF.Builder.CreateInBoundsGEP(Value, Offset); 519 Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty); 520 return std::make_pair(Value, Offset); 521 } 522 523 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 524 QualType SrcRecordTy) { 525 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 526 return IsDeref && 527 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 528 } 529 530 static llvm::CallSite emitRTtypeidCall(CodeGenFunction &CGF, 531 llvm::Value *Argument) { 532 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 533 llvm::FunctionType *FTy = 534 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false); 535 llvm::Value *Args[] = {Argument}; 536 llvm::Constant *Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid"); 537 return CGF.EmitRuntimeCallOrInvoke(Fn, Args); 538 } 539 540 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 541 llvm::CallSite Call = 542 emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy)); 543 Call.setDoesNotReturn(); 544 CGF.Builder.CreateUnreachable(); 545 } 546 547 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF, 548 QualType SrcRecordTy, 549 llvm::Value *ThisPtr, 550 llvm::Type *StdTypeInfoPtrTy) { 551 const CXXRecordDecl *RD = SrcRecordTy->getAsCXXRecordDecl(); 552 llvm::Value *CastPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy); 553 llvm::Value *AdjustedThisPtr = CGF.Builder.CreateInBoundsGEP( 554 CastPtr, getPolymorphicOffset(CGF, RD, CastPtr)); 555 return CGF.Builder.CreateBitCast( 556 emitRTtypeidCall(CGF, AdjustedThisPtr).getInstruction(), 557 StdTypeInfoPtrTy); 558 } 559 560 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 561 QualType SrcRecordTy) { 562 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 563 return SrcIsPtr && 564 !CGM.getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr(); 565 } 566 567 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall( 568 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy, 569 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 570 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 571 572 llvm::Value *SrcRTTI = 573 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 574 llvm::Value *DestRTTI = 575 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 576 577 llvm::Value *Offset; 578 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 579 580 // PVOID __RTDynamicCast( 581 // PVOID inptr, 582 // LONG VfDelta, 583 // PVOID SrcType, 584 // PVOID TargetType, 585 // BOOL isReference) 586 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy, 587 CGF.Int8PtrTy, CGF.Int32Ty}; 588 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 589 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 590 "__RTDynamicCast"); 591 llvm::Value *Args[] = { 592 Value, Offset, SrcRTTI, DestRTTI, 593 llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())}; 594 Value = CGF.EmitRuntimeCallOrInvoke(Function, Args).getInstruction(); 595 return CGF.Builder.CreateBitCast(Value, DestLTy); 596 } 597 598 llvm::Value * 599 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 600 QualType SrcRecordTy, 601 QualType DestTy) { 602 llvm::Value *Offset; 603 std::tie(Value, Offset) = performBaseAdjustment(CGF, Value, SrcRecordTy); 604 605 // PVOID __RTCastToVoid( 606 // PVOID inptr) 607 llvm::Type *ArgTypes[] = {CGF.Int8PtrTy}; 608 llvm::Constant *Function = CGF.CGM.CreateRuntimeFunction( 609 llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false), 610 "__RTCastToVoid"); 611 llvm::Value *Args[] = {Value}; 612 return CGF.EmitRuntimeCall(Function, Args); 613 } 614 615 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 616 return false; 617 } 618 619 llvm::Value * 620 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 621 llvm::Value *This, 622 const CXXRecordDecl *ClassDecl, 623 const CXXRecordDecl *BaseClassDecl) { 624 int64_t VBPtrChars = 625 getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity(); 626 llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars); 627 CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy); 628 CharUnits VBTableChars = 629 IntSize * 630 CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl); 631 llvm::Value *VBTableOffset = 632 llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity()); 633 634 llvm::Value *VBPtrToNewBase = 635 GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset); 636 VBPtrToNewBase = 637 CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy); 638 return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase); 639 } 640 641 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const { 642 return isa<CXXConstructorDecl>(GD.getDecl()); 643 } 644 645 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 646 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 647 if (!RD) 648 return false; 649 650 if (FI.isInstanceMethod()) { 651 // If it's an instance method, aggregates are always returned indirectly via 652 // the second parameter. 653 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 654 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod()); 655 return true; 656 } else if (!RD->isPOD()) { 657 // If it's a free function, non-POD types are returned indirectly. 658 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 659 return true; 660 } 661 662 // Otherwise, use the C ABI rules. 663 return false; 664 } 665 666 void MicrosoftCXXABI::BuildConstructorSignature( 667 const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy, 668 SmallVectorImpl<CanQualType> &ArgTys) { 669 670 // All parameters are already in place except is_most_derived, which goes 671 // after 'this' if it's variadic and last if it's not. 672 673 const CXXRecordDecl *Class = Ctor->getParent(); 674 const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>(); 675 if (Class->getNumVBases()) { 676 if (FPT->isVariadic()) 677 ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy); 678 else 679 ArgTys.push_back(CGM.getContext().IntTy); 680 } 681 } 682 683 llvm::BasicBlock * 684 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, 685 const CXXRecordDecl *RD) { 686 llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF); 687 assert(IsMostDerivedClass && 688 "ctor for a class with virtual bases must have an implicit parameter"); 689 llvm::Value *IsCompleteObject = 690 CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object"); 691 692 llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases"); 693 llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases"); 694 CGF.Builder.CreateCondBr(IsCompleteObject, 695 CallVbaseCtorsBB, SkipVbaseCtorsBB); 696 697 CGF.EmitBlock(CallVbaseCtorsBB); 698 699 // Fill in the vbtable pointers here. 700 EmitVBPtrStores(CGF, RD); 701 702 // CGF will put the base ctor calls in this basic block for us later. 703 704 return SkipVbaseCtorsBB; 705 } 706 707 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers( 708 CodeGenFunction &CGF, const CXXRecordDecl *RD) { 709 // In most cases, an override for a vbase virtual method can adjust 710 // the "this" parameter by applying a constant offset. 711 // However, this is not enough while a constructor or a destructor of some 712 // class X is being executed if all the following conditions are met: 713 // - X has virtual bases, (1) 714 // - X overrides a virtual method M of a vbase Y, (2) 715 // - X itself is a vbase of the most derived class. 716 // 717 // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X 718 // which holds the extra amount of "this" adjustment we must do when we use 719 // the X vftables (i.e. during X ctor or dtor). 720 // Outside the ctors and dtors, the values of vtorDisps are zero. 721 722 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 723 typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets; 724 const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap(); 725 CGBuilderTy &Builder = CGF.Builder; 726 727 unsigned AS = 728 cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace(); 729 llvm::Value *Int8This = nullptr; // Initialize lazily. 730 731 for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end(); 732 I != E; ++I) { 733 if (!I->second.hasVtorDisp()) 734 continue; 735 736 llvm::Value *VBaseOffset = 737 GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first); 738 // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset() 739 // just to Trunc back immediately. 740 VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty); 741 uint64_t ConstantVBaseOffset = 742 Layout.getVBaseClassOffset(I->first).getQuantity(); 743 744 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase). 745 llvm::Value *VtorDispValue = Builder.CreateSub( 746 VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset), 747 "vtordisp.value"); 748 749 if (!Int8This) 750 Int8This = Builder.CreateBitCast(getThisValue(CGF), 751 CGF.Int8Ty->getPointerTo(AS)); 752 llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset); 753 // vtorDisp is always the 32-bits before the vbase in the class layout. 754 VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4); 755 VtorDispPtr = Builder.CreateBitCast( 756 VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr"); 757 758 Builder.CreateStore(VtorDispValue, VtorDispPtr); 759 } 760 } 761 762 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 763 // There's only one constructor type in this ABI. 764 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 765 } 766 767 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF, 768 const CXXRecordDecl *RD) { 769 llvm::Value *ThisInt8Ptr = 770 CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8"); 771 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 772 773 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 774 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 775 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 776 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 777 const ASTRecordLayout &SubobjectLayout = 778 CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr); 779 CharUnits Offs = VBT->NonVirtualOffset; 780 Offs += SubobjectLayout.getVBPtrOffset(); 781 if (VBT->getVBaseWithVPtr()) 782 Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr()); 783 llvm::Value *VBPtr = 784 CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity()); 785 VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0), 786 "vbptr." + VBT->ReusingBase->getName()); 787 CGF.Builder.CreateStore(GV, VBPtr); 788 } 789 } 790 791 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 792 CXXDtorType Type, 793 CanQualType &ResTy, 794 SmallVectorImpl<CanQualType> &ArgTys) { 795 // 'this' is already in place 796 797 // TODO: 'for base' flag 798 799 if (Type == Dtor_Deleting) { 800 // The scalar deleting destructor takes an implicit int parameter. 801 ArgTys.push_back(CGM.getContext().IntTy); 802 } 803 } 804 805 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 806 // The TU defining a dtor is only guaranteed to emit a base destructor. All 807 // other destructor variants are delegating thunks. 808 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 809 } 810 811 CharUnits 812 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) { 813 GD = GD.getCanonicalDecl(); 814 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 815 816 GlobalDecl LookupGD = GD; 817 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 818 // Complete destructors take a pointer to the complete object as a 819 // parameter, thus don't need this adjustment. 820 if (GD.getDtorType() == Dtor_Complete) 821 return CharUnits(); 822 823 // There's no Dtor_Base in vftable but it shares the this adjustment with 824 // the deleting one, so look it up instead. 825 LookupGD = GlobalDecl(DD, Dtor_Deleting); 826 } 827 828 MicrosoftVTableContext::MethodVFTableLocation ML = 829 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 830 CharUnits Adjustment = ML.VFPtrOffset; 831 832 // Normal virtual instance methods need to adjust from the vfptr that first 833 // defined the virtual method to the virtual base subobject, but destructors 834 // do not. The vector deleting destructor thunk applies this adjustment for 835 // us if necessary. 836 if (isa<CXXDestructorDecl>(MD)) 837 Adjustment = CharUnits::Zero(); 838 839 if (ML.VBase) { 840 const ASTRecordLayout &DerivedLayout = 841 CGM.getContext().getASTRecordLayout(MD->getParent()); 842 Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase); 843 } 844 845 return Adjustment; 846 } 847 848 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall( 849 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) { 850 if (!VirtualCall) { 851 // If the call of a virtual function is not virtual, we just have to 852 // compensate for the adjustment the virtual function does in its prologue. 853 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 854 if (Adjustment.isZero()) 855 return This; 856 857 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 858 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 859 This = CGF.Builder.CreateBitCast(This, charPtrTy); 860 assert(Adjustment.isPositive()); 861 return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity()); 862 } 863 864 GD = GD.getCanonicalDecl(); 865 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 866 867 GlobalDecl LookupGD = GD; 868 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) { 869 // Complete dtors take a pointer to the complete object, 870 // thus don't need adjustment. 871 if (GD.getDtorType() == Dtor_Complete) 872 return This; 873 874 // There's only Dtor_Deleting in vftable but it shares the this adjustment 875 // with the base one, so look up the deleting one instead. 876 LookupGD = GlobalDecl(DD, Dtor_Deleting); 877 } 878 MicrosoftVTableContext::MethodVFTableLocation ML = 879 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD); 880 881 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 882 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS); 883 CharUnits StaticOffset = ML.VFPtrOffset; 884 885 // Base destructors expect 'this' to point to the beginning of the base 886 // subobject, not the first vfptr that happens to contain the virtual dtor. 887 // However, we still need to apply the virtual base adjustment. 888 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 889 StaticOffset = CharUnits::Zero(); 890 891 if (ML.VBase) { 892 This = CGF.Builder.CreateBitCast(This, charPtrTy); 893 llvm::Value *VBaseOffset = 894 GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase); 895 This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset); 896 } 897 if (!StaticOffset.isZero()) { 898 assert(StaticOffset.isPositive()); 899 This = CGF.Builder.CreateBitCast(This, charPtrTy); 900 if (ML.VBase) { 901 // Non-virtual adjustment might result in a pointer outside the allocated 902 // object, e.g. if the final overrider class is laid out after the virtual 903 // base that declares a method in the most derived class. 904 // FIXME: Update the code that emits this adjustment in thunks prologues. 905 This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity()); 906 } else { 907 This = CGF.Builder.CreateConstInBoundsGEP1_32(This, 908 StaticOffset.getQuantity()); 909 } 910 } 911 return This; 912 } 913 914 static bool IsDeletingDtor(GlobalDecl GD) { 915 const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl()); 916 if (isa<CXXDestructorDecl>(MD)) { 917 return GD.getDtorType() == Dtor_Deleting; 918 } 919 return false; 920 } 921 922 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 923 QualType &ResTy, 924 FunctionArgList &Params) { 925 ASTContext &Context = getContext(); 926 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 927 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 928 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 929 ImplicitParamDecl *IsMostDerived 930 = ImplicitParamDecl::Create(Context, nullptr, 931 CGF.CurGD.getDecl()->getLocation(), 932 &Context.Idents.get("is_most_derived"), 933 Context.IntTy); 934 // The 'most_derived' parameter goes second if the ctor is variadic and last 935 // if it's not. Dtors can't be variadic. 936 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 937 if (FPT->isVariadic()) 938 Params.insert(Params.begin() + 1, IsMostDerived); 939 else 940 Params.push_back(IsMostDerived); 941 getStructorImplicitParamDecl(CGF) = IsMostDerived; 942 } else if (IsDeletingDtor(CGF.CurGD)) { 943 ImplicitParamDecl *ShouldDelete 944 = ImplicitParamDecl::Create(Context, nullptr, 945 CGF.CurGD.getDecl()->getLocation(), 946 &Context.Idents.get("should_call_delete"), 947 Context.IntTy); 948 Params.push_back(ShouldDelete); 949 getStructorImplicitParamDecl(CGF) = ShouldDelete; 950 } 951 } 952 953 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue( 954 CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) { 955 // In this ABI, every virtual function takes a pointer to one of the 956 // subobjects that first defines it as the 'this' parameter, rather than a 957 // pointer to the final overrider subobject. Thus, we need to adjust it back 958 // to the final overrider subobject before use. 959 // See comments in the MicrosoftVFTableContext implementation for the details. 960 CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD); 961 if (Adjustment.isZero()) 962 return This; 963 964 unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace(); 965 llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS), 966 *thisTy = This->getType(); 967 968 This = CGF.Builder.CreateBitCast(This, charPtrTy); 969 assert(Adjustment.isPositive()); 970 This = 971 CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity()); 972 return CGF.Builder.CreateBitCast(This, thisTy); 973 } 974 975 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 976 EmitThisParam(CGF); 977 978 /// If this is a function that the ABI specifies returns 'this', initialize 979 /// the return slot to 'this' at the start of the function. 980 /// 981 /// Unlike the setting of return types, this is done within the ABI 982 /// implementation instead of by clients of CGCXXABI because: 983 /// 1) getThisValue is currently protected 984 /// 2) in theory, an ABI could implement 'this' returns some other way; 985 /// HasThisReturn only specifies a contract, not the implementation 986 if (HasThisReturn(CGF.CurGD)) 987 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 988 989 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 990 if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) { 991 assert(getStructorImplicitParamDecl(CGF) && 992 "no implicit parameter for a constructor with virtual bases?"); 993 getStructorImplicitParamValue(CGF) 994 = CGF.Builder.CreateLoad( 995 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 996 "is_most_derived"); 997 } 998 999 if (IsDeletingDtor(CGF.CurGD)) { 1000 assert(getStructorImplicitParamDecl(CGF) && 1001 "no implicit parameter for a deleting destructor?"); 1002 getStructorImplicitParamValue(CGF) 1003 = CGF.Builder.CreateLoad( 1004 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), 1005 "should_call_delete"); 1006 } 1007 } 1008 1009 unsigned MicrosoftCXXABI::addImplicitConstructorArgs( 1010 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1011 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1012 assert(Type == Ctor_Complete || Type == Ctor_Base); 1013 1014 // Check if we need a 'most_derived' parameter. 1015 if (!D->getParent()->getNumVBases()) 1016 return 0; 1017 1018 // Add the 'most_derived' argument second if we are variadic or last if not. 1019 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1020 llvm::Value *MostDerivedArg = 1021 llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete); 1022 RValue RV = RValue::get(MostDerivedArg); 1023 if (MostDerivedArg) { 1024 if (FPT->isVariadic()) 1025 Args.insert(Args.begin() + 1, 1026 CallArg(RV, getContext().IntTy, /*needscopy=*/false)); 1027 else 1028 Args.add(RV, getContext().IntTy); 1029 } 1030 1031 return 1; // Added one arg. 1032 } 1033 1034 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1035 const CXXDestructorDecl *DD, 1036 CXXDtorType Type, bool ForVirtualBase, 1037 bool Delegating, llvm::Value *This) { 1038 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 1039 1040 if (DD->isVirtual()) { 1041 assert(Type != CXXDtorType::Dtor_Deleting && 1042 "The deleting destructor should only be called via a virtual call"); 1043 This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type), 1044 This, false); 1045 } 1046 1047 // FIXME: Provide a source location here. 1048 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This, 1049 /*ImplicitParam=*/nullptr, 1050 /*ImplicitParamTy=*/QualType(), nullptr, nullptr); 1051 } 1052 1053 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1054 const CXXRecordDecl *RD) { 1055 MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext(); 1056 VPtrInfoVector VFPtrs = VFTContext.getVFPtrOffsets(RD); 1057 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1058 1059 for (VPtrInfo *Info : VFPtrs) { 1060 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC); 1061 if (VTable->hasInitializer()) 1062 continue; 1063 if (getContext().getLangOpts().RTTI) 1064 CGM.getMSCompleteObjectLocator(RD, Info); 1065 1066 const VTableLayout &VTLayout = 1067 VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC); 1068 llvm::Constant *Init = CGVT.CreateVTableInitializer( 1069 RD, VTLayout.vtable_component_begin(), 1070 VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(), 1071 VTLayout.getNumVTableThunks()); 1072 VTable->setInitializer(Init); 1073 1074 VTable->setLinkage(Linkage); 1075 1076 CGM.setGlobalVisibility(VTable, RD); 1077 } 1078 } 1079 1080 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor( 1081 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1082 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 1083 NeedsVirtualOffset = (NearestVBase != nullptr); 1084 1085 llvm::Value *VTableAddressPoint = 1086 getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1087 if (!VTableAddressPoint) { 1088 assert(Base.getBase()->getNumVBases() && 1089 !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr()); 1090 } 1091 return VTableAddressPoint; 1092 } 1093 1094 static void mangleVFTableName(MicrosoftMangleContext &MangleContext, 1095 const CXXRecordDecl *RD, const VPtrInfo *VFPtr, 1096 SmallString<256> &Name) { 1097 llvm::raw_svector_ostream Out(Name); 1098 MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out); 1099 } 1100 1101 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr( 1102 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1103 llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset()); 1104 assert(VTable && "Couldn't find a vftable for the given base?"); 1105 return VTable; 1106 } 1107 1108 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1109 CharUnits VPtrOffset) { 1110 // getAddrOfVTable may return 0 if asked to get an address of a vtable which 1111 // shouldn't be used in the given record type. We want to cache this result in 1112 // VFTablesMap, thus a simple zero check is not sufficient. 1113 VFTableIdTy ID(RD, VPtrOffset); 1114 VFTablesMapTy::iterator I; 1115 bool Inserted; 1116 std::tie(I, Inserted) = VFTablesMap.insert(std::make_pair(ID, nullptr)); 1117 if (!Inserted) 1118 return I->second; 1119 1120 llvm::GlobalVariable *&VTable = I->second; 1121 1122 MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext(); 1123 const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD); 1124 1125 if (DeferredVFTables.insert(RD)) { 1126 // We haven't processed this record type before. 1127 // Queue up this v-table for possible deferred emission. 1128 CGM.addDeferredVTable(RD); 1129 1130 #ifndef NDEBUG 1131 // Create all the vftables at once in order to make sure each vftable has 1132 // a unique mangled name. 1133 llvm::StringSet<> ObservedMangledNames; 1134 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1135 SmallString<256> Name; 1136 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 1137 if (!ObservedMangledNames.insert(Name.str())) 1138 llvm_unreachable("Already saw this mangling before?"); 1139 } 1140 #endif 1141 } 1142 1143 for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) { 1144 if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset) 1145 continue; 1146 1147 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 1148 CGM.Int8PtrTy, 1149 VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC) 1150 .getNumVTableComponents()); 1151 1152 SmallString<256> Name; 1153 mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name); 1154 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1155 Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage); 1156 VTable->setUnnamedAddr(true); 1157 if (RD->hasAttr<DLLImportAttr>()) 1158 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1159 else if (RD->hasAttr<DLLExportAttr>()) 1160 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1161 break; 1162 } 1163 1164 return VTable; 1165 } 1166 1167 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1168 GlobalDecl GD, 1169 llvm::Value *This, 1170 llvm::Type *Ty) { 1171 GD = GD.getCanonicalDecl(); 1172 CGBuilderTy &Builder = CGF.Builder; 1173 1174 Ty = Ty->getPointerTo()->getPointerTo(); 1175 llvm::Value *VPtr = 1176 adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1177 llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty); 1178 1179 MicrosoftVTableContext::MethodVFTableLocation ML = 1180 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); 1181 llvm::Value *VFuncPtr = 1182 Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1183 return Builder.CreateLoad(VFuncPtr); 1184 } 1185 1186 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 1187 const CXXDestructorDecl *Dtor, 1188 CXXDtorType DtorType, 1189 SourceLocation CallLoc, 1190 llvm::Value *This) { 1191 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1192 1193 // We have only one destructor in the vftable but can get both behaviors 1194 // by passing an implicit int parameter. 1195 GlobalDecl GD(Dtor, Dtor_Deleting); 1196 const CGFunctionInfo *FInfo = 1197 &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting); 1198 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1199 llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty); 1200 1201 ASTContext &Context = CGF.getContext(); 1202 llvm::Value *ImplicitParam = 1203 llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()), 1204 DtorType == Dtor_Deleting); 1205 1206 This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true); 1207 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 1208 ImplicitParam, Context.IntTy, nullptr, nullptr); 1209 } 1210 1211 const VBTableGlobals & 1212 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) { 1213 // At this layer, we can key the cache off of a single class, which is much 1214 // easier than caching each vbtable individually. 1215 llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry; 1216 bool Added; 1217 std::tie(Entry, Added) = 1218 VBTablesMap.insert(std::make_pair(RD, VBTableGlobals())); 1219 VBTableGlobals &VBGlobals = Entry->second; 1220 if (!Added) 1221 return VBGlobals; 1222 1223 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1224 VBGlobals.VBTables = &Context.enumerateVBTables(RD); 1225 1226 // Cache the globals for all vbtables so we don't have to recompute the 1227 // mangled names. 1228 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1229 for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(), 1230 E = VBGlobals.VBTables->end(); 1231 I != E; ++I) { 1232 VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage)); 1233 } 1234 1235 return VBGlobals; 1236 } 1237 1238 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk( 1239 const CXXMethodDecl *MD, 1240 const MicrosoftVTableContext::MethodVFTableLocation &ML) { 1241 // Calculate the mangled name. 1242 SmallString<256> ThunkName; 1243 llvm::raw_svector_ostream Out(ThunkName); 1244 getMangleContext().mangleVirtualMemPtrThunk(MD, Out); 1245 Out.flush(); 1246 1247 // If the thunk has been generated previously, just return it. 1248 if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName)) 1249 return cast<llvm::Function>(GV); 1250 1251 // Create the llvm::Function. 1252 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD); 1253 llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo); 1254 llvm::Function *ThunkFn = 1255 llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage, 1256 ThunkName.str(), &CGM.getModule()); 1257 assert(ThunkFn->getName() == ThunkName && "name was uniqued!"); 1258 1259 ThunkFn->setLinkage(MD->isExternallyVisible() 1260 ? llvm::GlobalValue::LinkOnceODRLinkage 1261 : llvm::GlobalValue::InternalLinkage); 1262 1263 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn); 1264 CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn); 1265 1266 // Start codegen. 1267 CodeGenFunction CGF(CGM); 1268 CGF.StartThunk(ThunkFn, MD, FnInfo); 1269 1270 // Load the vfptr and then callee from the vftable. The callee should have 1271 // adjusted 'this' so that the vfptr is at offset zero. 1272 llvm::Value *This = CGF.LoadCXXThis(); 1273 llvm::Value *VTable = 1274 CGF.GetVTablePtr(This, ThunkTy->getPointerTo()->getPointerTo()); 1275 llvm::Value *VFuncPtr = 1276 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn"); 1277 llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr); 1278 1279 unsigned CallingConv; 1280 CodeGen::AttributeListType AttributeList; 1281 CGM.ConstructAttributeList(FnInfo, MD, AttributeList, CallingConv, true); 1282 llvm::AttributeSet Attrs = 1283 llvm::AttributeSet::get(CGF.getLLVMContext(), AttributeList); 1284 1285 // Do a musttail call with perfect argument forwarding. Any inalloca argument 1286 // will be forwarded in place without any copy. 1287 SmallVector<llvm::Value *, 8> Args; 1288 for (llvm::Argument &A : ThunkFn->args()) 1289 Args.push_back(&A); 1290 llvm::CallInst *Call = CGF.Builder.CreateCall(Callee, Args); 1291 Call->setTailCallKind(llvm::CallInst::TCK_MustTail); 1292 Call->setAttributes(Attrs); 1293 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1294 1295 if (Call->getType()->isVoidTy()) 1296 CGF.Builder.CreateRetVoid(); 1297 else 1298 CGF.Builder.CreateRet(Call); 1299 1300 // Finish the function to maintain CodeGenFunction invariants. 1301 // FIXME: Don't emit unreachable code. 1302 CGF.EmitBlock(CGF.createBasicBlock()); 1303 CGF.FinishFunction(); 1304 1305 return ThunkFn; 1306 } 1307 1308 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1309 const VBTableGlobals &VBGlobals = enumerateVBTables(RD); 1310 for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) { 1311 const VPtrInfo *VBT = (*VBGlobals.VBTables)[I]; 1312 llvm::GlobalVariable *GV = VBGlobals.Globals[I]; 1313 emitVBTableDefinition(*VBT, RD, GV); 1314 } 1315 } 1316 1317 llvm::GlobalVariable * 1318 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD, 1319 llvm::GlobalVariable::LinkageTypes Linkage) { 1320 SmallString<256> OutName; 1321 llvm::raw_svector_ostream Out(OutName); 1322 MicrosoftMangleContext &Mangler = 1323 cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext()); 1324 Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out); 1325 Out.flush(); 1326 StringRef Name = OutName.str(); 1327 1328 llvm::ArrayType *VBTableType = 1329 llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases()); 1330 1331 assert(!CGM.getModule().getNamedGlobal(Name) && 1332 "vbtable with this name already exists: mangling bug?"); 1333 llvm::GlobalVariable *GV = 1334 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage); 1335 GV->setUnnamedAddr(true); 1336 1337 if (RD->hasAttr<DLLImportAttr>()) 1338 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1339 else if (RD->hasAttr<DLLExportAttr>()) 1340 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1341 1342 return GV; 1343 } 1344 1345 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT, 1346 const CXXRecordDecl *RD, 1347 llvm::GlobalVariable *GV) const { 1348 const CXXRecordDecl *ReusingBase = VBT.ReusingBase; 1349 1350 assert(RD->getNumVBases() && ReusingBase->getNumVBases() && 1351 "should only emit vbtables for classes with vbtables"); 1352 1353 const ASTRecordLayout &BaseLayout = 1354 CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr); 1355 const ASTRecordLayout &DerivedLayout = 1356 CGM.getContext().getASTRecordLayout(RD); 1357 1358 SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(), 1359 nullptr); 1360 1361 // The offset from ReusingBase's vbptr to itself always leads. 1362 CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset(); 1363 Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity()); 1364 1365 MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext(); 1366 for (const auto &I : ReusingBase->vbases()) { 1367 const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl(); 1368 CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase); 1369 assert(!Offset.isNegative()); 1370 1371 // Make it relative to the subobject vbptr. 1372 CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset; 1373 if (VBT.getVBaseWithVPtr()) 1374 CompleteVBPtrOffset += 1375 DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr()); 1376 Offset -= CompleteVBPtrOffset; 1377 1378 unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase); 1379 assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?"); 1380 Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity()); 1381 } 1382 1383 assert(Offsets.size() == 1384 cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType()) 1385 ->getElementType())->getNumElements()); 1386 llvm::ArrayType *VBTableType = 1387 llvm::ArrayType::get(CGM.IntTy, Offsets.size()); 1388 llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets); 1389 GV->setInitializer(Init); 1390 1391 // Set the right visibility. 1392 CGM.setGlobalVisibility(GV, RD); 1393 } 1394 1395 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1396 llvm::Value *This, 1397 const ThisAdjustment &TA) { 1398 if (TA.isEmpty()) 1399 return This; 1400 1401 llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy); 1402 1403 if (!TA.Virtual.isEmpty()) { 1404 assert(TA.Virtual.Microsoft.VtordispOffset < 0); 1405 // Adjust the this argument based on the vtordisp value. 1406 llvm::Value *VtorDispPtr = 1407 CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset); 1408 VtorDispPtr = 1409 CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo()); 1410 llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp"); 1411 V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp)); 1412 1413 if (TA.Virtual.Microsoft.VBPtrOffset) { 1414 // If the final overrider is defined in a virtual base other than the one 1415 // that holds the vfptr, we have to use a vtordispex thunk which looks up 1416 // the vbtable of the derived class. 1417 assert(TA.Virtual.Microsoft.VBPtrOffset > 0); 1418 assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0); 1419 llvm::Value *VBPtr; 1420 llvm::Value *VBaseOffset = 1421 GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset, 1422 TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr); 1423 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1424 } 1425 } 1426 1427 if (TA.NonVirtual) { 1428 // Non-virtual adjustment might result in a pointer outside the allocated 1429 // object, e.g. if the final overrider class is laid out after the virtual 1430 // base that declares a method in the most derived class. 1431 V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual); 1432 } 1433 1434 // Don't need to bitcast back, the call CodeGen will handle this. 1435 return V; 1436 } 1437 1438 llvm::Value * 1439 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1440 const ReturnAdjustment &RA) { 1441 if (RA.isEmpty()) 1442 return Ret; 1443 1444 llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy); 1445 1446 if (RA.Virtual.Microsoft.VBIndex) { 1447 assert(RA.Virtual.Microsoft.VBIndex > 0); 1448 int32_t IntSize = 1449 getContext().getTypeSizeInChars(getContext().IntTy).getQuantity(); 1450 llvm::Value *VBPtr; 1451 llvm::Value *VBaseOffset = 1452 GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset, 1453 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr); 1454 V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset); 1455 } 1456 1457 if (RA.NonVirtual) 1458 V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual); 1459 1460 // Cast back to the original type. 1461 return CGF.Builder.CreateBitCast(V, Ret->getType()); 1462 } 1463 1464 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr, 1465 QualType elementType) { 1466 // Microsoft seems to completely ignore the possibility of a 1467 // two-argument usual deallocation function. 1468 return elementType.isDestructedType(); 1469 } 1470 1471 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) { 1472 // Microsoft seems to completely ignore the possibility of a 1473 // two-argument usual deallocation function. 1474 return expr->getAllocatedType().isDestructedType(); 1475 } 1476 1477 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) { 1478 // The array cookie is always a size_t; we then pad that out to the 1479 // alignment of the element type. 1480 ASTContext &Ctx = getContext(); 1481 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 1482 Ctx.getTypeAlignInChars(type)); 1483 } 1484 1485 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1486 llvm::Value *allocPtr, 1487 CharUnits cookieSize) { 1488 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1489 llvm::Value *numElementsPtr = 1490 CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS)); 1491 return CGF.Builder.CreateLoad(numElementsPtr); 1492 } 1493 1494 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1495 llvm::Value *newPtr, 1496 llvm::Value *numElements, 1497 const CXXNewExpr *expr, 1498 QualType elementType) { 1499 assert(requiresArrayCookie(expr)); 1500 1501 // The size of the cookie. 1502 CharUnits cookieSize = getArrayCookieSizeImpl(elementType); 1503 1504 // Compute an offset to the cookie. 1505 llvm::Value *cookiePtr = newPtr; 1506 1507 // Write the number of elements into the appropriate slot. 1508 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1509 llvm::Value *numElementsPtr 1510 = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS)); 1511 CGF.Builder.CreateStore(numElements, numElementsPtr); 1512 1513 // Finally, compute a pointer to the actual data buffer by skipping 1514 // over the cookie completely. 1515 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1516 cookieSize.getQuantity()); 1517 } 1518 1519 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 1520 llvm::GlobalVariable *GV, 1521 bool PerformInit) { 1522 // MSVC only uses guards for static locals. 1523 if (!D.isStaticLocal()) { 1524 assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()); 1525 // GlobalOpt is allowed to discard the initializer, so use linkonce_odr. 1526 CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage); 1527 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1528 return; 1529 } 1530 1531 // MSVC always uses an i32 bitfield to guard initialization, which is *not* 1532 // threadsafe. Since the user may be linking in inline functions compiled by 1533 // cl.exe, there's no reason to provide a false sense of security by using 1534 // critical sections here. 1535 1536 if (D.getTLSKind()) 1537 CGM.ErrorUnsupported(&D, "dynamic TLS initialization"); 1538 1539 CGBuilderTy &Builder = CGF.Builder; 1540 llvm::IntegerType *GuardTy = CGF.Int32Ty; 1541 llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0); 1542 1543 // Get the guard variable for this function if we have one already. 1544 GuardInfo *GI = &GuardVariableMap[D.getDeclContext()]; 1545 1546 unsigned BitIndex; 1547 if (D.isStaticLocal() && D.isExternallyVisible()) { 1548 // Externally visible variables have to be numbered in Sema to properly 1549 // handle unreachable VarDecls. 1550 BitIndex = getContext().getStaticLocalNumber(&D); 1551 assert(BitIndex > 0); 1552 BitIndex--; 1553 } else { 1554 // Non-externally visible variables are numbered here in CodeGen. 1555 BitIndex = GI->BitIndex++; 1556 } 1557 1558 if (BitIndex >= 32) { 1559 if (D.isExternallyVisible()) 1560 ErrorUnsupportedABI(CGF, "more than 32 guarded initializations"); 1561 BitIndex %= 32; 1562 GI->Guard = nullptr; 1563 } 1564 1565 // Lazily create the i32 bitfield for this function. 1566 if (!GI->Guard) { 1567 // Mangle the name for the guard. 1568 SmallString<256> GuardName; 1569 { 1570 llvm::raw_svector_ostream Out(GuardName); 1571 getMangleContext().mangleStaticGuardVariable(&D, Out); 1572 Out.flush(); 1573 } 1574 1575 // Create the guard variable with a zero-initializer. Just absorb linkage, 1576 // visibility and dll storage class from the guarded variable. 1577 GI->Guard = 1578 new llvm::GlobalVariable(CGM.getModule(), GuardTy, false, 1579 GV->getLinkage(), Zero, GuardName.str()); 1580 GI->Guard->setVisibility(GV->getVisibility()); 1581 GI->Guard->setDLLStorageClass(GV->getDLLStorageClass()); 1582 } else { 1583 assert(GI->Guard->getLinkage() == GV->getLinkage() && 1584 "static local from the same function had different linkage"); 1585 } 1586 1587 // Pseudo code for the test: 1588 // if (!(GuardVar & MyGuardBit)) { 1589 // GuardVar |= MyGuardBit; 1590 // ... initialize the object ...; 1591 // } 1592 1593 // Test our bit from the guard variable. 1594 llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex); 1595 llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard); 1596 llvm::Value *IsInitialized = 1597 Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero); 1598 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1599 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1600 Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock); 1601 1602 // Set our bit in the guard variable and emit the initializer and add a global 1603 // destructor if appropriate. 1604 CGF.EmitBlock(InitBlock); 1605 Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard); 1606 CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit); 1607 Builder.CreateBr(EndBlock); 1608 1609 // Continue. 1610 CGF.EmitBlock(EndBlock); 1611 } 1612 1613 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 1614 // Null-ness for function memptrs only depends on the first field, which is 1615 // the function pointer. The rest don't matter, so we can zero initialize. 1616 if (MPT->isMemberFunctionPointer()) 1617 return true; 1618 1619 // The virtual base adjustment field is always -1 for null, so if we have one 1620 // we can't zero initialize. The field offset is sometimes also -1 if 0 is a 1621 // valid field offset. 1622 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1623 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1624 return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) && 1625 RD->nullFieldOffsetIsZero()); 1626 } 1627 1628 llvm::Type * 1629 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 1630 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1631 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1632 llvm::SmallVector<llvm::Type *, 4> fields; 1633 if (MPT->isMemberFunctionPointer()) 1634 fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk 1635 else 1636 fields.push_back(CGM.IntTy); // FieldOffset 1637 1638 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1639 Inheritance)) 1640 fields.push_back(CGM.IntTy); 1641 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1642 fields.push_back(CGM.IntTy); 1643 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1644 fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset 1645 1646 if (fields.size() == 1) 1647 return fields[0]; 1648 return llvm::StructType::get(CGM.getLLVMContext(), fields); 1649 } 1650 1651 void MicrosoftCXXABI:: 1652 GetNullMemberPointerFields(const MemberPointerType *MPT, 1653 llvm::SmallVectorImpl<llvm::Constant *> &fields) { 1654 assert(fields.empty()); 1655 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1656 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1657 if (MPT->isMemberFunctionPointer()) { 1658 // FunctionPointerOrVirtualThunk 1659 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1660 } else { 1661 if (RD->nullFieldOffsetIsZero()) 1662 fields.push_back(getZeroInt()); // FieldOffset 1663 else 1664 fields.push_back(getAllOnesInt()); // FieldOffset 1665 } 1666 1667 if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(), 1668 Inheritance)) 1669 fields.push_back(getZeroInt()); 1670 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 1671 fields.push_back(getZeroInt()); 1672 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1673 fields.push_back(getAllOnesInt()); 1674 } 1675 1676 llvm::Constant * 1677 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 1678 llvm::SmallVector<llvm::Constant *, 4> fields; 1679 GetNullMemberPointerFields(MPT, fields); 1680 if (fields.size() == 1) 1681 return fields[0]; 1682 llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields); 1683 assert(Res->getType() == ConvertMemberPointerType(MPT)); 1684 return Res; 1685 } 1686 1687 llvm::Constant * 1688 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField, 1689 bool IsMemberFunction, 1690 const CXXRecordDecl *RD, 1691 CharUnits NonVirtualBaseAdjustment) 1692 { 1693 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1694 1695 // Single inheritance class member pointer are represented as scalars instead 1696 // of aggregates. 1697 if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance)) 1698 return FirstField; 1699 1700 llvm::SmallVector<llvm::Constant *, 4> fields; 1701 fields.push_back(FirstField); 1702 1703 if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance)) 1704 fields.push_back(llvm::ConstantInt::get( 1705 CGM.IntTy, NonVirtualBaseAdjustment.getQuantity())); 1706 1707 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) { 1708 CharUnits Offs = CharUnits::Zero(); 1709 if (RD->getNumVBases()) 1710 Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1711 fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity())); 1712 } 1713 1714 // The rest of the fields are adjusted by conversions to a more derived class. 1715 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 1716 fields.push_back(getZeroInt()); 1717 1718 return llvm::ConstantStruct::getAnon(fields); 1719 } 1720 1721 llvm::Constant * 1722 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 1723 CharUnits offset) { 1724 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1725 llvm::Constant *FirstField = 1726 llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity()); 1727 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD, 1728 CharUnits::Zero()); 1729 } 1730 1731 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 1732 return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero()); 1733 } 1734 1735 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, 1736 QualType MPType) { 1737 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 1738 const ValueDecl *MPD = MP.getMemberPointerDecl(); 1739 if (!MPD) 1740 return EmitNullMemberPointer(MPT); 1741 1742 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 1743 1744 // FIXME PR15713: Support virtual inheritance paths. 1745 1746 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 1747 return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD, 1748 ThisAdjustment); 1749 1750 CharUnits FieldOffset = 1751 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 1752 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 1753 } 1754 1755 llvm::Constant * 1756 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD, 1757 const CXXMethodDecl *MD, 1758 CharUnits NonVirtualBaseAdjustment) { 1759 assert(MD->isInstance() && "Member function must not be static!"); 1760 MD = MD->getCanonicalDecl(); 1761 RD = RD->getMostRecentDecl(); 1762 CodeGenTypes &Types = CGM.getTypes(); 1763 1764 llvm::Constant *FirstField; 1765 if (!MD->isVirtual()) { 1766 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1767 llvm::Type *Ty; 1768 // Check whether the function has a computable LLVM signature. 1769 if (Types.isFuncTypeConvertible(FPT)) { 1770 // The function has a computable LLVM signature; use the correct type. 1771 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 1772 } else { 1773 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 1774 // function type is incomplete. 1775 Ty = CGM.PtrDiffTy; 1776 } 1777 FirstField = CGM.GetAddrOfFunction(MD, Ty); 1778 FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy); 1779 } else { 1780 MicrosoftVTableContext::MethodVFTableLocation ML = 1781 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD); 1782 if (MD->isVariadic()) { 1783 CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function"); 1784 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1785 } else if (!CGM.getTypes().isFuncTypeConvertible( 1786 MD->getType()->castAs<FunctionType>())) { 1787 CGM.ErrorUnsupported(MD, "pointer to virtual member function with " 1788 "incomplete return or parameter type"); 1789 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1790 } else if (ML.VBase) { 1791 CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding " 1792 "member function in virtual base class"); 1793 FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy); 1794 } else { 1795 llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML); 1796 FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy); 1797 // Include the vfptr adjustment if the method is in a non-primary vftable. 1798 NonVirtualBaseAdjustment += ML.VFPtrOffset; 1799 } 1800 } 1801 1802 // The rest of the fields are common with data member pointers. 1803 return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD, 1804 NonVirtualBaseAdjustment); 1805 } 1806 1807 /// Member pointers are the same if they're either bitwise identical *or* both 1808 /// null. Null-ness for function members is determined by the first field, 1809 /// while for data member pointers we must compare all fields. 1810 llvm::Value * 1811 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 1812 llvm::Value *L, 1813 llvm::Value *R, 1814 const MemberPointerType *MPT, 1815 bool Inequality) { 1816 CGBuilderTy &Builder = CGF.Builder; 1817 1818 // Handle != comparisons by switching the sense of all boolean operations. 1819 llvm::ICmpInst::Predicate Eq; 1820 llvm::Instruction::BinaryOps And, Or; 1821 if (Inequality) { 1822 Eq = llvm::ICmpInst::ICMP_NE; 1823 And = llvm::Instruction::Or; 1824 Or = llvm::Instruction::And; 1825 } else { 1826 Eq = llvm::ICmpInst::ICMP_EQ; 1827 And = llvm::Instruction::And; 1828 Or = llvm::Instruction::Or; 1829 } 1830 1831 // If this is a single field member pointer (single inheritance), this is a 1832 // single icmp. 1833 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 1834 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 1835 if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(), 1836 Inheritance)) 1837 return Builder.CreateICmp(Eq, L, R); 1838 1839 // Compare the first field. 1840 llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0"); 1841 llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0"); 1842 llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first"); 1843 1844 // Compare everything other than the first field. 1845 llvm::Value *Res = nullptr; 1846 llvm::StructType *LType = cast<llvm::StructType>(L->getType()); 1847 for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) { 1848 llvm::Value *LF = Builder.CreateExtractValue(L, I); 1849 llvm::Value *RF = Builder.CreateExtractValue(R, I); 1850 llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest"); 1851 if (Res) 1852 Res = Builder.CreateBinOp(And, Res, Cmp); 1853 else 1854 Res = Cmp; 1855 } 1856 1857 // Check if the first field is 0 if this is a function pointer. 1858 if (MPT->isMemberFunctionPointer()) { 1859 // (l1 == r1 && ...) || l0 == 0 1860 llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType()); 1861 llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero"); 1862 Res = Builder.CreateBinOp(Or, Res, IsZero); 1863 } 1864 1865 // Combine the comparison of the first field, which must always be true for 1866 // this comparison to succeeed. 1867 return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp"); 1868 } 1869 1870 llvm::Value * 1871 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 1872 llvm::Value *MemPtr, 1873 const MemberPointerType *MPT) { 1874 CGBuilderTy &Builder = CGF.Builder; 1875 llvm::SmallVector<llvm::Constant *, 4> fields; 1876 // We only need one field for member functions. 1877 if (MPT->isMemberFunctionPointer()) 1878 fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy)); 1879 else 1880 GetNullMemberPointerFields(MPT, fields); 1881 assert(!fields.empty()); 1882 llvm::Value *FirstField = MemPtr; 1883 if (MemPtr->getType()->isStructTy()) 1884 FirstField = Builder.CreateExtractValue(MemPtr, 0); 1885 llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0"); 1886 1887 // For function member pointers, we only need to test the function pointer 1888 // field. The other fields if any can be garbage. 1889 if (MPT->isMemberFunctionPointer()) 1890 return Res; 1891 1892 // Otherwise, emit a series of compares and combine the results. 1893 for (int I = 1, E = fields.size(); I < E; ++I) { 1894 llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I); 1895 llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp"); 1896 Res = Builder.CreateOr(Res, Next, "memptr.tobool"); 1897 } 1898 return Res; 1899 } 1900 1901 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT, 1902 llvm::Constant *Val) { 1903 // Function pointers are null if the pointer in the first field is null. 1904 if (MPT->isMemberFunctionPointer()) { 1905 llvm::Constant *FirstField = Val->getType()->isStructTy() ? 1906 Val->getAggregateElement(0U) : Val; 1907 return FirstField->isNullValue(); 1908 } 1909 1910 // If it's not a function pointer and it's zero initializable, we can easily 1911 // check zero. 1912 if (isZeroInitializable(MPT) && Val->isNullValue()) 1913 return true; 1914 1915 // Otherwise, break down all the fields for comparison. Hopefully these 1916 // little Constants are reused, while a big null struct might not be. 1917 llvm::SmallVector<llvm::Constant *, 4> Fields; 1918 GetNullMemberPointerFields(MPT, Fields); 1919 if (Fields.size() == 1) { 1920 assert(Val->getType()->isIntegerTy()); 1921 return Val == Fields[0]; 1922 } 1923 1924 unsigned I, E; 1925 for (I = 0, E = Fields.size(); I != E; ++I) { 1926 if (Val->getAggregateElement(I) != Fields[I]) 1927 break; 1928 } 1929 return I == E; 1930 } 1931 1932 llvm::Value * 1933 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF, 1934 llvm::Value *This, 1935 llvm::Value *VBPtrOffset, 1936 llvm::Value *VBTableOffset, 1937 llvm::Value **VBPtrOut) { 1938 CGBuilderTy &Builder = CGF.Builder; 1939 // Load the vbtable pointer from the vbptr in the instance. 1940 This = Builder.CreateBitCast(This, CGM.Int8PtrTy); 1941 llvm::Value *VBPtr = 1942 Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr"); 1943 if (VBPtrOut) *VBPtrOut = VBPtr; 1944 VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0)); 1945 llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable"); 1946 1947 // Load an i32 offset from the vb-table. 1948 llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset); 1949 VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0)); 1950 return Builder.CreateLoad(VBaseOffs, "vbase_offs"); 1951 } 1952 1953 // Returns an adjusted base cast to i8*, since we do more address arithmetic on 1954 // it. 1955 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase( 1956 CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD, 1957 llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) { 1958 CGBuilderTy &Builder = CGF.Builder; 1959 Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy); 1960 llvm::BasicBlock *OriginalBB = nullptr; 1961 llvm::BasicBlock *SkipAdjustBB = nullptr; 1962 llvm::BasicBlock *VBaseAdjustBB = nullptr; 1963 1964 // In the unspecified inheritance model, there might not be a vbtable at all, 1965 // in which case we need to skip the virtual base lookup. If there is a 1966 // vbtable, the first entry is a no-op entry that gives back the original 1967 // base, so look for a virtual base adjustment offset of zero. 1968 if (VBPtrOffset) { 1969 OriginalBB = Builder.GetInsertBlock(); 1970 VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust"); 1971 SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust"); 1972 llvm::Value *IsVirtual = 1973 Builder.CreateICmpNE(VBTableOffset, getZeroInt(), 1974 "memptr.is_vbase"); 1975 Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB); 1976 CGF.EmitBlock(VBaseAdjustBB); 1977 } 1978 1979 // If we weren't given a dynamic vbptr offset, RD should be complete and we'll 1980 // know the vbptr offset. 1981 if (!VBPtrOffset) { 1982 CharUnits offs = CharUnits::Zero(); 1983 if (!RD->hasDefinition()) { 1984 DiagnosticsEngine &Diags = CGF.CGM.getDiags(); 1985 unsigned DiagID = Diags.getCustomDiagID( 1986 DiagnosticsEngine::Error, 1987 "member pointer representation requires a " 1988 "complete class type for %0 to perform this expression"); 1989 Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange(); 1990 } else if (RD->getNumVBases()) 1991 offs = getContext().getASTRecordLayout(RD).getVBPtrOffset(); 1992 VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity()); 1993 } 1994 llvm::Value *VBPtr = nullptr; 1995 llvm::Value *VBaseOffs = 1996 GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr); 1997 llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs); 1998 1999 // Merge control flow with the case where we didn't have to adjust. 2000 if (VBaseAdjustBB) { 2001 Builder.CreateBr(SkipAdjustBB); 2002 CGF.EmitBlock(SkipAdjustBB); 2003 llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base"); 2004 Phi->addIncoming(Base, OriginalBB); 2005 Phi->addIncoming(AdjustedBase, VBaseAdjustBB); 2006 return Phi; 2007 } 2008 return AdjustedBase; 2009 } 2010 2011 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress( 2012 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 2013 const MemberPointerType *MPT) { 2014 assert(MPT->isMemberDataPointer()); 2015 unsigned AS = Base->getType()->getPointerAddressSpace(); 2016 llvm::Type *PType = 2017 CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 2018 CGBuilderTy &Builder = CGF.Builder; 2019 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2020 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2021 2022 // Extract the fields we need, regardless of model. We'll apply them if we 2023 // have them. 2024 llvm::Value *FieldOffset = MemPtr; 2025 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2026 llvm::Value *VBPtrOffset = nullptr; 2027 if (MemPtr->getType()->isStructTy()) { 2028 // We need to extract values. 2029 unsigned I = 0; 2030 FieldOffset = Builder.CreateExtractValue(MemPtr, I++); 2031 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2032 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2033 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2034 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2035 } 2036 2037 if (VirtualBaseAdjustmentOffset) { 2038 Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset, 2039 VBPtrOffset); 2040 } 2041 2042 // Cast to char*. 2043 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 2044 2045 // Apply the offset, which we assume is non-null. 2046 llvm::Value *Addr = 2047 Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset"); 2048 2049 // Cast the address to the appropriate pointer type, adopting the address 2050 // space of the base pointer. 2051 return Builder.CreateBitCast(Addr, PType); 2052 } 2053 2054 static MSInheritanceAttr::Spelling 2055 getInheritanceFromMemptr(const MemberPointerType *MPT) { 2056 return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel(); 2057 } 2058 2059 llvm::Value * 2060 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 2061 const CastExpr *E, 2062 llvm::Value *Src) { 2063 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 2064 E->getCastKind() == CK_BaseToDerivedMemberPointer || 2065 E->getCastKind() == CK_ReinterpretMemberPointer); 2066 2067 // Use constant emission if we can. 2068 if (isa<llvm::Constant>(Src)) 2069 return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src)); 2070 2071 // We may be adding or dropping fields from the member pointer, so we need 2072 // both types and the inheritance models of both records. 2073 const MemberPointerType *SrcTy = 2074 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 2075 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 2076 bool IsFunc = SrcTy->isMemberFunctionPointer(); 2077 2078 // If the classes use the same null representation, reinterpret_cast is a nop. 2079 bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer; 2080 if (IsReinterpret && IsFunc) 2081 return Src; 2082 2083 CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl(); 2084 CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl(); 2085 if (IsReinterpret && 2086 SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero()) 2087 return Src; 2088 2089 CGBuilderTy &Builder = CGF.Builder; 2090 2091 // Branch past the conversion if Src is null. 2092 llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy); 2093 llvm::Constant *DstNull = EmitNullMemberPointer(DstTy); 2094 2095 // C++ 5.2.10p9: The null member pointer value is converted to the null member 2096 // pointer value of the destination type. 2097 if (IsReinterpret) { 2098 // For reinterpret casts, sema ensures that src and dst are both functions 2099 // or data and have the same size, which means the LLVM types should match. 2100 assert(Src->getType() == DstNull->getType()); 2101 return Builder.CreateSelect(IsNotNull, Src, DstNull); 2102 } 2103 2104 llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock(); 2105 llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert"); 2106 llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted"); 2107 Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB); 2108 CGF.EmitBlock(ConvertBB); 2109 2110 // Decompose src. 2111 llvm::Value *FirstField = Src; 2112 llvm::Value *NonVirtualBaseAdjustment = nullptr; 2113 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2114 llvm::Value *VBPtrOffset = nullptr; 2115 MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel(); 2116 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 2117 // We need to extract values. 2118 unsigned I = 0; 2119 FirstField = Builder.CreateExtractValue(Src, I++); 2120 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 2121 NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++); 2122 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 2123 VBPtrOffset = Builder.CreateExtractValue(Src, I++); 2124 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 2125 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++); 2126 } 2127 2128 // For data pointers, we adjust the field offset directly. For functions, we 2129 // have a separate field. 2130 llvm::Constant *Adj = getMemberPointerAdjustment(E); 2131 if (Adj) { 2132 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 2133 llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField; 2134 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 2135 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 2136 NVAdjustField = getZeroInt(); 2137 if (isDerivedToBase) 2138 NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj"); 2139 else 2140 NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj"); 2141 } 2142 2143 // FIXME PR15713: Support conversions through virtually derived classes. 2144 2145 // Recompose dst from the null struct and the adjusted fields from src. 2146 MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel(); 2147 llvm::Value *Dst; 2148 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) { 2149 Dst = FirstField; 2150 } else { 2151 Dst = llvm::UndefValue::get(DstNull->getType()); 2152 unsigned Idx = 0; 2153 Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++); 2154 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 2155 Dst = Builder.CreateInsertValue( 2156 Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++); 2157 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 2158 Dst = Builder.CreateInsertValue( 2159 Dst, getValueOrZeroInt(VBPtrOffset), Idx++); 2160 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 2161 Dst = Builder.CreateInsertValue( 2162 Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++); 2163 } 2164 Builder.CreateBr(ContinueBB); 2165 2166 // In the continuation, choose between DstNull and Dst. 2167 CGF.EmitBlock(ContinueBB); 2168 llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted"); 2169 Phi->addIncoming(DstNull, OriginalBB); 2170 Phi->addIncoming(Dst, ConvertBB); 2171 return Phi; 2172 } 2173 2174 llvm::Constant * 2175 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E, 2176 llvm::Constant *Src) { 2177 const MemberPointerType *SrcTy = 2178 E->getSubExpr()->getType()->castAs<MemberPointerType>(); 2179 const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>(); 2180 2181 // If src is null, emit a new null for dst. We can't return src because dst 2182 // might have a new representation. 2183 if (MemberPointerConstantIsNull(SrcTy, Src)) 2184 return EmitNullMemberPointer(DstTy); 2185 2186 // We don't need to do anything for reinterpret_casts of non-null member 2187 // pointers. We should only get here when the two type representations have 2188 // the same size. 2189 if (E->getCastKind() == CK_ReinterpretMemberPointer) 2190 return Src; 2191 2192 MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy); 2193 MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy); 2194 2195 // Decompose src. 2196 llvm::Constant *FirstField = Src; 2197 llvm::Constant *NonVirtualBaseAdjustment = nullptr; 2198 llvm::Constant *VirtualBaseAdjustmentOffset = nullptr; 2199 llvm::Constant *VBPtrOffset = nullptr; 2200 bool IsFunc = SrcTy->isMemberFunctionPointer(); 2201 if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) { 2202 // We need to extract values. 2203 unsigned I = 0; 2204 FirstField = Src->getAggregateElement(I++); 2205 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance)) 2206 NonVirtualBaseAdjustment = Src->getAggregateElement(I++); 2207 if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance)) 2208 VBPtrOffset = Src->getAggregateElement(I++); 2209 if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance)) 2210 VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++); 2211 } 2212 2213 // For data pointers, we adjust the field offset directly. For functions, we 2214 // have a separate field. 2215 llvm::Constant *Adj = getMemberPointerAdjustment(E); 2216 if (Adj) { 2217 Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy); 2218 llvm::Constant *&NVAdjustField = 2219 IsFunc ? NonVirtualBaseAdjustment : FirstField; 2220 bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 2221 if (!NVAdjustField) // If this field didn't exist in src, it's zero. 2222 NVAdjustField = getZeroInt(); 2223 if (IsDerivedToBase) 2224 NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj); 2225 else 2226 NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj); 2227 } 2228 2229 // FIXME PR15713: Support conversions through virtually derived classes. 2230 2231 // Recompose dst from the null struct and the adjusted fields from src. 2232 if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) 2233 return FirstField; 2234 2235 llvm::SmallVector<llvm::Constant *, 4> Fields; 2236 Fields.push_back(FirstField); 2237 if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance)) 2238 Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment)); 2239 if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance)) 2240 Fields.push_back(getConstantOrZeroInt(VBPtrOffset)); 2241 if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance)) 2242 Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset)); 2243 return llvm::ConstantStruct::getAnon(Fields); 2244 } 2245 2246 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer( 2247 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 2248 llvm::Value *MemPtr, const MemberPointerType *MPT) { 2249 assert(MPT->isMemberFunctionPointer()); 2250 const FunctionProtoType *FPT = 2251 MPT->getPointeeType()->castAs<FunctionProtoType>(); 2252 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl(); 2253 llvm::FunctionType *FTy = 2254 CGM.getTypes().GetFunctionType( 2255 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 2256 CGBuilderTy &Builder = CGF.Builder; 2257 2258 MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel(); 2259 2260 // Extract the fields we need, regardless of model. We'll apply them if we 2261 // have them. 2262 llvm::Value *FunctionPointer = MemPtr; 2263 llvm::Value *NonVirtualBaseAdjustment = nullptr; 2264 llvm::Value *VirtualBaseAdjustmentOffset = nullptr; 2265 llvm::Value *VBPtrOffset = nullptr; 2266 if (MemPtr->getType()->isStructTy()) { 2267 // We need to extract values. 2268 unsigned I = 0; 2269 FunctionPointer = Builder.CreateExtractValue(MemPtr, I++); 2270 if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance)) 2271 NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++); 2272 if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) 2273 VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++); 2274 if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance)) 2275 VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++); 2276 } 2277 2278 if (VirtualBaseAdjustmentOffset) { 2279 This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset, 2280 VBPtrOffset); 2281 } 2282 2283 if (NonVirtualBaseAdjustment) { 2284 // Apply the adjustment and cast back to the original struct type. 2285 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 2286 Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment); 2287 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 2288 } 2289 2290 return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo()); 2291 } 2292 2293 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) { 2294 return new MicrosoftCXXABI(CGM); 2295 } 2296