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