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