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