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