1 //===------- ItaniumCXXABI.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 Itanium C++ ABI. The class 11 // in this file generates structures that follow the Itanium C++ ABI, which is 12 // documented at: 13 // http://www.codesourcery.com/public/cxx-abi/abi.html 14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html 15 // 16 // It also supports the closely-related ARM ABI, documented at: 17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CGCXXABI.h" 22 #include "CGRecordLayout.h" 23 #include "CGVTables.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenModule.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/Type.h" 28 #include "llvm/IR/CallSite.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Intrinsics.h" 31 #include "llvm/IR/Value.h" 32 33 using namespace clang; 34 using namespace CodeGen; 35 36 namespace { 37 class ItaniumCXXABI : public CodeGen::CGCXXABI { 38 /// VTables - All the vtables which have been defined. 39 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables; 40 41 protected: 42 bool UseARMMethodPtrABI; 43 bool UseARMGuardVarABI; 44 45 ItaniumMangleContext &getMangleContext() { 46 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 47 } 48 49 public: 50 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 51 bool UseARMMethodPtrABI = false, 52 bool UseARMGuardVarABI = false) : 53 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 54 UseARMGuardVarABI(UseARMGuardVarABI) { } 55 56 bool classifyReturnType(CGFunctionInfo &FI) const override; 57 58 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override { 59 // Structures with either a non-trivial destructor or a non-trivial 60 // copy constructor are always indirect. 61 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared 62 // special members. 63 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) 64 return RAA_Indirect; 65 return RAA_Default; 66 } 67 68 bool isZeroInitializable(const MemberPointerType *MPT) override; 69 70 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override; 71 72 llvm::Value * 73 EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 74 const Expr *E, 75 llvm::Value *&This, 76 llvm::Value *MemFnPtr, 77 const MemberPointerType *MPT) override; 78 79 llvm::Value * 80 EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, 81 llvm::Value *Base, 82 llvm::Value *MemPtr, 83 const MemberPointerType *MPT) override; 84 85 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 86 const CastExpr *E, 87 llvm::Value *Src) override; 88 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 89 llvm::Constant *Src) override; 90 91 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override; 92 93 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override; 94 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 95 CharUnits offset) override; 96 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override; 97 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 98 CharUnits ThisAdjustment); 99 100 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 101 llvm::Value *L, llvm::Value *R, 102 const MemberPointerType *MPT, 103 bool Inequality) override; 104 105 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 106 llvm::Value *Addr, 107 const MemberPointerType *MPT) override; 108 109 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr, 110 QualType type) override; 111 112 void EmitFundamentalRTTIDescriptor(QualType Type); 113 void EmitFundamentalRTTIDescriptors(); 114 llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override; 115 116 bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override; 117 void EmitBadTypeidCall(CodeGenFunction &CGF) override; 118 llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, 119 llvm::Value *ThisPtr, 120 llvm::Type *StdTypeInfoPtrTy) override; 121 122 bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 123 QualType SrcRecordTy) override; 124 125 llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 126 QualType SrcRecordTy, QualType DestTy, 127 QualType DestRecordTy, 128 llvm::BasicBlock *CastEnd) override; 129 130 llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value, 131 QualType SrcRecordTy, 132 QualType DestTy) override; 133 134 bool EmitBadCastCall(CodeGenFunction &CGF) override; 135 136 llvm::Value * 137 GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This, 138 const CXXRecordDecl *ClassDecl, 139 const CXXRecordDecl *BaseClassDecl) override; 140 141 void EmitCXXConstructors(const CXXConstructorDecl *D) override; 142 143 void buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 144 SmallVectorImpl<CanQualType> &ArgTys) override; 145 146 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 147 CXXDtorType DT) const override { 148 // Itanium does not emit any destructor variant as an inline thunk. 149 // Delegating may occur as an optimization, but all variants are either 150 // emitted with external linkage or as linkonce if they are inline and used. 151 return false; 152 } 153 154 void EmitCXXDestructors(const CXXDestructorDecl *D) override; 155 156 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 157 FunctionArgList &Params) override; 158 159 void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override; 160 161 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 162 const CXXConstructorDecl *D, 163 CXXCtorType Type, bool ForVirtualBase, 164 bool Delegating, 165 CallArgList &Args) override; 166 167 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 168 CXXDtorType Type, bool ForVirtualBase, 169 bool Delegating, llvm::Value *This) override; 170 171 void emitVTableDefinitions(CodeGenVTables &CGVT, 172 const CXXRecordDecl *RD) override; 173 174 llvm::Value *getVTableAddressPointInStructor( 175 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 176 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 177 bool &NeedsVirtualOffset) override; 178 179 llvm::Constant * 180 getVTableAddressPointForConstExpr(BaseSubobject Base, 181 const CXXRecordDecl *VTableClass) override; 182 183 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 184 CharUnits VPtrOffset) override; 185 186 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 187 llvm::Value *This, 188 llvm::Type *Ty) override; 189 190 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 191 const CXXDestructorDecl *Dtor, 192 CXXDtorType DtorType, llvm::Value *This, 193 const CXXMemberCallExpr *CE) override; 194 195 void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override; 196 197 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD, 198 bool ReturnAdjustment) override { 199 // Allow inlining of thunks by emitting them with available_externally 200 // linkage together with vtables when needed. 201 if (ForVTable) 202 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 203 } 204 205 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 206 const ThisAdjustment &TA) override; 207 208 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 209 const ReturnAdjustment &RA) override; 210 211 size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, 212 FunctionArgList &Args) const override { 213 assert(!Args.empty() && "expected the arglist to not be empty!"); 214 return Args.size() - 1; 215 } 216 217 StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; } 218 StringRef GetDeletedVirtualCallName() override 219 { return "__cxa_deleted_virtual"; } 220 221 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 222 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 223 llvm::Value *NewPtr, 224 llvm::Value *NumElements, 225 const CXXNewExpr *expr, 226 QualType ElementType) override; 227 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 228 llvm::Value *allocPtr, 229 CharUnits cookieSize) override; 230 231 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 232 llvm::GlobalVariable *DeclPtr, 233 bool PerformInit) override; 234 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 235 llvm::Constant *dtor, llvm::Constant *addr) override; 236 237 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 238 llvm::Value *Val); 239 void EmitThreadLocalInitFuncs( 240 CodeGenModule &CGM, 241 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 242 CXXThreadLocals, 243 ArrayRef<llvm::Function *> CXXThreadLocalInits, 244 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override; 245 246 bool usesThreadWrapperFunction() const override { return true; } 247 LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, 248 QualType LValType) override; 249 250 bool NeedsVTTParameter(GlobalDecl GD) override; 251 252 /**************************** RTTI Uniqueness ******************************/ 253 254 protected: 255 /// Returns true if the ABI requires RTTI type_info objects to be unique 256 /// across a program. 257 virtual bool shouldRTTIBeUnique() const { return true; } 258 259 public: 260 /// What sort of unique-RTTI behavior should we use? 261 enum RTTIUniquenessKind { 262 /// We are guaranteeing, or need to guarantee, that the RTTI string 263 /// is unique. 264 RUK_Unique, 265 266 /// We are not guaranteeing uniqueness for the RTTI string, so we 267 /// can demote to hidden visibility but must use string comparisons. 268 RUK_NonUniqueHidden, 269 270 /// We are not guaranteeing uniqueness for the RTTI string, so we 271 /// have to use string comparisons, but we also have to emit it with 272 /// non-hidden visibility. 273 RUK_NonUniqueVisible 274 }; 275 276 /// Return the required visibility status for the given type and linkage in 277 /// the current ABI. 278 RTTIUniquenessKind 279 classifyRTTIUniqueness(QualType CanTy, 280 llvm::GlobalValue::LinkageTypes Linkage) const; 281 friend class ItaniumRTTIBuilder; 282 283 void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override; 284 }; 285 286 class ARMCXXABI : public ItaniumCXXABI { 287 public: 288 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 289 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 290 /* UseARMGuardVarABI = */ true) {} 291 292 bool HasThisReturn(GlobalDecl GD) const override { 293 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 294 isa<CXXDestructorDecl>(GD.getDecl()) && 295 GD.getDtorType() != Dtor_Deleting)); 296 } 297 298 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, 299 QualType ResTy) override; 300 301 CharUnits getArrayCookieSizeImpl(QualType elementType) override; 302 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 303 llvm::Value *NewPtr, 304 llvm::Value *NumElements, 305 const CXXNewExpr *expr, 306 QualType ElementType) override; 307 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr, 308 CharUnits cookieSize) override; 309 }; 310 311 class iOS64CXXABI : public ARMCXXABI { 312 public: 313 iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {} 314 315 // ARM64 libraries are prepared for non-unique RTTI. 316 bool shouldRTTIBeUnique() const override { return false; } 317 }; 318 } 319 320 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 321 switch (CGM.getTarget().getCXXABI().getKind()) { 322 // For IR-generation purposes, there's no significant difference 323 // between the ARM and iOS ABIs. 324 case TargetCXXABI::GenericARM: 325 case TargetCXXABI::iOS: 326 return new ARMCXXABI(CGM); 327 328 case TargetCXXABI::iOS64: 329 return new iOS64CXXABI(CGM); 330 331 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 332 // include the other 32-bit ARM oddities: constructor/destructor return values 333 // and array cookies. 334 case TargetCXXABI::GenericAArch64: 335 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 336 /* UseARMGuardVarABI = */ true); 337 338 case TargetCXXABI::GenericItanium: 339 if (CGM.getContext().getTargetInfo().getTriple().getArch() 340 == llvm::Triple::le32) { 341 // For PNaCl, use ARM-style method pointers so that PNaCl code 342 // does not assume anything about the alignment of function 343 // pointers. 344 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 345 /* UseARMGuardVarABI = */ false); 346 } 347 return new ItaniumCXXABI(CGM); 348 349 case TargetCXXABI::Microsoft: 350 llvm_unreachable("Microsoft ABI is not Itanium-based"); 351 } 352 llvm_unreachable("bad ABI kind"); 353 } 354 355 llvm::Type * 356 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 357 if (MPT->isMemberDataPointer()) 358 return CGM.PtrDiffTy; 359 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL); 360 } 361 362 /// In the Itanium and ARM ABIs, method pointers have the form: 363 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 364 /// 365 /// In the Itanium ABI: 366 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 367 /// - the this-adjustment is (memptr.adj) 368 /// - the virtual offset is (memptr.ptr - 1) 369 /// 370 /// In the ARM ABI: 371 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 372 /// - the this-adjustment is (memptr.adj >> 1) 373 /// - the virtual offset is (memptr.ptr) 374 /// ARM uses 'adj' for the virtual flag because Thumb functions 375 /// may be only single-byte aligned. 376 /// 377 /// If the member is virtual, the adjusted 'this' pointer points 378 /// to a vtable pointer from which the virtual offset is applied. 379 /// 380 /// If the member is non-virtual, memptr.ptr is the address of 381 /// the function to call. 382 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer( 383 CodeGenFunction &CGF, const Expr *E, llvm::Value *&This, 384 llvm::Value *MemFnPtr, const MemberPointerType *MPT) { 385 CGBuilderTy &Builder = CGF.Builder; 386 387 const FunctionProtoType *FPT = 388 MPT->getPointeeType()->getAs<FunctionProtoType>(); 389 const CXXRecordDecl *RD = 390 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 391 392 llvm::FunctionType *FTy = 393 CGM.getTypes().GetFunctionType( 394 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 395 396 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 397 398 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 399 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 400 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 401 402 // Extract memptr.adj, which is in the second field. 403 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 404 405 // Compute the true adjustment. 406 llvm::Value *Adj = RawAdj; 407 if (UseARMMethodPtrABI) 408 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 409 410 // Apply the adjustment and cast back to the original struct type 411 // for consistency. 412 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 413 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 414 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 415 416 // Load the function pointer. 417 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 418 419 // If the LSB in the function pointer is 1, the function pointer points to 420 // a virtual function. 421 llvm::Value *IsVirtual; 422 if (UseARMMethodPtrABI) 423 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 424 else 425 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 426 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 427 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 428 429 // In the virtual path, the adjustment left 'This' pointing to the 430 // vtable of the correct base subobject. The "function pointer" is an 431 // offset within the vtable (+1 for the virtual flag on non-ARM). 432 CGF.EmitBlock(FnVirtual); 433 434 // Cast the adjusted this to a pointer to vtable pointer and load. 435 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 436 llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy); 437 438 // Apply the offset. 439 llvm::Value *VTableOffset = FnAsInt; 440 if (!UseARMMethodPtrABI) 441 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 442 VTable = Builder.CreateGEP(VTable, VTableOffset); 443 444 // Load the virtual function to call. 445 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 446 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 447 CGF.EmitBranch(FnEnd); 448 449 // In the non-virtual path, the function pointer is actually a 450 // function pointer. 451 CGF.EmitBlock(FnNonVirtual); 452 llvm::Value *NonVirtualFn = 453 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 454 455 // We're done. 456 CGF.EmitBlock(FnEnd); 457 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2); 458 Callee->addIncoming(VirtualFn, FnVirtual); 459 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 460 return Callee; 461 } 462 463 /// Compute an l-value by applying the given pointer-to-member to a 464 /// base object. 465 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress( 466 CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr, 467 const MemberPointerType *MPT) { 468 assert(MemPtr->getType() == CGM.PtrDiffTy); 469 470 CGBuilderTy &Builder = CGF.Builder; 471 472 unsigned AS = Base->getType()->getPointerAddressSpace(); 473 474 // Cast to char*. 475 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 476 477 // Apply the offset, which we assume is non-null. 478 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset"); 479 480 // Cast the address to the appropriate pointer type, adopting the 481 // address space of the base pointer. 482 llvm::Type *PType 483 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 484 return Builder.CreateBitCast(Addr, PType); 485 } 486 487 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 488 /// conversion. 489 /// 490 /// Bitcast conversions are always a no-op under Itanium. 491 /// 492 /// Obligatory offset/adjustment diagram: 493 /// <-- offset --> <-- adjustment --> 494 /// |--------------------------|----------------------|--------------------| 495 /// ^Derived address point ^Base address point ^Member address point 496 /// 497 /// So when converting a base member pointer to a derived member pointer, 498 /// we add the offset to the adjustment because the address point has 499 /// decreased; and conversely, when converting a derived MP to a base MP 500 /// we subtract the offset from the adjustment because the address point 501 /// has increased. 502 /// 503 /// The standard forbids (at compile time) conversion to and from 504 /// virtual bases, which is why we don't have to consider them here. 505 /// 506 /// The standard forbids (at run time) casting a derived MP to a base 507 /// MP when the derived MP does not point to a member of the base. 508 /// This is why -1 is a reasonable choice for null data member 509 /// pointers. 510 llvm::Value * 511 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 512 const CastExpr *E, 513 llvm::Value *src) { 514 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 515 E->getCastKind() == CK_BaseToDerivedMemberPointer || 516 E->getCastKind() == CK_ReinterpretMemberPointer); 517 518 // Under Itanium, reinterprets don't require any additional processing. 519 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 520 521 // Use constant emission if we can. 522 if (isa<llvm::Constant>(src)) 523 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 524 525 llvm::Constant *adj = getMemberPointerAdjustment(E); 526 if (!adj) return src; 527 528 CGBuilderTy &Builder = CGF.Builder; 529 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 530 531 const MemberPointerType *destTy = 532 E->getType()->castAs<MemberPointerType>(); 533 534 // For member data pointers, this is just a matter of adding the 535 // offset if the source is non-null. 536 if (destTy->isMemberDataPointer()) { 537 llvm::Value *dst; 538 if (isDerivedToBase) 539 dst = Builder.CreateNSWSub(src, adj, "adj"); 540 else 541 dst = Builder.CreateNSWAdd(src, adj, "adj"); 542 543 // Null check. 544 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 545 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 546 return Builder.CreateSelect(isNull, src, dst); 547 } 548 549 // The this-adjustment is left-shifted by 1 on ARM. 550 if (UseARMMethodPtrABI) { 551 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 552 offset <<= 1; 553 adj = llvm::ConstantInt::get(adj->getType(), offset); 554 } 555 556 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 557 llvm::Value *dstAdj; 558 if (isDerivedToBase) 559 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 560 else 561 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 562 563 return Builder.CreateInsertValue(src, dstAdj, 1); 564 } 565 566 llvm::Constant * 567 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 568 llvm::Constant *src) { 569 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 570 E->getCastKind() == CK_BaseToDerivedMemberPointer || 571 E->getCastKind() == CK_ReinterpretMemberPointer); 572 573 // Under Itanium, reinterprets don't require any additional processing. 574 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 575 576 // If the adjustment is trivial, we don't need to do anything. 577 llvm::Constant *adj = getMemberPointerAdjustment(E); 578 if (!adj) return src; 579 580 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 581 582 const MemberPointerType *destTy = 583 E->getType()->castAs<MemberPointerType>(); 584 585 // For member data pointers, this is just a matter of adding the 586 // offset if the source is non-null. 587 if (destTy->isMemberDataPointer()) { 588 // null maps to null. 589 if (src->isAllOnesValue()) return src; 590 591 if (isDerivedToBase) 592 return llvm::ConstantExpr::getNSWSub(src, adj); 593 else 594 return llvm::ConstantExpr::getNSWAdd(src, adj); 595 } 596 597 // The this-adjustment is left-shifted by 1 on ARM. 598 if (UseARMMethodPtrABI) { 599 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 600 offset <<= 1; 601 adj = llvm::ConstantInt::get(adj->getType(), offset); 602 } 603 604 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 605 llvm::Constant *dstAdj; 606 if (isDerivedToBase) 607 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 608 else 609 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 610 611 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 612 } 613 614 llvm::Constant * 615 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 616 // Itanium C++ ABI 2.3: 617 // A NULL pointer is represented as -1. 618 if (MPT->isMemberDataPointer()) 619 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 620 621 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 622 llvm::Constant *Values[2] = { Zero, Zero }; 623 return llvm::ConstantStruct::getAnon(Values); 624 } 625 626 llvm::Constant * 627 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 628 CharUnits offset) { 629 // Itanium C++ ABI 2.3: 630 // A pointer to data member is an offset from the base address of 631 // the class object containing it, represented as a ptrdiff_t 632 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 633 } 634 635 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 636 return BuildMemberPointer(MD, CharUnits::Zero()); 637 } 638 639 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 640 CharUnits ThisAdjustment) { 641 assert(MD->isInstance() && "Member function must not be static!"); 642 MD = MD->getCanonicalDecl(); 643 644 CodeGenTypes &Types = CGM.getTypes(); 645 646 // Get the function pointer (or index if this is a virtual function). 647 llvm::Constant *MemPtr[2]; 648 if (MD->isVirtual()) { 649 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); 650 651 const ASTContext &Context = getContext(); 652 CharUnits PointerWidth = 653 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 654 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 655 656 if (UseARMMethodPtrABI) { 657 // ARM C++ ABI 3.2.1: 658 // This ABI specifies that adj contains twice the this 659 // adjustment, plus 1 if the member function is virtual. The 660 // least significant bit of adj then makes exactly the same 661 // discrimination as the least significant bit of ptr does for 662 // Itanium. 663 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 664 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 665 2 * ThisAdjustment.getQuantity() + 1); 666 } else { 667 // Itanium C++ ABI 2.3: 668 // For a virtual function, [the pointer field] is 1 plus the 669 // virtual table offset (in bytes) of the function, 670 // represented as a ptrdiff_t. 671 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 672 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 673 ThisAdjustment.getQuantity()); 674 } 675 } else { 676 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 677 llvm::Type *Ty; 678 // Check whether the function has a computable LLVM signature. 679 if (Types.isFuncTypeConvertible(FPT)) { 680 // The function has a computable LLVM signature; use the correct type. 681 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 682 } else { 683 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 684 // function type is incomplete. 685 Ty = CGM.PtrDiffTy; 686 } 687 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 688 689 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 690 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 691 (UseARMMethodPtrABI ? 2 : 1) * 692 ThisAdjustment.getQuantity()); 693 } 694 695 return llvm::ConstantStruct::getAnon(MemPtr); 696 } 697 698 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 699 QualType MPType) { 700 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 701 const ValueDecl *MPD = MP.getMemberPointerDecl(); 702 if (!MPD) 703 return EmitNullMemberPointer(MPT); 704 705 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 706 707 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 708 return BuildMemberPointer(MD, ThisAdjustment); 709 710 CharUnits FieldOffset = 711 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 712 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 713 } 714 715 /// The comparison algorithm is pretty easy: the member pointers are 716 /// the same if they're either bitwise identical *or* both null. 717 /// 718 /// ARM is different here only because null-ness is more complicated. 719 llvm::Value * 720 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 721 llvm::Value *L, 722 llvm::Value *R, 723 const MemberPointerType *MPT, 724 bool Inequality) { 725 CGBuilderTy &Builder = CGF.Builder; 726 727 llvm::ICmpInst::Predicate Eq; 728 llvm::Instruction::BinaryOps And, Or; 729 if (Inequality) { 730 Eq = llvm::ICmpInst::ICMP_NE; 731 And = llvm::Instruction::Or; 732 Or = llvm::Instruction::And; 733 } else { 734 Eq = llvm::ICmpInst::ICMP_EQ; 735 And = llvm::Instruction::And; 736 Or = llvm::Instruction::Or; 737 } 738 739 // Member data pointers are easy because there's a unique null 740 // value, so it just comes down to bitwise equality. 741 if (MPT->isMemberDataPointer()) 742 return Builder.CreateICmp(Eq, L, R); 743 744 // For member function pointers, the tautologies are more complex. 745 // The Itanium tautology is: 746 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 747 // The ARM tautology is: 748 // (L == R) <==> (L.ptr == R.ptr && 749 // (L.adj == R.adj || 750 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 751 // The inequality tautologies have exactly the same structure, except 752 // applying De Morgan's laws. 753 754 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 755 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 756 757 // This condition tests whether L.ptr == R.ptr. This must always be 758 // true for equality to hold. 759 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 760 761 // This condition, together with the assumption that L.ptr == R.ptr, 762 // tests whether the pointers are both null. ARM imposes an extra 763 // condition. 764 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 765 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 766 767 // This condition tests whether L.adj == R.adj. If this isn't 768 // true, the pointers are unequal unless they're both null. 769 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 770 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 771 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 772 773 // Null member function pointers on ARM clear the low bit of Adj, 774 // so the zero condition has to check that neither low bit is set. 775 if (UseARMMethodPtrABI) { 776 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 777 778 // Compute (l.adj | r.adj) & 1 and test it against zero. 779 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 780 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 781 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 782 "cmp.or.adj"); 783 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 784 } 785 786 // Tie together all our conditions. 787 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 788 Result = Builder.CreateBinOp(And, PtrEq, Result, 789 Inequality ? "memptr.ne" : "memptr.eq"); 790 return Result; 791 } 792 793 llvm::Value * 794 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 795 llvm::Value *MemPtr, 796 const MemberPointerType *MPT) { 797 CGBuilderTy &Builder = CGF.Builder; 798 799 /// For member data pointers, this is just a check against -1. 800 if (MPT->isMemberDataPointer()) { 801 assert(MemPtr->getType() == CGM.PtrDiffTy); 802 llvm::Value *NegativeOne = 803 llvm::Constant::getAllOnesValue(MemPtr->getType()); 804 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 805 } 806 807 // In Itanium, a member function pointer is not null if 'ptr' is not null. 808 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 809 810 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 811 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 812 813 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 814 // (the virtual bit) is set. 815 if (UseARMMethodPtrABI) { 816 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 817 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 818 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 819 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 820 "memptr.isvirtual"); 821 Result = Builder.CreateOr(Result, IsVirtual); 822 } 823 824 return Result; 825 } 826 827 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const { 828 const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl(); 829 if (!RD) 830 return false; 831 832 // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor. 833 // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared 834 // special members. 835 if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) { 836 FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false); 837 return true; 838 } 839 return false; 840 } 841 842 /// The Itanium ABI requires non-zero initialization only for data 843 /// member pointers, for which '0' is a valid offset. 844 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 845 return MPT->getPointeeType()->isFunctionType(); 846 } 847 848 /// The Itanium ABI always places an offset to the complete object 849 /// at entry -2 in the vtable. 850 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 851 llvm::Value *ptr, 852 QualType type) { 853 // Grab the vtable pointer as an intptr_t*. 854 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo()); 855 856 // Track back to entry -2 and pull out the offset there. 857 llvm::Value *offsetPtr = 858 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr"); 859 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr); 860 offset->setAlignment(CGF.PointerAlignInBytes); 861 862 // Apply the offset. 863 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 864 return CGF.Builder.CreateInBoundsGEP(ptr, offset); 865 } 866 867 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) { 868 // void *__dynamic_cast(const void *sub, 869 // const abi::__class_type_info *src, 870 // const abi::__class_type_info *dst, 871 // std::ptrdiff_t src2dst_offset); 872 873 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 874 llvm::Type *PtrDiffTy = 875 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 876 877 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; 878 879 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false); 880 881 // Mark the function as nounwind readonly. 882 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind, 883 llvm::Attribute::ReadOnly }; 884 llvm::AttributeSet Attrs = llvm::AttributeSet::get( 885 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs); 886 887 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs); 888 } 889 890 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { 891 // void __cxa_bad_cast(); 892 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 893 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); 894 } 895 896 /// \brief Compute the src2dst_offset hint as described in the 897 /// Itanium C++ ABI [2.9.7] 898 static CharUnits computeOffsetHint(ASTContext &Context, 899 const CXXRecordDecl *Src, 900 const CXXRecordDecl *Dst) { 901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 902 /*DetectVirtual=*/false); 903 904 // If Dst is not derived from Src we can skip the whole computation below and 905 // return that Src is not a public base of Dst. Record all inheritance paths. 906 if (!Dst->isDerivedFrom(Src, Paths)) 907 return CharUnits::fromQuantity(-2ULL); 908 909 unsigned NumPublicPaths = 0; 910 CharUnits Offset; 911 912 // Now walk all possible inheritance paths. 913 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E; 914 ++I) { 915 if (I->Access != AS_public) // Ignore non-public inheritance. 916 continue; 917 918 ++NumPublicPaths; 919 920 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) { 921 // If the path contains a virtual base class we can't give any hint. 922 // -1: no hint. 923 if (J->Base->isVirtual()) 924 return CharUnits::fromQuantity(-1ULL); 925 926 if (NumPublicPaths > 1) // Won't use offsets, skip computation. 927 continue; 928 929 // Accumulate the base class offsets. 930 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class); 931 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl()); 932 } 933 } 934 935 // -2: Src is not a public base of Dst. 936 if (NumPublicPaths == 0) 937 return CharUnits::fromQuantity(-2ULL); 938 939 // -3: Src is a multiple public base type but never a virtual base type. 940 if (NumPublicPaths > 1) 941 return CharUnits::fromQuantity(-3ULL); 942 943 // Otherwise, the Src type is a unique public nonvirtual base type of Dst. 944 // Return the offset of Src from the origin of Dst. 945 return Offset; 946 } 947 948 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { 949 // void __cxa_bad_typeid(); 950 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 951 952 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); 953 } 954 955 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref, 956 QualType SrcRecordTy) { 957 return IsDeref; 958 } 959 960 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) { 961 llvm::Value *Fn = getBadTypeidFn(CGF); 962 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 963 CGF.Builder.CreateUnreachable(); 964 } 965 966 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF, 967 QualType SrcRecordTy, 968 llvm::Value *ThisPtr, 969 llvm::Type *StdTypeInfoPtrTy) { 970 llvm::Value *Value = 971 CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo()); 972 973 // Load the type info. 974 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); 975 return CGF.Builder.CreateLoad(Value); 976 } 977 978 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, 979 QualType SrcRecordTy) { 980 return SrcIsPtr; 981 } 982 983 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall( 984 CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy, 985 QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) { 986 llvm::Type *PtrDiffLTy = 987 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 988 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 989 990 llvm::Value *SrcRTTI = 991 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 992 llvm::Value *DestRTTI = 993 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 994 995 // Compute the offset hint. 996 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl(); 997 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl(); 998 llvm::Value *OffsetHint = llvm::ConstantInt::get( 999 PtrDiffLTy, 1000 computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity()); 1001 1002 // Emit the call to __dynamic_cast. 1003 Value = CGF.EmitCastToVoidPtr(Value); 1004 1005 llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint}; 1006 Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args); 1007 Value = CGF.Builder.CreateBitCast(Value, DestLTy); 1008 1009 /// C++ [expr.dynamic.cast]p9: 1010 /// A failed cast to reference type throws std::bad_cast 1011 if (DestTy->isReferenceType()) { 1012 llvm::BasicBlock *BadCastBlock = 1013 CGF.createBasicBlock("dynamic_cast.bad_cast"); 1014 1015 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); 1016 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); 1017 1018 CGF.EmitBlock(BadCastBlock); 1019 EmitBadCastCall(CGF); 1020 } 1021 1022 return Value; 1023 } 1024 1025 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, 1026 llvm::Value *Value, 1027 QualType SrcRecordTy, 1028 QualType DestTy) { 1029 llvm::Type *PtrDiffLTy = 1030 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1031 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1032 1033 // Get the vtable pointer. 1034 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo()); 1035 1036 // Get the offset-to-top from the vtable. 1037 llvm::Value *OffsetToTop = 1038 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); 1039 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top"); 1040 1041 // Finally, add the offset to the pointer. 1042 Value = CGF.EmitCastToVoidPtr(Value); 1043 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); 1044 1045 return CGF.Builder.CreateBitCast(Value, DestLTy); 1046 } 1047 1048 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) { 1049 llvm::Value *Fn = getBadCastFn(CGF); 1050 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn(); 1051 CGF.Builder.CreateUnreachable(); 1052 return true; 1053 } 1054 1055 llvm::Value * 1056 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 1057 llvm::Value *This, 1058 const CXXRecordDecl *ClassDecl, 1059 const CXXRecordDecl *BaseClassDecl) { 1060 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy); 1061 CharUnits VBaseOffsetOffset = 1062 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, 1063 BaseClassDecl); 1064 1065 llvm::Value *VBaseOffsetPtr = 1066 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1067 "vbase.offset.ptr"); 1068 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 1069 CGM.PtrDiffTy->getPointerTo()); 1070 1071 llvm::Value *VBaseOffset = 1072 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1073 1074 return VBaseOffset; 1075 } 1076 1077 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 1078 // Just make sure we're in sync with TargetCXXABI. 1079 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 1080 1081 // The constructor used for constructing this as a base class; 1082 // ignores virtual bases. 1083 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 1084 1085 // The constructor used for constructing this as a complete class; 1086 // constucts the virtual bases, then calls the base constructor. 1087 if (!D->getParent()->isAbstract()) { 1088 // We don't need to emit the complete ctor if the class is abstract. 1089 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 1090 } 1091 } 1092 1093 void 1094 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T, 1095 SmallVectorImpl<CanQualType> &ArgTys) { 1096 ASTContext &Context = getContext(); 1097 1098 // All parameters are already in place except VTT, which goes after 'this'. 1099 // These are Clang types, so we don't need to worry about sret yet. 1100 1101 // Check if we need to add a VTT parameter (which has type void **). 1102 if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0) 1103 ArgTys.insert(ArgTys.begin() + 1, 1104 Context.getPointerType(Context.VoidPtrTy)); 1105 } 1106 1107 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 1108 // The destructor used for destructing this as a base class; ignores 1109 // virtual bases. 1110 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 1111 1112 // The destructor used for destructing this as a most-derived class; 1113 // call the base destructor and then destructs any virtual bases. 1114 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 1115 1116 // The destructor in a virtual table is always a 'deleting' 1117 // destructor, which calls the complete destructor and then uses the 1118 // appropriate operator delete. 1119 if (D->isVirtual()) 1120 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 1121 } 1122 1123 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 1124 QualType &ResTy, 1125 FunctionArgList &Params) { 1126 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 1127 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 1128 1129 // Check if we need a VTT parameter as well. 1130 if (NeedsVTTParameter(CGF.CurGD)) { 1131 ASTContext &Context = getContext(); 1132 1133 // FIXME: avoid the fake decl 1134 QualType T = Context.getPointerType(Context.VoidPtrTy); 1135 ImplicitParamDecl *VTTDecl 1136 = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(), 1137 &Context.Idents.get("vtt"), T); 1138 Params.insert(Params.begin() + 1, VTTDecl); 1139 getStructorImplicitParamDecl(CGF) = VTTDecl; 1140 } 1141 } 1142 1143 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 1144 /// Initialize the 'this' slot. 1145 EmitThisParam(CGF); 1146 1147 /// Initialize the 'vtt' slot if needed. 1148 if (getStructorImplicitParamDecl(CGF)) { 1149 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( 1150 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); 1151 } 1152 1153 /// If this is a function that the ABI specifies returns 'this', initialize 1154 /// the return slot to 'this' at the start of the function. 1155 /// 1156 /// Unlike the setting of return types, this is done within the ABI 1157 /// implementation instead of by clients of CGCXXABI because: 1158 /// 1) getThisValue is currently protected 1159 /// 2) in theory, an ABI could implement 'this' returns some other way; 1160 /// HasThisReturn only specifies a contract, not the implementation 1161 if (HasThisReturn(CGF.CurGD)) 1162 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 1163 } 1164 1165 unsigned ItaniumCXXABI::addImplicitConstructorArgs( 1166 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 1167 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 1168 if (!NeedsVTTParameter(GlobalDecl(D, Type))) 1169 return 0; 1170 1171 // Insert the implicit 'vtt' argument as the second argument. 1172 llvm::Value *VTT = 1173 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); 1174 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1175 Args.insert(Args.begin() + 1, 1176 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false)); 1177 return 1; // Added one arg. 1178 } 1179 1180 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 1181 const CXXDestructorDecl *DD, 1182 CXXDtorType Type, bool ForVirtualBase, 1183 bool Delegating, llvm::Value *This) { 1184 GlobalDecl GD(DD, Type); 1185 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); 1186 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 1187 1188 llvm::Value *Callee = nullptr; 1189 if (getContext().getLangOpts().AppleKext) 1190 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); 1191 1192 if (!Callee) 1193 Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type)); 1194 1195 CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT, 1196 VTTTy, nullptr); 1197 } 1198 1199 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 1200 const CXXRecordDecl *RD) { 1201 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); 1202 if (VTable->hasInitializer()) 1203 return; 1204 1205 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1206 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 1207 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 1208 llvm::Constant *RTTI = 1209 CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD)); 1210 1211 // Create and set the initializer. 1212 llvm::Constant *Init = CGVT.CreateVTableInitializer( 1213 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(), 1214 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI); 1215 VTable->setInitializer(Init); 1216 1217 // Set the correct linkage. 1218 VTable->setLinkage(Linkage); 1219 1220 // Set the right visibility. 1221 CGM.setGlobalVisibility(VTable, RD); 1222 1223 // Use pointer alignment for the vtable. Otherwise we would align them based 1224 // on the size of the initializer which doesn't make sense as only single 1225 // values are read. 1226 unsigned PAlign = CGM.getTarget().getPointerAlign(0); 1227 VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity()); 1228 1229 // If this is the magic class __cxxabiv1::__fundamental_type_info, 1230 // we will emit the typeinfo for the fundamental types. This is the 1231 // same behaviour as GCC. 1232 const DeclContext *DC = RD->getDeclContext(); 1233 if (RD->getIdentifier() && 1234 RD->getIdentifier()->isStr("__fundamental_type_info") && 1235 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() && 1236 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 1237 DC->getParent()->isTranslationUnit()) 1238 EmitFundamentalRTTIDescriptors(); 1239 } 1240 1241 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( 1242 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 1243 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 1244 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD); 1245 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase); 1246 1247 llvm::Value *VTableAddressPoint; 1248 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) { 1249 // Get the secondary vpointer index. 1250 uint64_t VirtualPointerIndex = 1251 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1252 1253 /// Load the VTT. 1254 llvm::Value *VTT = CGF.LoadCXXVTT(); 1255 if (VirtualPointerIndex) 1256 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1257 1258 // And load the address point from the VTT. 1259 VTableAddressPoint = CGF.Builder.CreateLoad(VTT); 1260 } else { 1261 llvm::Constant *VTable = 1262 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits()); 1263 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1264 .getVTableLayout(VTableClass) 1265 .getAddressPoint(Base); 1266 VTableAddressPoint = 1267 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1268 } 1269 1270 return VTableAddressPoint; 1271 } 1272 1273 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( 1274 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1275 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits()); 1276 1277 // Find the appropriate vtable within the vtable group. 1278 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1279 .getVTableLayout(VTableClass) 1280 .getAddressPoint(Base); 1281 llvm::Value *Indices[] = { 1282 llvm::ConstantInt::get(CGM.Int64Ty, 0), 1283 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint) 1284 }; 1285 1286 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices); 1287 } 1288 1289 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1290 CharUnits VPtrOffset) { 1291 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); 1292 1293 llvm::GlobalVariable *&VTable = VTables[RD]; 1294 if (VTable) 1295 return VTable; 1296 1297 // Queue up this v-table for possible deferred emission. 1298 CGM.addDeferredVTable(RD); 1299 1300 SmallString<256> OutName; 1301 llvm::raw_svector_ostream Out(OutName); 1302 getMangleContext().mangleCXXVTable(RD, Out); 1303 Out.flush(); 1304 StringRef Name = OutName.str(); 1305 1306 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1307 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 1308 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents()); 1309 1310 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1311 Name, ArrayType, llvm::GlobalValue::ExternalLinkage); 1312 VTable->setUnnamedAddr(true); 1313 1314 if (RD->hasAttr<DLLImportAttr>()) 1315 VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 1316 else if (RD->hasAttr<DLLExportAttr>()) 1317 VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 1318 1319 return VTable; 1320 } 1321 1322 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1323 GlobalDecl GD, 1324 llvm::Value *This, 1325 llvm::Type *Ty) { 1326 GD = GD.getCanonicalDecl(); 1327 Ty = Ty->getPointerTo()->getPointerTo(); 1328 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty); 1329 1330 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 1331 llvm::Value *VFuncPtr = 1332 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 1333 return CGF.Builder.CreateLoad(VFuncPtr); 1334 } 1335 1336 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 1337 const CXXDestructorDecl *Dtor, 1338 CXXDtorType DtorType, 1339 llvm::Value *This, 1340 const CXXMemberCallExpr *CE) { 1341 assert(CE == nullptr || CE->arg_begin() == CE->arg_end()); 1342 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1343 1344 const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 1345 Dtor, getFromDtorType(DtorType)); 1346 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1347 llvm::Value *Callee = 1348 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty); 1349 1350 CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This, 1351 /*ImplicitParam=*/nullptr, QualType(), CE); 1352 } 1353 1354 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1355 CodeGenVTables &VTables = CGM.getVTables(); 1356 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 1357 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); 1358 } 1359 1360 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, 1361 llvm::Value *Ptr, 1362 int64_t NonVirtualAdjustment, 1363 int64_t VirtualAdjustment, 1364 bool IsReturnAdjustment) { 1365 if (!NonVirtualAdjustment && !VirtualAdjustment) 1366 return Ptr; 1367 1368 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 1369 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy); 1370 1371 if (NonVirtualAdjustment && !IsReturnAdjustment) { 1372 // Perform the non-virtual adjustment for a base-to-derived cast. 1373 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1374 } 1375 1376 if (VirtualAdjustment) { 1377 llvm::Type *PtrDiffTy = 1378 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1379 1380 // Perform the virtual adjustment. 1381 llvm::Value *VTablePtrPtr = 1382 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo()); 1383 1384 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 1385 1386 llvm::Value *OffsetPtr = 1387 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 1388 1389 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 1390 1391 // Load the adjustment offset from the vtable. 1392 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr); 1393 1394 // Adjust our pointer. 1395 V = CGF.Builder.CreateInBoundsGEP(V, Offset); 1396 } 1397 1398 if (NonVirtualAdjustment && IsReturnAdjustment) { 1399 // Perform the non-virtual adjustment for a derived-to-base cast. 1400 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1401 } 1402 1403 // Cast back to the original type. 1404 return CGF.Builder.CreateBitCast(V, Ptr->getType()); 1405 } 1406 1407 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1408 llvm::Value *This, 1409 const ThisAdjustment &TA) { 1410 return performTypeAdjustment(CGF, This, TA.NonVirtual, 1411 TA.Virtual.Itanium.VCallOffsetOffset, 1412 /*IsReturnAdjustment=*/false); 1413 } 1414 1415 llvm::Value * 1416 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1417 const ReturnAdjustment &RA) { 1418 return performTypeAdjustment(CGF, Ret, RA.NonVirtual, 1419 RA.Virtual.Itanium.VBaseOffsetOffset, 1420 /*IsReturnAdjustment=*/true); 1421 } 1422 1423 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 1424 RValue RV, QualType ResultType) { 1425 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 1426 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 1427 1428 // Destructor thunks in the ARM ABI have indeterminate results. 1429 llvm::Type *T = 1430 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 1431 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 1432 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 1433 } 1434 1435 /************************** Array allocation cookies **************************/ 1436 1437 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1438 // The array cookie is a size_t; pad that up to the element alignment. 1439 // The cookie is actually right-justified in that space. 1440 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 1441 CGM.getContext().getTypeAlignInChars(elementType)); 1442 } 1443 1444 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1445 llvm::Value *NewPtr, 1446 llvm::Value *NumElements, 1447 const CXXNewExpr *expr, 1448 QualType ElementType) { 1449 assert(requiresArrayCookie(expr)); 1450 1451 unsigned AS = NewPtr->getType()->getPointerAddressSpace(); 1452 1453 ASTContext &Ctx = getContext(); 1454 QualType SizeTy = Ctx.getSizeType(); 1455 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 1456 1457 // The size of the cookie. 1458 CharUnits CookieSize = 1459 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 1460 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 1461 1462 // Compute an offset to the cookie. 1463 llvm::Value *CookiePtr = NewPtr; 1464 CharUnits CookieOffset = CookieSize - SizeSize; 1465 if (!CookieOffset.isZero()) 1466 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 1467 CookieOffset.getQuantity()); 1468 1469 // Write the number of elements into the appropriate slot. 1470 llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS); 1471 llvm::Value *NumElementsPtr = 1472 CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy); 1473 llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr); 1474 if (CGM.getLangOpts().Sanitize.Address && AS == 0 && 1475 expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) { 1476 // The store to the CookiePtr does not need to be instrumented. 1477 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI); 1478 llvm::FunctionType *FTy = 1479 llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false); 1480 llvm::Constant *F = 1481 CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie"); 1482 CGF.Builder.CreateCall(F, NumElementsPtr); 1483 } 1484 1485 // Finally, compute a pointer to the actual data buffer by skipping 1486 // over the cookie completely. 1487 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 1488 CookieSize.getQuantity()); 1489 } 1490 1491 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1492 llvm::Value *allocPtr, 1493 CharUnits cookieSize) { 1494 // The element size is right-justified in the cookie. 1495 llvm::Value *numElementsPtr = allocPtr; 1496 CharUnits numElementsOffset = 1497 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes); 1498 if (!numElementsOffset.isZero()) 1499 numElementsPtr = 1500 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr, 1501 numElementsOffset.getQuantity()); 1502 1503 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1504 numElementsPtr = 1505 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1506 if (!CGM.getLangOpts().Sanitize.Address || AS != 0) 1507 return CGF.Builder.CreateLoad(numElementsPtr); 1508 // In asan mode emit a function call instead of a regular load and let the 1509 // run-time deal with it: if the shadow is properly poisoned return the 1510 // cookie, otherwise return 0 to avoid an infinite loop calling DTORs. 1511 // We can't simply ignore this load using nosanitize metadata because 1512 // the metadata may be lost. 1513 llvm::FunctionType *FTy = 1514 llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false); 1515 llvm::Constant *F = 1516 CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie"); 1517 return CGF.Builder.CreateCall(F, numElementsPtr); 1518 } 1519 1520 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1521 // ARM says that the cookie is always: 1522 // struct array_cookie { 1523 // std::size_t element_size; // element_size != 0 1524 // std::size_t element_count; 1525 // }; 1526 // But the base ABI doesn't give anything an alignment greater than 1527 // 8, so we can dismiss this as typical ABI-author blindness to 1528 // actual language complexity and round up to the element alignment. 1529 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 1530 CGM.getContext().getTypeAlignInChars(elementType)); 1531 } 1532 1533 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1534 llvm::Value *newPtr, 1535 llvm::Value *numElements, 1536 const CXXNewExpr *expr, 1537 QualType elementType) { 1538 assert(requiresArrayCookie(expr)); 1539 1540 // NewPtr is a char*, but we generalize to arbitrary addrspaces. 1541 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1542 1543 // The cookie is always at the start of the buffer. 1544 llvm::Value *cookie = newPtr; 1545 1546 // The first element is the element size. 1547 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS)); 1548 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1549 getContext().getTypeSizeInChars(elementType).getQuantity()); 1550 CGF.Builder.CreateStore(elementSize, cookie); 1551 1552 // The second element is the element count. 1553 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1); 1554 CGF.Builder.CreateStore(numElements, cookie); 1555 1556 // Finally, compute a pointer to the actual data buffer by skipping 1557 // over the cookie completely. 1558 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1559 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1560 cookieSize.getQuantity()); 1561 } 1562 1563 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1564 llvm::Value *allocPtr, 1565 CharUnits cookieSize) { 1566 // The number of elements is at offset sizeof(size_t) relative to 1567 // the allocated pointer. 1568 llvm::Value *numElementsPtr 1569 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes); 1570 1571 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1572 numElementsPtr = 1573 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1574 return CGF.Builder.CreateLoad(numElementsPtr); 1575 } 1576 1577 /*********************** Static local initialization **************************/ 1578 1579 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1580 llvm::PointerType *GuardPtrTy) { 1581 // int __cxa_guard_acquire(__guard *guard_object); 1582 llvm::FunctionType *FTy = 1583 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1584 GuardPtrTy, /*isVarArg=*/false); 1585 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire", 1586 llvm::AttributeSet::get(CGM.getLLVMContext(), 1587 llvm::AttributeSet::FunctionIndex, 1588 llvm::Attribute::NoUnwind)); 1589 } 1590 1591 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1592 llvm::PointerType *GuardPtrTy) { 1593 // void __cxa_guard_release(__guard *guard_object); 1594 llvm::FunctionType *FTy = 1595 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1596 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release", 1597 llvm::AttributeSet::get(CGM.getLLVMContext(), 1598 llvm::AttributeSet::FunctionIndex, 1599 llvm::Attribute::NoUnwind)); 1600 } 1601 1602 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1603 llvm::PointerType *GuardPtrTy) { 1604 // void __cxa_guard_abort(__guard *guard_object); 1605 llvm::FunctionType *FTy = 1606 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1607 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort", 1608 llvm::AttributeSet::get(CGM.getLLVMContext(), 1609 llvm::AttributeSet::FunctionIndex, 1610 llvm::Attribute::NoUnwind)); 1611 } 1612 1613 namespace { 1614 struct CallGuardAbort : EHScopeStack::Cleanup { 1615 llvm::GlobalVariable *Guard; 1616 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1617 1618 void Emit(CodeGenFunction &CGF, Flags flags) override { 1619 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1620 Guard); 1621 } 1622 }; 1623 } 1624 1625 /// The ARM code here follows the Itanium code closely enough that we 1626 /// just special-case it at particular places. 1627 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1628 const VarDecl &D, 1629 llvm::GlobalVariable *var, 1630 bool shouldPerformInit) { 1631 CGBuilderTy &Builder = CGF.Builder; 1632 1633 // We only need to use thread-safe statics for local non-TLS variables; 1634 // global initialization is always single-threaded. 1635 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 1636 D.isLocalVarDecl() && !D.getTLSKind(); 1637 1638 // If we have a global variable with internal linkage and thread-safe statics 1639 // are disabled, we can just let the guard variable be of type i8. 1640 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 1641 1642 llvm::IntegerType *guardTy; 1643 if (useInt8GuardVariable) { 1644 guardTy = CGF.Int8Ty; 1645 } else { 1646 // Guard variables are 64 bits in the generic ABI and size width on ARM 1647 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 1648 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty); 1649 } 1650 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 1651 1652 // Create the guard variable if we don't already have it (as we 1653 // might if we're double-emitting this function body). 1654 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 1655 if (!guard) { 1656 // Mangle the name for the guard. 1657 SmallString<256> guardName; 1658 { 1659 llvm::raw_svector_ostream out(guardName); 1660 getMangleContext().mangleStaticGuardVariable(&D, out); 1661 out.flush(); 1662 } 1663 1664 // Create the guard variable with a zero-initializer. 1665 // Just absorb linkage and visibility from the guarded variable. 1666 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 1667 false, var->getLinkage(), 1668 llvm::ConstantInt::get(guardTy, 0), 1669 guardName.str()); 1670 guard->setVisibility(var->getVisibility()); 1671 // If the variable is thread-local, so is its guard variable. 1672 guard->setThreadLocalMode(var->getThreadLocalMode()); 1673 1674 // The ABI says: It is suggested that it be emitted in the same COMDAT group 1675 // as the associated data object 1676 if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) { 1677 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName()); 1678 guard->setComdat(C); 1679 var->setComdat(C); 1680 CGF.CurFn->setComdat(C); 1681 } 1682 1683 CGM.setStaticLocalDeclGuardAddress(&D, guard); 1684 } 1685 1686 // Test whether the variable has completed initialization. 1687 // 1688 // Itanium C++ ABI 3.3.2: 1689 // The following is pseudo-code showing how these functions can be used: 1690 // if (obj_guard.first_byte == 0) { 1691 // if ( __cxa_guard_acquire (&obj_guard) ) { 1692 // try { 1693 // ... initialize the object ...; 1694 // } catch (...) { 1695 // __cxa_guard_abort (&obj_guard); 1696 // throw; 1697 // } 1698 // ... queue object destructor with __cxa_atexit() ...; 1699 // __cxa_guard_release (&obj_guard); 1700 // } 1701 // } 1702 1703 // Load the first byte of the guard variable. 1704 llvm::LoadInst *LI = 1705 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy)); 1706 LI->setAlignment(1); 1707 1708 // Itanium ABI: 1709 // An implementation supporting thread-safety on multiprocessor 1710 // systems must also guarantee that references to the initialized 1711 // object do not occur before the load of the initialization flag. 1712 // 1713 // In LLVM, we do this by marking the load Acquire. 1714 if (threadsafe) 1715 LI->setAtomic(llvm::Acquire); 1716 1717 // For ARM, we should only check the first bit, rather than the entire byte: 1718 // 1719 // ARM C++ ABI 3.2.3.1: 1720 // To support the potential use of initialization guard variables 1721 // as semaphores that are the target of ARM SWP and LDREX/STREX 1722 // synchronizing instructions we define a static initialization 1723 // guard variable to be a 4-byte aligned, 4-byte word with the 1724 // following inline access protocol. 1725 // #define INITIALIZED 1 1726 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1727 // if (__cxa_guard_acquire(&obj_guard)) 1728 // ... 1729 // } 1730 // 1731 // and similarly for ARM64: 1732 // 1733 // ARM64 C++ ABI 3.2.2: 1734 // This ABI instead only specifies the value bit 0 of the static guard 1735 // variable; all other bits are platform defined. Bit 0 shall be 0 when the 1736 // variable is not initialized and 1 when it is. 1737 llvm::Value *V = 1738 (UseARMGuardVarABI && !useInt8GuardVariable) 1739 ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1)) 1740 : LI; 1741 llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1742 1743 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1744 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1745 1746 // Check if the first byte of the guard variable is zero. 1747 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock); 1748 1749 CGF.EmitBlock(InitCheckBlock); 1750 1751 // Variables used when coping with thread-safe statics and exceptions. 1752 if (threadsafe) { 1753 // Call __cxa_guard_acquire. 1754 llvm::Value *V 1755 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 1756 1757 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1758 1759 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1760 InitBlock, EndBlock); 1761 1762 // Call __cxa_guard_abort along the exceptional edge. 1763 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 1764 1765 CGF.EmitBlock(InitBlock); 1766 } 1767 1768 // Emit the initializer and add a global destructor if appropriate. 1769 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 1770 1771 if (threadsafe) { 1772 // Pop the guard-abort cleanup if we pushed one. 1773 CGF.PopCleanupBlock(); 1774 1775 // Call __cxa_guard_release. This cannot throw. 1776 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard); 1777 } else { 1778 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard); 1779 } 1780 1781 CGF.EmitBlock(EndBlock); 1782 } 1783 1784 /// Register a global destructor using __cxa_atexit. 1785 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 1786 llvm::Constant *dtor, 1787 llvm::Constant *addr, 1788 bool TLS) { 1789 const char *Name = "__cxa_atexit"; 1790 if (TLS) { 1791 const llvm::Triple &T = CGF.getTarget().getTriple(); 1792 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit"; 1793 } 1794 1795 // We're assuming that the destructor function is something we can 1796 // reasonably call with the default CC. Go ahead and cast it to the 1797 // right prototype. 1798 llvm::Type *dtorTy = 1799 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 1800 1801 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 1802 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 1803 llvm::FunctionType *atexitTy = 1804 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 1805 1806 // Fetch the actual function. 1807 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 1808 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 1809 fn->setDoesNotThrow(); 1810 1811 // Create a variable that binds the atexit to this shared object. 1812 llvm::Constant *handle = 1813 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 1814 1815 llvm::Value *args[] = { 1816 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 1817 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 1818 handle 1819 }; 1820 CGF.EmitNounwindRuntimeCall(atexit, args); 1821 } 1822 1823 /// Register a global destructor as best as we know how. 1824 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 1825 const VarDecl &D, 1826 llvm::Constant *dtor, 1827 llvm::Constant *addr) { 1828 // Use __cxa_atexit if available. 1829 if (CGM.getCodeGenOpts().CXAAtExit) 1830 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 1831 1832 if (D.getTLSKind()) 1833 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 1834 1835 // In Apple kexts, we want to add a global destructor entry. 1836 // FIXME: shouldn't this be guarded by some variable? 1837 if (CGM.getLangOpts().AppleKext) { 1838 // Generate a global destructor entry. 1839 return CGM.AddCXXDtorEntry(dtor, addr); 1840 } 1841 1842 CGF.registerGlobalDtorWithAtExit(D, dtor, addr); 1843 } 1844 1845 static bool isThreadWrapperReplaceable(const VarDecl *VD, 1846 CodeGen::CodeGenModule &CGM) { 1847 assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!"); 1848 // OS X prefers to have references to thread local variables to go through 1849 // the thread wrapper instead of directly referencing the backing variable. 1850 return VD->getTLSKind() == VarDecl::TLS_Dynamic && 1851 CGM.getTarget().getTriple().isMacOSX(); 1852 } 1853 1854 /// Get the appropriate linkage for the wrapper function. This is essentially 1855 /// the weak form of the variable's linkage; every translation unit which needs 1856 /// the wrapper emits a copy, and we want the linker to merge them. 1857 static llvm::GlobalValue::LinkageTypes 1858 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) { 1859 llvm::GlobalValue::LinkageTypes VarLinkage = 1860 CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false); 1861 1862 // For internal linkage variables, we don't need an external or weak wrapper. 1863 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 1864 return VarLinkage; 1865 1866 // If the thread wrapper is replaceable, give it appropriate linkage. 1867 if (isThreadWrapperReplaceable(VD, CGM)) { 1868 if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) || 1869 llvm::GlobalVariable::isWeakODRLinkage(VarLinkage)) 1870 return llvm::GlobalVariable::WeakAnyLinkage; 1871 return VarLinkage; 1872 } 1873 return llvm::GlobalValue::WeakODRLinkage; 1874 } 1875 1876 llvm::Function * 1877 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 1878 llvm::Value *Val) { 1879 // Mangle the name for the thread_local wrapper function. 1880 SmallString<256> WrapperName; 1881 { 1882 llvm::raw_svector_ostream Out(WrapperName); 1883 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 1884 Out.flush(); 1885 } 1886 1887 if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName)) 1888 return cast<llvm::Function>(V); 1889 1890 llvm::Type *RetTy = Val->getType(); 1891 if (VD->getType()->isReferenceType()) 1892 RetTy = RetTy->getPointerElementType(); 1893 1894 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false); 1895 llvm::Function *Wrapper = 1896 llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM), 1897 WrapperName.str(), &CGM.getModule()); 1898 // Always resolve references to the wrapper at link time. 1899 if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM)) 1900 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 1901 return Wrapper; 1902 } 1903 1904 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 1905 CodeGenModule &CGM, 1906 ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>> 1907 CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits, 1908 ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) { 1909 llvm::Function *InitFunc = nullptr; 1910 if (!CXXThreadLocalInits.empty()) { 1911 // Generate a guarded initialization function. 1912 llvm::FunctionType *FTy = 1913 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 1914 InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init", 1915 SourceLocation(), 1916 /*TLS=*/true); 1917 llvm::GlobalVariable *Guard = new llvm::GlobalVariable( 1918 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false, 1919 llvm::GlobalVariable::InternalLinkage, 1920 llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard"); 1921 Guard->setThreadLocal(true); 1922 CodeGenFunction(CGM) 1923 .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard); 1924 } 1925 for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) { 1926 const VarDecl *VD = CXXThreadLocals[I].first; 1927 llvm::GlobalVariable *Var = CXXThreadLocals[I].second; 1928 1929 // Some targets require that all access to thread local variables go through 1930 // the thread wrapper. This means that we cannot attempt to create a thread 1931 // wrapper or a thread helper. 1932 if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition()) 1933 continue; 1934 1935 // Mangle the name for the thread_local initialization function. 1936 SmallString<256> InitFnName; 1937 { 1938 llvm::raw_svector_ostream Out(InitFnName); 1939 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 1940 Out.flush(); 1941 } 1942 1943 // If we have a definition for the variable, emit the initialization 1944 // function as an alias to the global Init function (if any). Otherwise, 1945 // produce a declaration of the initialization function. 1946 llvm::GlobalValue *Init = nullptr; 1947 bool InitIsInitFunc = false; 1948 if (VD->hasDefinition()) { 1949 InitIsInitFunc = true; 1950 if (InitFunc) 1951 Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(), 1952 InitFunc); 1953 } else { 1954 // Emit a weak global function referring to the initialization function. 1955 // This function will not exist if the TU defining the thread_local 1956 // variable in question does not need any dynamic initialization for 1957 // its thread_local variables. 1958 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 1959 Init = llvm::Function::Create( 1960 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(), 1961 &CGM.getModule()); 1962 } 1963 1964 if (Init) 1965 Init->setVisibility(Var->getVisibility()); 1966 1967 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 1968 llvm::LLVMContext &Context = CGM.getModule().getContext(); 1969 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 1970 CGBuilderTy Builder(Entry); 1971 if (InitIsInitFunc) { 1972 if (Init) 1973 Builder.CreateCall(Init); 1974 } else { 1975 // Don't know whether we have an init function. Call it if it exists. 1976 llvm::Value *Have = Builder.CreateIsNotNull(Init); 1977 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1978 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1979 Builder.CreateCondBr(Have, InitBB, ExitBB); 1980 1981 Builder.SetInsertPoint(InitBB); 1982 Builder.CreateCall(Init); 1983 Builder.CreateBr(ExitBB); 1984 1985 Builder.SetInsertPoint(ExitBB); 1986 } 1987 1988 // For a reference, the result of the wrapper function is a pointer to 1989 // the referenced object. 1990 llvm::Value *Val = Var; 1991 if (VD->getType()->isReferenceType()) { 1992 llvm::LoadInst *LI = Builder.CreateLoad(Val); 1993 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity()); 1994 Val = LI; 1995 } 1996 if (Val->getType() != Wrapper->getReturnType()) 1997 Val = Builder.CreatePointerBitCastOrAddrSpaceCast( 1998 Val, Wrapper->getReturnType(), ""); 1999 Builder.CreateRet(Val); 2000 } 2001 } 2002 2003 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, 2004 const VarDecl *VD, 2005 QualType LValType) { 2006 QualType T = VD->getType(); 2007 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T); 2008 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty); 2009 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val); 2010 2011 Val = CGF.Builder.CreateCall(Wrapper); 2012 2013 LValue LV; 2014 if (VD->getType()->isReferenceType()) 2015 LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType); 2016 else 2017 LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD)); 2018 // FIXME: need setObjCGCLValueClass? 2019 return LV; 2020 } 2021 2022 /// Return whether the given global decl needs a VTT parameter, which it does 2023 /// if it's a base constructor or destructor with virtual bases. 2024 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 2025 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 2026 2027 // We don't have any virtual bases, just return early. 2028 if (!MD->getParent()->getNumVBases()) 2029 return false; 2030 2031 // Check if we have a base constructor. 2032 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 2033 return true; 2034 2035 // Check if we have a base destructor. 2036 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 2037 return true; 2038 2039 return false; 2040 } 2041 2042 namespace { 2043 class ItaniumRTTIBuilder { 2044 CodeGenModule &CGM; // Per-module state. 2045 llvm::LLVMContext &VMContext; 2046 const ItaniumCXXABI &CXXABI; // Per-module state. 2047 2048 /// Fields - The fields of the RTTI descriptor currently being built. 2049 SmallVector<llvm::Constant *, 16> Fields; 2050 2051 /// GetAddrOfTypeName - Returns the mangled type name of the given type. 2052 llvm::GlobalVariable * 2053 GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage); 2054 2055 /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI 2056 /// descriptor of the given type. 2057 llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty); 2058 2059 /// BuildVTablePointer - Build the vtable pointer for the given type. 2060 void BuildVTablePointer(const Type *Ty); 2061 2062 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2063 /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b. 2064 void BuildSIClassTypeInfo(const CXXRecordDecl *RD); 2065 2066 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2067 /// classes with bases that do not satisfy the abi::__si_class_type_info 2068 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2069 void BuildVMIClassTypeInfo(const CXXRecordDecl *RD); 2070 2071 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used 2072 /// for pointer types. 2073 void BuildPointerTypeInfo(QualType PointeeTy); 2074 2075 /// BuildObjCObjectTypeInfo - Build the appropriate kind of 2076 /// type_info for an object type. 2077 void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty); 2078 2079 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2080 /// struct, used for member pointer types. 2081 void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty); 2082 2083 public: 2084 ItaniumRTTIBuilder(const ItaniumCXXABI &ABI) 2085 : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {} 2086 2087 // Pointer type info flags. 2088 enum { 2089 /// PTI_Const - Type has const qualifier. 2090 PTI_Const = 0x1, 2091 2092 /// PTI_Volatile - Type has volatile qualifier. 2093 PTI_Volatile = 0x2, 2094 2095 /// PTI_Restrict - Type has restrict qualifier. 2096 PTI_Restrict = 0x4, 2097 2098 /// PTI_Incomplete - Type is incomplete. 2099 PTI_Incomplete = 0x8, 2100 2101 /// PTI_ContainingClassIncomplete - Containing class is incomplete. 2102 /// (in pointer to member). 2103 PTI_ContainingClassIncomplete = 0x10 2104 }; 2105 2106 // VMI type info flags. 2107 enum { 2108 /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance. 2109 VMI_NonDiamondRepeat = 0x1, 2110 2111 /// VMI_DiamondShaped - Class is diamond shaped. 2112 VMI_DiamondShaped = 0x2 2113 }; 2114 2115 // Base class type info flags. 2116 enum { 2117 /// BCTI_Virtual - Base class is virtual. 2118 BCTI_Virtual = 0x1, 2119 2120 /// BCTI_Public - Base class is public. 2121 BCTI_Public = 0x2 2122 }; 2123 2124 /// BuildTypeInfo - Build the RTTI type info struct for the given type. 2125 /// 2126 /// \param Force - true to force the creation of this RTTI value 2127 llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false); 2128 }; 2129 } 2130 2131 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName( 2132 QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) { 2133 SmallString<256> OutName; 2134 llvm::raw_svector_ostream Out(OutName); 2135 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out); 2136 Out.flush(); 2137 StringRef Name = OutName.str(); 2138 2139 // We know that the mangled name of the type starts at index 4 of the 2140 // mangled name of the typename, so we can just index into it in order to 2141 // get the mangled name of the type. 2142 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext, 2143 Name.substr(4)); 2144 2145 llvm::GlobalVariable *GV = 2146 CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage); 2147 2148 GV->setInitializer(Init); 2149 2150 return GV; 2151 } 2152 2153 llvm::Constant * 2154 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) { 2155 // Mangle the RTTI name. 2156 SmallString<256> OutName; 2157 llvm::raw_svector_ostream Out(OutName); 2158 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2159 Out.flush(); 2160 StringRef Name = OutName.str(); 2161 2162 // Look for an existing global. 2163 llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name); 2164 2165 if (!GV) { 2166 // Create a new global variable. 2167 GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy, 2168 /*Constant=*/true, 2169 llvm::GlobalValue::ExternalLinkage, nullptr, 2170 Name); 2171 } 2172 2173 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2174 } 2175 2176 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type 2177 /// info for that type is defined in the standard library. 2178 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) { 2179 // Itanium C++ ABI 2.9.2: 2180 // Basic type information (e.g. for "int", "bool", etc.) will be kept in 2181 // the run-time support library. Specifically, the run-time support 2182 // library should contain type_info objects for the types X, X* and 2183 // X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char, 2184 // unsigned char, signed char, short, unsigned short, int, unsigned int, 2185 // long, unsigned long, long long, unsigned long long, float, double, 2186 // long double, char16_t, char32_t, and the IEEE 754r decimal and 2187 // half-precision floating point types. 2188 switch (Ty->getKind()) { 2189 case BuiltinType::Void: 2190 case BuiltinType::NullPtr: 2191 case BuiltinType::Bool: 2192 case BuiltinType::WChar_S: 2193 case BuiltinType::WChar_U: 2194 case BuiltinType::Char_U: 2195 case BuiltinType::Char_S: 2196 case BuiltinType::UChar: 2197 case BuiltinType::SChar: 2198 case BuiltinType::Short: 2199 case BuiltinType::UShort: 2200 case BuiltinType::Int: 2201 case BuiltinType::UInt: 2202 case BuiltinType::Long: 2203 case BuiltinType::ULong: 2204 case BuiltinType::LongLong: 2205 case BuiltinType::ULongLong: 2206 case BuiltinType::Half: 2207 case BuiltinType::Float: 2208 case BuiltinType::Double: 2209 case BuiltinType::LongDouble: 2210 case BuiltinType::Char16: 2211 case BuiltinType::Char32: 2212 case BuiltinType::Int128: 2213 case BuiltinType::UInt128: 2214 case BuiltinType::OCLImage1d: 2215 case BuiltinType::OCLImage1dArray: 2216 case BuiltinType::OCLImage1dBuffer: 2217 case BuiltinType::OCLImage2d: 2218 case BuiltinType::OCLImage2dArray: 2219 case BuiltinType::OCLImage3d: 2220 case BuiltinType::OCLSampler: 2221 case BuiltinType::OCLEvent: 2222 return true; 2223 2224 case BuiltinType::Dependent: 2225 #define BUILTIN_TYPE(Id, SingletonId) 2226 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2227 case BuiltinType::Id: 2228 #include "clang/AST/BuiltinTypes.def" 2229 llvm_unreachable("asking for RRTI for a placeholder type!"); 2230 2231 case BuiltinType::ObjCId: 2232 case BuiltinType::ObjCClass: 2233 case BuiltinType::ObjCSel: 2234 llvm_unreachable("FIXME: Objective-C types are unsupported!"); 2235 } 2236 2237 llvm_unreachable("Invalid BuiltinType Kind!"); 2238 } 2239 2240 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) { 2241 QualType PointeeTy = PointerTy->getPointeeType(); 2242 const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy); 2243 if (!BuiltinTy) 2244 return false; 2245 2246 // Check the qualifiers. 2247 Qualifiers Quals = PointeeTy.getQualifiers(); 2248 Quals.removeConst(); 2249 2250 if (!Quals.empty()) 2251 return false; 2252 2253 return TypeInfoIsInStandardLibrary(BuiltinTy); 2254 } 2255 2256 /// IsStandardLibraryRTTIDescriptor - Returns whether the type 2257 /// information for the given type exists in the standard library. 2258 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) { 2259 // Type info for builtin types is defined in the standard library. 2260 if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty)) 2261 return TypeInfoIsInStandardLibrary(BuiltinTy); 2262 2263 // Type info for some pointer types to builtin types is defined in the 2264 // standard library. 2265 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2266 return TypeInfoIsInStandardLibrary(PointerTy); 2267 2268 return false; 2269 } 2270 2271 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for 2272 /// the given type exists somewhere else, and that we should not emit the type 2273 /// information in this translation unit. Assumes that it is not a 2274 /// standard-library type. 2275 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM, 2276 QualType Ty) { 2277 ASTContext &Context = CGM.getContext(); 2278 2279 // If RTTI is disabled, assume it might be disabled in the 2280 // translation unit that defines any potential key function, too. 2281 if (!Context.getLangOpts().RTTI) return false; 2282 2283 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2284 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 2285 if (!RD->hasDefinition()) 2286 return false; 2287 2288 if (!RD->isDynamicClass()) 2289 return false; 2290 2291 // FIXME: this may need to be reconsidered if the key function 2292 // changes. 2293 return CGM.getVTables().isVTableExternal(RD); 2294 } 2295 2296 return false; 2297 } 2298 2299 /// IsIncompleteClassType - Returns whether the given record type is incomplete. 2300 static bool IsIncompleteClassType(const RecordType *RecordTy) { 2301 return !RecordTy->getDecl()->isCompleteDefinition(); 2302 } 2303 2304 /// ContainsIncompleteClassType - Returns whether the given type contains an 2305 /// incomplete class type. This is true if 2306 /// 2307 /// * The given type is an incomplete class type. 2308 /// * The given type is a pointer type whose pointee type contains an 2309 /// incomplete class type. 2310 /// * The given type is a member pointer type whose class is an incomplete 2311 /// class type. 2312 /// * The given type is a member pointer type whoise pointee type contains an 2313 /// incomplete class type. 2314 /// is an indirect or direct pointer to an incomplete class type. 2315 static bool ContainsIncompleteClassType(QualType Ty) { 2316 if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) { 2317 if (IsIncompleteClassType(RecordTy)) 2318 return true; 2319 } 2320 2321 if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty)) 2322 return ContainsIncompleteClassType(PointerTy->getPointeeType()); 2323 2324 if (const MemberPointerType *MemberPointerTy = 2325 dyn_cast<MemberPointerType>(Ty)) { 2326 // Check if the class type is incomplete. 2327 const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass()); 2328 if (IsIncompleteClassType(ClassType)) 2329 return true; 2330 2331 return ContainsIncompleteClassType(MemberPointerTy->getPointeeType()); 2332 } 2333 2334 return false; 2335 } 2336 2337 // CanUseSingleInheritance - Return whether the given record decl has a "single, 2338 // public, non-virtual base at offset zero (i.e. the derived class is dynamic 2339 // iff the base is)", according to Itanium C++ ABI, 2.95p6b. 2340 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) { 2341 // Check the number of bases. 2342 if (RD->getNumBases() != 1) 2343 return false; 2344 2345 // Get the base. 2346 CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(); 2347 2348 // Check that the base is not virtual. 2349 if (Base->isVirtual()) 2350 return false; 2351 2352 // Check that the base is public. 2353 if (Base->getAccessSpecifier() != AS_public) 2354 return false; 2355 2356 // Check that the class is dynamic iff the base is. 2357 const CXXRecordDecl *BaseDecl = 2358 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2359 if (!BaseDecl->isEmpty() && 2360 BaseDecl->isDynamicClass() != RD->isDynamicClass()) 2361 return false; 2362 2363 return true; 2364 } 2365 2366 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) { 2367 // abi::__class_type_info. 2368 static const char * const ClassTypeInfo = 2369 "_ZTVN10__cxxabiv117__class_type_infoE"; 2370 // abi::__si_class_type_info. 2371 static const char * const SIClassTypeInfo = 2372 "_ZTVN10__cxxabiv120__si_class_type_infoE"; 2373 // abi::__vmi_class_type_info. 2374 static const char * const VMIClassTypeInfo = 2375 "_ZTVN10__cxxabiv121__vmi_class_type_infoE"; 2376 2377 const char *VTableName = nullptr; 2378 2379 switch (Ty->getTypeClass()) { 2380 #define TYPE(Class, Base) 2381 #define ABSTRACT_TYPE(Class, Base) 2382 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2383 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2384 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2385 #include "clang/AST/TypeNodes.def" 2386 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2387 2388 case Type::LValueReference: 2389 case Type::RValueReference: 2390 llvm_unreachable("References shouldn't get here"); 2391 2392 case Type::Auto: 2393 llvm_unreachable("Undeduced auto type shouldn't get here"); 2394 2395 case Type::Builtin: 2396 // GCC treats vector and complex types as fundamental types. 2397 case Type::Vector: 2398 case Type::ExtVector: 2399 case Type::Complex: 2400 case Type::Atomic: 2401 // FIXME: GCC treats block pointers as fundamental types?! 2402 case Type::BlockPointer: 2403 // abi::__fundamental_type_info. 2404 VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE"; 2405 break; 2406 2407 case Type::ConstantArray: 2408 case Type::IncompleteArray: 2409 case Type::VariableArray: 2410 // abi::__array_type_info. 2411 VTableName = "_ZTVN10__cxxabiv117__array_type_infoE"; 2412 break; 2413 2414 case Type::FunctionNoProto: 2415 case Type::FunctionProto: 2416 // abi::__function_type_info. 2417 VTableName = "_ZTVN10__cxxabiv120__function_type_infoE"; 2418 break; 2419 2420 case Type::Enum: 2421 // abi::__enum_type_info. 2422 VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE"; 2423 break; 2424 2425 case Type::Record: { 2426 const CXXRecordDecl *RD = 2427 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2428 2429 if (!RD->hasDefinition() || !RD->getNumBases()) { 2430 VTableName = ClassTypeInfo; 2431 } else if (CanUseSingleInheritance(RD)) { 2432 VTableName = SIClassTypeInfo; 2433 } else { 2434 VTableName = VMIClassTypeInfo; 2435 } 2436 2437 break; 2438 } 2439 2440 case Type::ObjCObject: 2441 // Ignore protocol qualifiers. 2442 Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr(); 2443 2444 // Handle id and Class. 2445 if (isa<BuiltinType>(Ty)) { 2446 VTableName = ClassTypeInfo; 2447 break; 2448 } 2449 2450 assert(isa<ObjCInterfaceType>(Ty)); 2451 // Fall through. 2452 2453 case Type::ObjCInterface: 2454 if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) { 2455 VTableName = SIClassTypeInfo; 2456 } else { 2457 VTableName = ClassTypeInfo; 2458 } 2459 break; 2460 2461 case Type::ObjCObjectPointer: 2462 case Type::Pointer: 2463 // abi::__pointer_type_info. 2464 VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE"; 2465 break; 2466 2467 case Type::MemberPointer: 2468 // abi::__pointer_to_member_type_info. 2469 VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE"; 2470 break; 2471 } 2472 2473 llvm::Constant *VTable = 2474 CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy); 2475 2476 llvm::Type *PtrDiffTy = 2477 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 2478 2479 // The vtable address point is 2. 2480 llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2); 2481 VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two); 2482 VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy); 2483 2484 Fields.push_back(VTable); 2485 } 2486 2487 /// \brief Return the linkage that the type info and type info name constants 2488 /// should have for the given type. 2489 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM, 2490 QualType Ty) { 2491 // Itanium C++ ABI 2.9.5p7: 2492 // In addition, it and all of the intermediate abi::__pointer_type_info 2493 // structs in the chain down to the abi::__class_type_info for the 2494 // incomplete class type must be prevented from resolving to the 2495 // corresponding type_info structs for the complete class type, possibly 2496 // by making them local static objects. Finally, a dummy class RTTI is 2497 // generated for the incomplete type that will not resolve to the final 2498 // complete class RTTI (because the latter need not exist), possibly by 2499 // making it a local static object. 2500 if (ContainsIncompleteClassType(Ty)) 2501 return llvm::GlobalValue::InternalLinkage; 2502 2503 switch (Ty->getLinkage()) { 2504 case NoLinkage: 2505 case InternalLinkage: 2506 case UniqueExternalLinkage: 2507 return llvm::GlobalValue::InternalLinkage; 2508 2509 case VisibleNoLinkage: 2510 case ExternalLinkage: 2511 if (!CGM.getLangOpts().RTTI) { 2512 // RTTI is not enabled, which means that this type info struct is going 2513 // to be used for exception handling. Give it linkonce_odr linkage. 2514 return llvm::GlobalValue::LinkOnceODRLinkage; 2515 } 2516 2517 if (const RecordType *Record = dyn_cast<RecordType>(Ty)) { 2518 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2519 if (RD->hasAttr<WeakAttr>()) 2520 return llvm::GlobalValue::WeakODRLinkage; 2521 if (RD->isDynamicClass()) 2522 return CGM.getVTableLinkage(RD); 2523 } 2524 2525 return llvm::GlobalValue::LinkOnceODRLinkage; 2526 } 2527 2528 llvm_unreachable("Invalid linkage!"); 2529 } 2530 2531 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) { 2532 // We want to operate on the canonical type. 2533 Ty = CGM.getContext().getCanonicalType(Ty); 2534 2535 // Check if we've already emitted an RTTI descriptor for this type. 2536 SmallString<256> OutName; 2537 llvm::raw_svector_ostream Out(OutName); 2538 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out); 2539 Out.flush(); 2540 StringRef Name = OutName.str(); 2541 2542 llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name); 2543 if (OldGV && !OldGV->isDeclaration()) { 2544 assert(!OldGV->hasAvailableExternallyLinkage() && 2545 "available_externally typeinfos not yet implemented"); 2546 2547 return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy); 2548 } 2549 2550 // Check if there is already an external RTTI descriptor for this type. 2551 bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty); 2552 if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty))) 2553 return GetAddrOfExternalRTTIDescriptor(Ty); 2554 2555 // Emit the standard library with external linkage. 2556 llvm::GlobalVariable::LinkageTypes Linkage; 2557 if (IsStdLib) 2558 Linkage = llvm::GlobalValue::ExternalLinkage; 2559 else 2560 Linkage = getTypeInfoLinkage(CGM, Ty); 2561 2562 // Add the vtable pointer. 2563 BuildVTablePointer(cast<Type>(Ty)); 2564 2565 // And the name. 2566 llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage); 2567 llvm::Constant *TypeNameField; 2568 2569 // If we're supposed to demote the visibility, be sure to set a flag 2570 // to use a string comparison for type_info comparisons. 2571 ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness = 2572 CXXABI.classifyRTTIUniqueness(Ty, Linkage); 2573 if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) { 2574 // The flag is the sign bit, which on ARM64 is defined to be clear 2575 // for global pointers. This is very ARM64-specific. 2576 TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty); 2577 llvm::Constant *flag = 2578 llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63); 2579 TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag); 2580 TypeNameField = 2581 llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy); 2582 } else { 2583 TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy); 2584 } 2585 Fields.push_back(TypeNameField); 2586 2587 switch (Ty->getTypeClass()) { 2588 #define TYPE(Class, Base) 2589 #define ABSTRACT_TYPE(Class, Base) 2590 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2591 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2592 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2593 #include "clang/AST/TypeNodes.def" 2594 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 2595 2596 // GCC treats vector types as fundamental types. 2597 case Type::Builtin: 2598 case Type::Vector: 2599 case Type::ExtVector: 2600 case Type::Complex: 2601 case Type::BlockPointer: 2602 // Itanium C++ ABI 2.9.5p4: 2603 // abi::__fundamental_type_info adds no data members to std::type_info. 2604 break; 2605 2606 case Type::LValueReference: 2607 case Type::RValueReference: 2608 llvm_unreachable("References shouldn't get here"); 2609 2610 case Type::Auto: 2611 llvm_unreachable("Undeduced auto type shouldn't get here"); 2612 2613 case Type::ConstantArray: 2614 case Type::IncompleteArray: 2615 case Type::VariableArray: 2616 // Itanium C++ ABI 2.9.5p5: 2617 // abi::__array_type_info adds no data members to std::type_info. 2618 break; 2619 2620 case Type::FunctionNoProto: 2621 case Type::FunctionProto: 2622 // Itanium C++ ABI 2.9.5p5: 2623 // abi::__function_type_info adds no data members to std::type_info. 2624 break; 2625 2626 case Type::Enum: 2627 // Itanium C++ ABI 2.9.5p5: 2628 // abi::__enum_type_info adds no data members to std::type_info. 2629 break; 2630 2631 case Type::Record: { 2632 const CXXRecordDecl *RD = 2633 cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl()); 2634 if (!RD->hasDefinition() || !RD->getNumBases()) { 2635 // We don't need to emit any fields. 2636 break; 2637 } 2638 2639 if (CanUseSingleInheritance(RD)) 2640 BuildSIClassTypeInfo(RD); 2641 else 2642 BuildVMIClassTypeInfo(RD); 2643 2644 break; 2645 } 2646 2647 case Type::ObjCObject: 2648 case Type::ObjCInterface: 2649 BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty)); 2650 break; 2651 2652 case Type::ObjCObjectPointer: 2653 BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 2654 break; 2655 2656 case Type::Pointer: 2657 BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType()); 2658 break; 2659 2660 case Type::MemberPointer: 2661 BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty)); 2662 break; 2663 2664 case Type::Atomic: 2665 // No fields, at least for the moment. 2666 break; 2667 } 2668 2669 llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields); 2670 2671 llvm::GlobalVariable *GV = 2672 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 2673 /*Constant=*/true, Linkage, Init, Name); 2674 2675 // If there's already an old global variable, replace it with the new one. 2676 if (OldGV) { 2677 GV->takeName(OldGV); 2678 llvm::Constant *NewPtr = 2679 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 2680 OldGV->replaceAllUsesWith(NewPtr); 2681 OldGV->eraseFromParent(); 2682 } 2683 2684 // The Itanium ABI specifies that type_info objects must be globally 2685 // unique, with one exception: if the type is an incomplete class 2686 // type or a (possibly indirect) pointer to one. That exception 2687 // affects the general case of comparing type_info objects produced 2688 // by the typeid operator, which is why the comparison operators on 2689 // std::type_info generally use the type_info name pointers instead 2690 // of the object addresses. However, the language's built-in uses 2691 // of RTTI generally require class types to be complete, even when 2692 // manipulating pointers to those class types. This allows the 2693 // implementation of dynamic_cast to rely on address equality tests, 2694 // which is much faster. 2695 2696 // All of this is to say that it's important that both the type_info 2697 // object and the type_info name be uniqued when weakly emitted. 2698 2699 // Give the type_info object and name the formal visibility of the 2700 // type itself. 2701 llvm::GlobalValue::VisibilityTypes llvmVisibility; 2702 if (llvm::GlobalValue::isLocalLinkage(Linkage)) 2703 // If the linkage is local, only default visibility makes sense. 2704 llvmVisibility = llvm::GlobalValue::DefaultVisibility; 2705 else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden) 2706 llvmVisibility = llvm::GlobalValue::HiddenVisibility; 2707 else 2708 llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility()); 2709 TypeName->setVisibility(llvmVisibility); 2710 GV->setVisibility(llvmVisibility); 2711 2712 return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy); 2713 } 2714 2715 /// ComputeQualifierFlags - Compute the pointer type info flags from the 2716 /// given qualifier. 2717 static unsigned ComputeQualifierFlags(Qualifiers Quals) { 2718 unsigned Flags = 0; 2719 2720 if (Quals.hasConst()) 2721 Flags |= ItaniumRTTIBuilder::PTI_Const; 2722 if (Quals.hasVolatile()) 2723 Flags |= ItaniumRTTIBuilder::PTI_Volatile; 2724 if (Quals.hasRestrict()) 2725 Flags |= ItaniumRTTIBuilder::PTI_Restrict; 2726 2727 return Flags; 2728 } 2729 2730 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info 2731 /// for the given Objective-C object type. 2732 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) { 2733 // Drop qualifiers. 2734 const Type *T = OT->getBaseType().getTypePtr(); 2735 assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T)); 2736 2737 // The builtin types are abi::__class_type_infos and don't require 2738 // extra fields. 2739 if (isa<BuiltinType>(T)) return; 2740 2741 ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl(); 2742 ObjCInterfaceDecl *Super = Class->getSuperClass(); 2743 2744 // Root classes are also __class_type_info. 2745 if (!Super) return; 2746 2747 QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super); 2748 2749 // Everything else is single inheritance. 2750 llvm::Constant *BaseTypeInfo = 2751 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy); 2752 Fields.push_back(BaseTypeInfo); 2753 } 2754 2755 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single 2756 /// inheritance, according to the Itanium C++ ABI, 2.95p6b. 2757 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) { 2758 // Itanium C++ ABI 2.9.5p6b: 2759 // It adds to abi::__class_type_info a single member pointing to the 2760 // type_info structure for the base type, 2761 llvm::Constant *BaseTypeInfo = 2762 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType()); 2763 Fields.push_back(BaseTypeInfo); 2764 } 2765 2766 namespace { 2767 /// SeenBases - Contains virtual and non-virtual bases seen when traversing 2768 /// a class hierarchy. 2769 struct SeenBases { 2770 llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases; 2771 llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases; 2772 }; 2773 } 2774 2775 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in 2776 /// abi::__vmi_class_type_info. 2777 /// 2778 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base, 2779 SeenBases &Bases) { 2780 2781 unsigned Flags = 0; 2782 2783 const CXXRecordDecl *BaseDecl = 2784 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2785 2786 if (Base->isVirtual()) { 2787 // Mark the virtual base as seen. 2788 if (!Bases.VirtualBases.insert(BaseDecl)) { 2789 // If this virtual base has been seen before, then the class is diamond 2790 // shaped. 2791 Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped; 2792 } else { 2793 if (Bases.NonVirtualBases.count(BaseDecl)) 2794 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2795 } 2796 } else { 2797 // Mark the non-virtual base as seen. 2798 if (!Bases.NonVirtualBases.insert(BaseDecl)) { 2799 // If this non-virtual base has been seen before, then the class has non- 2800 // diamond shaped repeated inheritance. 2801 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2802 } else { 2803 if (Bases.VirtualBases.count(BaseDecl)) 2804 Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat; 2805 } 2806 } 2807 2808 // Walk all bases. 2809 for (const auto &I : BaseDecl->bases()) 2810 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 2811 2812 return Flags; 2813 } 2814 2815 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) { 2816 unsigned Flags = 0; 2817 SeenBases Bases; 2818 2819 // Walk all bases. 2820 for (const auto &I : RD->bases()) 2821 Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases); 2822 2823 return Flags; 2824 } 2825 2826 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for 2827 /// classes with bases that do not satisfy the abi::__si_class_type_info 2828 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c. 2829 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) { 2830 llvm::Type *UnsignedIntLTy = 2831 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2832 2833 // Itanium C++ ABI 2.9.5p6c: 2834 // __flags is a word with flags describing details about the class 2835 // structure, which may be referenced by using the __flags_masks 2836 // enumeration. These flags refer to both direct and indirect bases. 2837 unsigned Flags = ComputeVMIClassTypeInfoFlags(RD); 2838 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2839 2840 // Itanium C++ ABI 2.9.5p6c: 2841 // __base_count is a word with the number of direct proper base class 2842 // descriptions that follow. 2843 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases())); 2844 2845 if (!RD->getNumBases()) 2846 return; 2847 2848 llvm::Type *LongLTy = 2849 CGM.getTypes().ConvertType(CGM.getContext().LongTy); 2850 2851 // Now add the base class descriptions. 2852 2853 // Itanium C++ ABI 2.9.5p6c: 2854 // __base_info[] is an array of base class descriptions -- one for every 2855 // direct proper base. Each description is of the type: 2856 // 2857 // struct abi::__base_class_type_info { 2858 // public: 2859 // const __class_type_info *__base_type; 2860 // long __offset_flags; 2861 // 2862 // enum __offset_flags_masks { 2863 // __virtual_mask = 0x1, 2864 // __public_mask = 0x2, 2865 // __offset_shift = 8 2866 // }; 2867 // }; 2868 for (const auto &Base : RD->bases()) { 2869 // The __base_type member points to the RTTI for the base type. 2870 Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType())); 2871 2872 const CXXRecordDecl *BaseDecl = 2873 cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 2874 2875 int64_t OffsetFlags = 0; 2876 2877 // All but the lower 8 bits of __offset_flags are a signed offset. 2878 // For a non-virtual base, this is the offset in the object of the base 2879 // subobject. For a virtual base, this is the offset in the virtual table of 2880 // the virtual base offset for the virtual base referenced (negative). 2881 CharUnits Offset; 2882 if (Base.isVirtual()) 2883 Offset = 2884 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl); 2885 else { 2886 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 2887 Offset = Layout.getBaseClassOffset(BaseDecl); 2888 }; 2889 2890 OffsetFlags = uint64_t(Offset.getQuantity()) << 8; 2891 2892 // The low-order byte of __offset_flags contains flags, as given by the 2893 // masks from the enumeration __offset_flags_masks. 2894 if (Base.isVirtual()) 2895 OffsetFlags |= BCTI_Virtual; 2896 if (Base.getAccessSpecifier() == AS_public) 2897 OffsetFlags |= BCTI_Public; 2898 2899 Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags)); 2900 } 2901 } 2902 2903 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, 2904 /// used for pointer types. 2905 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) { 2906 Qualifiers Quals; 2907 QualType UnqualifiedPointeeTy = 2908 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals); 2909 2910 // Itanium C++ ABI 2.9.5p7: 2911 // __flags is a flag word describing the cv-qualification and other 2912 // attributes of the type pointed to 2913 unsigned Flags = ComputeQualifierFlags(Quals); 2914 2915 // Itanium C++ ABI 2.9.5p7: 2916 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 2917 // incomplete class type, the incomplete target type flag is set. 2918 if (ContainsIncompleteClassType(UnqualifiedPointeeTy)) 2919 Flags |= PTI_Incomplete; 2920 2921 llvm::Type *UnsignedIntLTy = 2922 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2923 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2924 2925 // Itanium C++ ABI 2.9.5p7: 2926 // __pointee is a pointer to the std::type_info derivation for the 2927 // unqualified type being pointed to. 2928 llvm::Constant *PointeeTypeInfo = 2929 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy); 2930 Fields.push_back(PointeeTypeInfo); 2931 } 2932 2933 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info 2934 /// struct, used for member pointer types. 2935 void 2936 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) { 2937 QualType PointeeTy = Ty->getPointeeType(); 2938 2939 Qualifiers Quals; 2940 QualType UnqualifiedPointeeTy = 2941 CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals); 2942 2943 // Itanium C++ ABI 2.9.5p7: 2944 // __flags is a flag word describing the cv-qualification and other 2945 // attributes of the type pointed to. 2946 unsigned Flags = ComputeQualifierFlags(Quals); 2947 2948 const RecordType *ClassType = cast<RecordType>(Ty->getClass()); 2949 2950 // Itanium C++ ABI 2.9.5p7: 2951 // When the abi::__pbase_type_info is for a direct or indirect pointer to an 2952 // incomplete class type, the incomplete target type flag is set. 2953 if (ContainsIncompleteClassType(UnqualifiedPointeeTy)) 2954 Flags |= PTI_Incomplete; 2955 2956 if (IsIncompleteClassType(ClassType)) 2957 Flags |= PTI_ContainingClassIncomplete; 2958 2959 llvm::Type *UnsignedIntLTy = 2960 CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy); 2961 Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags)); 2962 2963 // Itanium C++ ABI 2.9.5p7: 2964 // __pointee is a pointer to the std::type_info derivation for the 2965 // unqualified type being pointed to. 2966 llvm::Constant *PointeeTypeInfo = 2967 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy); 2968 Fields.push_back(PointeeTypeInfo); 2969 2970 // Itanium C++ ABI 2.9.5p9: 2971 // __context is a pointer to an abi::__class_type_info corresponding to the 2972 // class type containing the member pointed to 2973 // (e.g., the "A" in "int A::*"). 2974 Fields.push_back( 2975 ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0))); 2976 } 2977 2978 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) { 2979 return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty); 2980 } 2981 2982 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) { 2983 QualType PointerType = getContext().getPointerType(Type); 2984 QualType PointerTypeConst = getContext().getPointerType(Type.withConst()); 2985 ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true); 2986 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true); 2987 ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true); 2988 } 2989 2990 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() { 2991 QualType FundamentalTypes[] = { 2992 getContext().VoidTy, getContext().NullPtrTy, 2993 getContext().BoolTy, getContext().WCharTy, 2994 getContext().CharTy, getContext().UnsignedCharTy, 2995 getContext().SignedCharTy, getContext().ShortTy, 2996 getContext().UnsignedShortTy, getContext().IntTy, 2997 getContext().UnsignedIntTy, getContext().LongTy, 2998 getContext().UnsignedLongTy, getContext().LongLongTy, 2999 getContext().UnsignedLongLongTy, getContext().HalfTy, 3000 getContext().FloatTy, getContext().DoubleTy, 3001 getContext().LongDoubleTy, getContext().Char16Ty, 3002 getContext().Char32Ty, 3003 }; 3004 for (const QualType &FundamentalType : FundamentalTypes) 3005 EmitFundamentalRTTIDescriptor(FundamentalType); 3006 } 3007 3008 /// What sort of uniqueness rules should we use for the RTTI for the 3009 /// given type? 3010 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness( 3011 QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const { 3012 if (shouldRTTIBeUnique()) 3013 return RUK_Unique; 3014 3015 // It's only necessary for linkonce_odr or weak_odr linkage. 3016 if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage && 3017 Linkage != llvm::GlobalValue::WeakODRLinkage) 3018 return RUK_Unique; 3019 3020 // It's only necessary with default visibility. 3021 if (CanTy->getVisibility() != DefaultVisibility) 3022 return RUK_Unique; 3023 3024 // If we're not required to publish this symbol, hide it. 3025 if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage) 3026 return RUK_NonUniqueHidden; 3027 3028 // If we're required to publish this symbol, as we might be under an 3029 // explicit instantiation, leave it with default visibility but 3030 // enable string-comparisons. 3031 assert(Linkage == llvm::GlobalValue::WeakODRLinkage); 3032 return RUK_NonUniqueVisible; 3033 } 3034 3035 // Find out how to codegen the complete destructor and constructor 3036 namespace { 3037 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT }; 3038 } 3039 static StructorCodegen getCodegenToUse(CodeGenModule &CGM, 3040 const CXXMethodDecl *MD) { 3041 if (!CGM.getCodeGenOpts().CXXCtorDtorAliases) 3042 return StructorCodegen::Emit; 3043 3044 // The complete and base structors are not equivalent if there are any virtual 3045 // bases, so emit separate functions. 3046 if (MD->getParent()->getNumVBases()) 3047 return StructorCodegen::Emit; 3048 3049 GlobalDecl AliasDecl; 3050 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 3051 AliasDecl = GlobalDecl(DD, Dtor_Complete); 3052 } else { 3053 const auto *CD = cast<CXXConstructorDecl>(MD); 3054 AliasDecl = GlobalDecl(CD, Ctor_Complete); 3055 } 3056 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3057 3058 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) 3059 return StructorCodegen::RAUW; 3060 3061 // FIXME: Should we allow available_externally aliases? 3062 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 3063 return StructorCodegen::RAUW; 3064 3065 if (llvm::GlobalValue::isWeakForLinker(Linkage)) { 3066 // Only ELF supports COMDATs with arbitrary names (C5/D5). 3067 if (CGM.getTarget().getTriple().isOSBinFormatELF()) 3068 return StructorCodegen::COMDAT; 3069 return StructorCodegen::Emit; 3070 } 3071 3072 return StructorCodegen::Alias; 3073 } 3074 3075 static void emitConstructorDestructorAlias(CodeGenModule &CGM, 3076 GlobalDecl AliasDecl, 3077 GlobalDecl TargetDecl) { 3078 llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl); 3079 3080 StringRef MangledName = CGM.getMangledName(AliasDecl); 3081 llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName); 3082 if (Entry && !Entry->isDeclaration()) 3083 return; 3084 3085 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl)); 3086 llvm::PointerType *AliasType = Aliasee->getType(); 3087 3088 // Create the alias with no name. 3089 auto *Alias = llvm::GlobalAlias::create( 3090 AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule()); 3091 3092 // Switch any previous uses to the alias. 3093 if (Entry) { 3094 assert(Entry->getType() == AliasType && 3095 "declaration exists with different type"); 3096 Alias->takeName(Entry); 3097 Entry->replaceAllUsesWith(Alias); 3098 Entry->eraseFromParent(); 3099 } else { 3100 Alias->setName(MangledName); 3101 } 3102 3103 // Finally, set up the alias with its proper name and attributes. 3104 CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 3105 } 3106 3107 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD, 3108 StructorType Type) { 3109 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 3110 const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD); 3111 3112 StructorCodegen CGType = getCodegenToUse(CGM, MD); 3113 3114 if (Type == StructorType::Complete) { 3115 GlobalDecl CompleteDecl; 3116 GlobalDecl BaseDecl; 3117 if (CD) { 3118 CompleteDecl = GlobalDecl(CD, Ctor_Complete); 3119 BaseDecl = GlobalDecl(CD, Ctor_Base); 3120 } else { 3121 CompleteDecl = GlobalDecl(DD, Dtor_Complete); 3122 BaseDecl = GlobalDecl(DD, Dtor_Base); 3123 } 3124 3125 if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) { 3126 emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl); 3127 return; 3128 } 3129 3130 if (CGType == StructorCodegen::RAUW) { 3131 StringRef MangledName = CGM.getMangledName(CompleteDecl); 3132 auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl)); 3133 CGM.addReplacement(MangledName, Aliasee); 3134 return; 3135 } 3136 } 3137 3138 // The base destructor is equivalent to the base destructor of its 3139 // base class if there is exactly one non-virtual base class with a 3140 // non-trivial destructor, there are no fields with a non-trivial 3141 // destructor, and the body of the destructor is trivial. 3142 if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT && 3143 !CGM.TryEmitBaseDestructorAsAlias(DD)) 3144 return; 3145 3146 llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type); 3147 3148 if (CGType == StructorCodegen::COMDAT) { 3149 SmallString<256> Buffer; 3150 llvm::raw_svector_ostream Out(Buffer); 3151 if (DD) 3152 getMangleContext().mangleCXXDtorComdat(DD, Out); 3153 else 3154 getMangleContext().mangleCXXCtorComdat(CD, Out); 3155 llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str()); 3156 Fn->setComdat(C); 3157 } 3158 } 3159