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