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