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