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