1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides C++ code generation targeting the Itanium C++ ABI. The class 11 // in this file generates structures that follow the Itanium C++ ABI, which is 12 // documented at: 13 // http://www.codesourcery.com/public/cxx-abi/abi.html 14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html 15 // 16 // It also supports the closely-related ARM ABI, documented at: 17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "CGCXXABI.h" 22 #include "CGRecordLayout.h" 23 #include "CGVTables.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenModule.h" 26 #include "clang/AST/Mangle.h" 27 #include "clang/AST/Type.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/Value.h" 31 32 using namespace clang; 33 using namespace CodeGen; 34 35 namespace { 36 class ItaniumCXXABI : public CodeGen::CGCXXABI { 37 /// VTables - All the vtables which have been defined. 38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables; 39 40 protected: 41 bool UseARMMethodPtrABI; 42 bool UseARMGuardVarABI; 43 44 ItaniumMangleContext &getMangleContext() { 45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext()); 46 } 47 48 public: 49 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, 50 bool UseARMMethodPtrABI = false, 51 bool UseARMGuardVarABI = false) : 52 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI), 53 UseARMGuardVarABI(UseARMGuardVarABI) { } 54 55 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const { 56 // Structures with either a non-trivial destructor or a non-trivial 57 // copy constructor are always indirect. 58 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor(); 59 } 60 61 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const { 62 // Structures with either a non-trivial destructor or a non-trivial 63 // copy constructor are always indirect. 64 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) 65 return RAA_Indirect; 66 return RAA_Default; 67 } 68 69 bool isZeroInitializable(const MemberPointerType *MPT); 70 71 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 72 73 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 74 llvm::Value *&This, 75 llvm::Value *MemFnPtr, 76 const MemberPointerType *MPT); 77 78 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 79 llvm::Value *Base, 80 llvm::Value *MemPtr, 81 const MemberPointerType *MPT); 82 83 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 84 const CastExpr *E, 85 llvm::Value *Src); 86 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E, 87 llvm::Constant *Src); 88 89 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 90 91 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 92 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 93 CharUnits offset); 94 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT); 95 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD, 96 CharUnits ThisAdjustment); 97 98 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 99 llvm::Value *L, 100 llvm::Value *R, 101 const MemberPointerType *MPT, 102 bool Inequality); 103 104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 105 llvm::Value *Addr, 106 const MemberPointerType *MPT); 107 108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, 109 llvm::Value *ptr, 110 QualType type); 111 112 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF, 113 llvm::Value *This, 114 const CXXRecordDecl *ClassDecl, 115 const CXXRecordDecl *BaseClassDecl); 116 117 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 118 CXXCtorType T, 119 CanQualType &ResTy, 120 SmallVectorImpl<CanQualType> &ArgTys); 121 122 void EmitCXXConstructors(const CXXConstructorDecl *D); 123 124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 125 CXXDtorType T, 126 CanQualType &ResTy, 127 SmallVectorImpl<CanQualType> &ArgTys); 128 129 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor, 130 CXXDtorType DT) const { 131 // Itanium does not emit any destructor variant as an inline thunk. 132 // Delegating may occur as an optimization, but all variants are either 133 // emitted with external linkage or as linkonce if they are inline and used. 134 return false; 135 } 136 137 void EmitCXXDestructors(const CXXDestructorDecl *D); 138 139 void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, 140 FunctionArgList &Params); 141 142 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 143 144 unsigned addImplicitConstructorArgs(CodeGenFunction &CGF, 145 const CXXConstructorDecl *D, 146 CXXCtorType Type, bool ForVirtualBase, 147 bool Delegating, CallArgList &Args); 148 149 void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, 150 CXXDtorType Type, bool ForVirtualBase, 151 bool Delegating, llvm::Value *This); 152 153 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD); 154 155 llvm::Value *getVTableAddressPointInStructor( 156 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, 157 BaseSubobject Base, const CXXRecordDecl *NearestVBase, 158 bool &NeedsVirtualOffset); 159 160 llvm::Constant * 161 getVTableAddressPointForConstExpr(BaseSubobject Base, 162 const CXXRecordDecl *VTableClass); 163 164 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD, 165 CharUnits VPtrOffset); 166 167 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, 168 llvm::Value *This, llvm::Type *Ty); 169 170 void EmitVirtualDestructorCall(CodeGenFunction &CGF, 171 const CXXDestructorDecl *Dtor, 172 CXXDtorType DtorType, SourceLocation CallLoc, 173 llvm::Value *This); 174 175 void emitVirtualInheritanceTables(const CXXRecordDecl *RD); 176 177 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) { 178 // Allow inlining of thunks by emitting them with available_externally 179 // linkage together with vtables when needed. 180 if (ForVTable) 181 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 182 } 183 184 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This, 185 const ThisAdjustment &TA); 186 187 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 188 const ReturnAdjustment &RA); 189 190 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; } 191 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; } 192 193 CharUnits getArrayCookieSizeImpl(QualType elementType); 194 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 195 llvm::Value *NewPtr, 196 llvm::Value *NumElements, 197 const CXXNewExpr *expr, 198 QualType ElementType); 199 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, 200 llvm::Value *allocPtr, 201 CharUnits cookieSize); 202 203 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 204 llvm::GlobalVariable *DeclPtr, bool PerformInit); 205 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, 206 llvm::Constant *dtor, llvm::Constant *addr); 207 208 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD, 209 llvm::GlobalVariable *Var); 210 void EmitThreadLocalInitFuncs( 211 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls, 212 llvm::Function *InitFunc); 213 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF, 214 const DeclRefExpr *DRE); 215 216 bool NeedsVTTParameter(GlobalDecl GD); 217 }; 218 219 class ARMCXXABI : public ItaniumCXXABI { 220 public: 221 ARMCXXABI(CodeGen::CodeGenModule &CGM) : 222 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 223 /* UseARMGuardVarABI = */ true) {} 224 225 bool HasThisReturn(GlobalDecl GD) const { 226 return (isa<CXXConstructorDecl>(GD.getDecl()) || ( 227 isa<CXXDestructorDecl>(GD.getDecl()) && 228 GD.getDtorType() != Dtor_Deleting)); 229 } 230 231 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy); 232 233 CharUnits getArrayCookieSizeImpl(QualType elementType); 234 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 235 llvm::Value *NewPtr, 236 llvm::Value *NumElements, 237 const CXXNewExpr *expr, 238 QualType ElementType); 239 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr, 240 CharUnits cookieSize); 241 }; 242 } 243 244 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 245 switch (CGM.getTarget().getCXXABI().getKind()) { 246 // For IR-generation purposes, there's no significant difference 247 // between the ARM and iOS ABIs. 248 case TargetCXXABI::GenericARM: 249 case TargetCXXABI::iOS: 250 return new ARMCXXABI(CGM); 251 252 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't 253 // include the other 32-bit ARM oddities: constructor/destructor return values 254 // and array cookies. 255 case TargetCXXABI::GenericAArch64: 256 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 257 /* UseARMGuardVarABI = */ true); 258 259 case TargetCXXABI::GenericItanium: 260 if (CGM.getContext().getTargetInfo().getTriple().getArch() 261 == llvm::Triple::le32) { 262 // For PNaCl, use ARM-style method pointers so that PNaCl code 263 // does not assume anything about the alignment of function 264 // pointers. 265 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true, 266 /* UseARMGuardVarABI = */ false); 267 } 268 return new ItaniumCXXABI(CGM); 269 270 case TargetCXXABI::Microsoft: 271 llvm_unreachable("Microsoft ABI is not Itanium-based"); 272 } 273 llvm_unreachable("bad ABI kind"); 274 } 275 276 llvm::Type * 277 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 278 if (MPT->isMemberDataPointer()) 279 return CGM.PtrDiffTy; 280 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL); 281 } 282 283 /// In the Itanium and ARM ABIs, method pointers have the form: 284 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 285 /// 286 /// In the Itanium ABI: 287 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero 288 /// - the this-adjustment is (memptr.adj) 289 /// - the virtual offset is (memptr.ptr - 1) 290 /// 291 /// In the ARM ABI: 292 /// - method pointers are virtual if (memptr.adj & 1) is nonzero 293 /// - the this-adjustment is (memptr.adj >> 1) 294 /// - the virtual offset is (memptr.ptr) 295 /// ARM uses 'adj' for the virtual flag because Thumb functions 296 /// may be only single-byte aligned. 297 /// 298 /// If the member is virtual, the adjusted 'this' pointer points 299 /// to a vtable pointer from which the virtual offset is applied. 300 /// 301 /// If the member is non-virtual, memptr.ptr is the address of 302 /// the function to call. 303 llvm::Value * 304 ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 305 llvm::Value *&This, 306 llvm::Value *MemFnPtr, 307 const MemberPointerType *MPT) { 308 CGBuilderTy &Builder = CGF.Builder; 309 310 const FunctionProtoType *FPT = 311 MPT->getPointeeType()->getAs<FunctionProtoType>(); 312 const CXXRecordDecl *RD = 313 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 314 315 llvm::FunctionType *FTy = 316 CGM.getTypes().GetFunctionType( 317 CGM.getTypes().arrangeCXXMethodType(RD, FPT)); 318 319 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1); 320 321 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 322 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 323 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 324 325 // Extract memptr.adj, which is in the second field. 326 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 327 328 // Compute the true adjustment. 329 llvm::Value *Adj = RawAdj; 330 if (UseARMMethodPtrABI) 331 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 332 333 // Apply the adjustment and cast back to the original struct type 334 // for consistency. 335 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 336 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 337 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 338 339 // Load the function pointer. 340 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 341 342 // If the LSB in the function pointer is 1, the function pointer points to 343 // a virtual function. 344 llvm::Value *IsVirtual; 345 if (UseARMMethodPtrABI) 346 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 347 else 348 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 349 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 350 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 351 352 // In the virtual path, the adjustment left 'This' pointing to the 353 // vtable of the correct base subobject. The "function pointer" is an 354 // offset within the vtable (+1 for the virtual flag on non-ARM). 355 CGF.EmitBlock(FnVirtual); 356 357 // Cast the adjusted this to a pointer to vtable pointer and load. 358 llvm::Type *VTableTy = Builder.getInt8PtrTy(); 359 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo()); 360 VTable = Builder.CreateLoad(VTable, "memptr.vtable"); 361 362 // Apply the offset. 363 llvm::Value *VTableOffset = FnAsInt; 364 if (!UseARMMethodPtrABI) 365 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 366 VTable = Builder.CreateGEP(VTable, VTableOffset); 367 368 // Load the virtual function to call. 369 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 370 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 371 CGF.EmitBranch(FnEnd); 372 373 // In the non-virtual path, the function pointer is actually a 374 // function pointer. 375 CGF.EmitBlock(FnNonVirtual); 376 llvm::Value *NonVirtualFn = 377 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 378 379 // We're done. 380 CGF.EmitBlock(FnEnd); 381 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2); 382 Callee->addIncoming(VirtualFn, FnVirtual); 383 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 384 return Callee; 385 } 386 387 /// Compute an l-value by applying the given pointer-to-member to a 388 /// base object. 389 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 390 llvm::Value *Base, 391 llvm::Value *MemPtr, 392 const MemberPointerType *MPT) { 393 assert(MemPtr->getType() == CGM.PtrDiffTy); 394 395 CGBuilderTy &Builder = CGF.Builder; 396 397 unsigned AS = Base->getType()->getPointerAddressSpace(); 398 399 // Cast to char*. 400 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 401 402 // Apply the offset, which we assume is non-null. 403 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset"); 404 405 // Cast the address to the appropriate pointer type, adopting the 406 // address space of the base pointer. 407 llvm::Type *PType 408 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 409 return Builder.CreateBitCast(Addr, PType); 410 } 411 412 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer 413 /// conversion. 414 /// 415 /// Bitcast conversions are always a no-op under Itanium. 416 /// 417 /// Obligatory offset/adjustment diagram: 418 /// <-- offset --> <-- adjustment --> 419 /// |--------------------------|----------------------|--------------------| 420 /// ^Derived address point ^Base address point ^Member address point 421 /// 422 /// So when converting a base member pointer to a derived member pointer, 423 /// we add the offset to the adjustment because the address point has 424 /// decreased; and conversely, when converting a derived MP to a base MP 425 /// we subtract the offset from the adjustment because the address point 426 /// has increased. 427 /// 428 /// The standard forbids (at compile time) conversion to and from 429 /// virtual bases, which is why we don't have to consider them here. 430 /// 431 /// The standard forbids (at run time) casting a derived MP to a base 432 /// MP when the derived MP does not point to a member of the base. 433 /// This is why -1 is a reasonable choice for null data member 434 /// pointers. 435 llvm::Value * 436 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 437 const CastExpr *E, 438 llvm::Value *src) { 439 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 440 E->getCastKind() == CK_BaseToDerivedMemberPointer || 441 E->getCastKind() == CK_ReinterpretMemberPointer); 442 443 // Under Itanium, reinterprets don't require any additional processing. 444 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 445 446 // Use constant emission if we can. 447 if (isa<llvm::Constant>(src)) 448 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src)); 449 450 llvm::Constant *adj = getMemberPointerAdjustment(E); 451 if (!adj) return src; 452 453 CGBuilderTy &Builder = CGF.Builder; 454 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 455 456 const MemberPointerType *destTy = 457 E->getType()->castAs<MemberPointerType>(); 458 459 // For member data pointers, this is just a matter of adding the 460 // offset if the source is non-null. 461 if (destTy->isMemberDataPointer()) { 462 llvm::Value *dst; 463 if (isDerivedToBase) 464 dst = Builder.CreateNSWSub(src, adj, "adj"); 465 else 466 dst = Builder.CreateNSWAdd(src, adj, "adj"); 467 468 // Null check. 469 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType()); 470 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull"); 471 return Builder.CreateSelect(isNull, src, dst); 472 } 473 474 // The this-adjustment is left-shifted by 1 on ARM. 475 if (UseARMMethodPtrABI) { 476 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 477 offset <<= 1; 478 adj = llvm::ConstantInt::get(adj->getType(), offset); 479 } 480 481 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj"); 482 llvm::Value *dstAdj; 483 if (isDerivedToBase) 484 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj"); 485 else 486 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj"); 487 488 return Builder.CreateInsertValue(src, dstAdj, 1); 489 } 490 491 llvm::Constant * 492 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E, 493 llvm::Constant *src) { 494 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 495 E->getCastKind() == CK_BaseToDerivedMemberPointer || 496 E->getCastKind() == CK_ReinterpretMemberPointer); 497 498 // Under Itanium, reinterprets don't require any additional processing. 499 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src; 500 501 // If the adjustment is trivial, we don't need to do anything. 502 llvm::Constant *adj = getMemberPointerAdjustment(E); 503 if (!adj) return src; 504 505 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer); 506 507 const MemberPointerType *destTy = 508 E->getType()->castAs<MemberPointerType>(); 509 510 // For member data pointers, this is just a matter of adding the 511 // offset if the source is non-null. 512 if (destTy->isMemberDataPointer()) { 513 // null maps to null. 514 if (src->isAllOnesValue()) return src; 515 516 if (isDerivedToBase) 517 return llvm::ConstantExpr::getNSWSub(src, adj); 518 else 519 return llvm::ConstantExpr::getNSWAdd(src, adj); 520 } 521 522 // The this-adjustment is left-shifted by 1 on ARM. 523 if (UseARMMethodPtrABI) { 524 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue(); 525 offset <<= 1; 526 adj = llvm::ConstantInt::get(adj->getType(), offset); 527 } 528 529 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1); 530 llvm::Constant *dstAdj; 531 if (isDerivedToBase) 532 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj); 533 else 534 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj); 535 536 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1); 537 } 538 539 llvm::Constant * 540 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 541 // Itanium C++ ABI 2.3: 542 // A NULL pointer is represented as -1. 543 if (MPT->isMemberDataPointer()) 544 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true); 545 546 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0); 547 llvm::Constant *Values[2] = { Zero, Zero }; 548 return llvm::ConstantStruct::getAnon(Values); 549 } 550 551 llvm::Constant * 552 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 553 CharUnits offset) { 554 // Itanium C++ ABI 2.3: 555 // A pointer to data member is an offset from the base address of 556 // the class object containing it, represented as a ptrdiff_t 557 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()); 558 } 559 560 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 561 return BuildMemberPointer(MD, CharUnits::Zero()); 562 } 563 564 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD, 565 CharUnits ThisAdjustment) { 566 assert(MD->isInstance() && "Member function must not be static!"); 567 MD = MD->getCanonicalDecl(); 568 569 CodeGenTypes &Types = CGM.getTypes(); 570 571 // Get the function pointer (or index if this is a virtual function). 572 llvm::Constant *MemPtr[2]; 573 if (MD->isVirtual()) { 574 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD); 575 576 const ASTContext &Context = getContext(); 577 CharUnits PointerWidth = 578 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); 579 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 580 581 if (UseARMMethodPtrABI) { 582 // ARM C++ ABI 3.2.1: 583 // This ABI specifies that adj contains twice the this 584 // adjustment, plus 1 if the member function is virtual. The 585 // least significant bit of adj then makes exactly the same 586 // discrimination as the least significant bit of ptr does for 587 // Itanium. 588 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset); 589 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 590 2 * ThisAdjustment.getQuantity() + 1); 591 } else { 592 // Itanium C++ ABI 2.3: 593 // For a virtual function, [the pointer field] is 1 plus the 594 // virtual table offset (in bytes) of the function, 595 // represented as a ptrdiff_t. 596 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1); 597 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 598 ThisAdjustment.getQuantity()); 599 } 600 } else { 601 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 602 llvm::Type *Ty; 603 // Check whether the function has a computable LLVM signature. 604 if (Types.isFuncTypeConvertible(FPT)) { 605 // The function has a computable LLVM signature; use the correct type. 606 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD)); 607 } else { 608 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 609 // function type is incomplete. 610 Ty = CGM.PtrDiffTy; 611 } 612 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 613 614 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy); 615 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy, 616 (UseARMMethodPtrABI ? 2 : 1) * 617 ThisAdjustment.getQuantity()); 618 } 619 620 return llvm::ConstantStruct::getAnon(MemPtr); 621 } 622 623 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP, 624 QualType MPType) { 625 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>(); 626 const ValueDecl *MPD = MP.getMemberPointerDecl(); 627 if (!MPD) 628 return EmitNullMemberPointer(MPT); 629 630 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP); 631 632 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) 633 return BuildMemberPointer(MD, ThisAdjustment); 634 635 CharUnits FieldOffset = 636 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD)); 637 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset); 638 } 639 640 /// The comparison algorithm is pretty easy: the member pointers are 641 /// the same if they're either bitwise identical *or* both null. 642 /// 643 /// ARM is different here only because null-ness is more complicated. 644 llvm::Value * 645 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 646 llvm::Value *L, 647 llvm::Value *R, 648 const MemberPointerType *MPT, 649 bool Inequality) { 650 CGBuilderTy &Builder = CGF.Builder; 651 652 llvm::ICmpInst::Predicate Eq; 653 llvm::Instruction::BinaryOps And, Or; 654 if (Inequality) { 655 Eq = llvm::ICmpInst::ICMP_NE; 656 And = llvm::Instruction::Or; 657 Or = llvm::Instruction::And; 658 } else { 659 Eq = llvm::ICmpInst::ICMP_EQ; 660 And = llvm::Instruction::And; 661 Or = llvm::Instruction::Or; 662 } 663 664 // Member data pointers are easy because there's a unique null 665 // value, so it just comes down to bitwise equality. 666 if (MPT->isMemberDataPointer()) 667 return Builder.CreateICmp(Eq, L, R); 668 669 // For member function pointers, the tautologies are more complex. 670 // The Itanium tautology is: 671 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 672 // The ARM tautology is: 673 // (L == R) <==> (L.ptr == R.ptr && 674 // (L.adj == R.adj || 675 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 676 // The inequality tautologies have exactly the same structure, except 677 // applying De Morgan's laws. 678 679 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 680 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 681 682 // This condition tests whether L.ptr == R.ptr. This must always be 683 // true for equality to hold. 684 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 685 686 // This condition, together with the assumption that L.ptr == R.ptr, 687 // tests whether the pointers are both null. ARM imposes an extra 688 // condition. 689 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 690 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 691 692 // This condition tests whether L.adj == R.adj. If this isn't 693 // true, the pointers are unequal unless they're both null. 694 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 695 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 696 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 697 698 // Null member function pointers on ARM clear the low bit of Adj, 699 // so the zero condition has to check that neither low bit is set. 700 if (UseARMMethodPtrABI) { 701 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 702 703 // Compute (l.adj | r.adj) & 1 and test it against zero. 704 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 705 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 706 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 707 "cmp.or.adj"); 708 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 709 } 710 711 // Tie together all our conditions. 712 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 713 Result = Builder.CreateBinOp(And, PtrEq, Result, 714 Inequality ? "memptr.ne" : "memptr.eq"); 715 return Result; 716 } 717 718 llvm::Value * 719 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 720 llvm::Value *MemPtr, 721 const MemberPointerType *MPT) { 722 CGBuilderTy &Builder = CGF.Builder; 723 724 /// For member data pointers, this is just a check against -1. 725 if (MPT->isMemberDataPointer()) { 726 assert(MemPtr->getType() == CGM.PtrDiffTy); 727 llvm::Value *NegativeOne = 728 llvm::Constant::getAllOnesValue(MemPtr->getType()); 729 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 730 } 731 732 // In Itanium, a member function pointer is not null if 'ptr' is not null. 733 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 734 735 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 736 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 737 738 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 739 // (the virtual bit) is set. 740 if (UseARMMethodPtrABI) { 741 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 742 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 743 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 744 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 745 "memptr.isvirtual"); 746 Result = Builder.CreateOr(Result, IsVirtual); 747 } 748 749 return Result; 750 } 751 752 /// The Itanium ABI requires non-zero initialization only for data 753 /// member pointers, for which '0' is a valid offset. 754 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 755 return MPT->getPointeeType()->isFunctionType(); 756 } 757 758 /// The Itanium ABI always places an offset to the complete object 759 /// at entry -2 in the vtable. 760 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF, 761 llvm::Value *ptr, 762 QualType type) { 763 // Grab the vtable pointer as an intptr_t*. 764 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo()); 765 766 // Track back to entry -2 and pull out the offset there. 767 llvm::Value *offsetPtr = 768 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr"); 769 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr); 770 offset->setAlignment(CGF.PointerAlignInBytes); 771 772 // Apply the offset. 773 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 774 return CGF.Builder.CreateInBoundsGEP(ptr, offset); 775 } 776 777 llvm::Value * 778 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF, 779 llvm::Value *This, 780 const CXXRecordDecl *ClassDecl, 781 const CXXRecordDecl *BaseClassDecl) { 782 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy); 783 CharUnits VBaseOffsetOffset = 784 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl, 785 BaseClassDecl); 786 787 llvm::Value *VBaseOffsetPtr = 788 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 789 "vbase.offset.ptr"); 790 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr, 791 CGM.PtrDiffTy->getPointerTo()); 792 793 llvm::Value *VBaseOffset = 794 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 795 796 return VBaseOffset; 797 } 798 799 /// The generic ABI passes 'this', plus a VTT if it's initializing a 800 /// base subobject. 801 void 802 ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 803 CXXCtorType Type, CanQualType &ResTy, 804 SmallVectorImpl<CanQualType> &ArgTys) { 805 ASTContext &Context = getContext(); 806 807 // All parameters are already in place except VTT, which goes after 'this'. 808 // These are Clang types, so we don't need to worry about sret yet. 809 810 // Check if we need to add a VTT parameter (which has type void **). 811 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0) 812 ArgTys.insert(ArgTys.begin() + 1, 813 Context.getPointerType(Context.VoidPtrTy)); 814 } 815 816 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) { 817 // Just make sure we're in sync with TargetCXXABI. 818 assert(CGM.getTarget().getCXXABI().hasConstructorVariants()); 819 820 // The constructor used for constructing this as a base class; 821 // ignores virtual bases. 822 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base)); 823 824 // The constructor used for constructing this as a complete class; 825 // constucts the virtual bases, then calls the base constructor. 826 if (!D->getParent()->isAbstract()) { 827 // We don't need to emit the complete ctor if the class is abstract. 828 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete)); 829 } 830 } 831 832 /// The generic ABI passes 'this', plus a VTT if it's destroying a 833 /// base subobject. 834 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 835 CXXDtorType Type, 836 CanQualType &ResTy, 837 SmallVectorImpl<CanQualType> &ArgTys) { 838 ASTContext &Context = getContext(); 839 840 // 'this' parameter is already there, as well as 'this' return if 841 // HasThisReturn(GlobalDecl(Dtor, Type)) is true 842 843 // Check if we need to add a VTT parameter (which has type void **). 844 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0) 845 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 846 } 847 848 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) { 849 // The destructor used for destructing this as a base class; ignores 850 // virtual bases. 851 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base)); 852 853 // The destructor used for destructing this as a most-derived class; 854 // call the base destructor and then destructs any virtual bases. 855 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete)); 856 857 // The destructor in a virtual table is always a 'deleting' 858 // destructor, which calls the complete destructor and then uses the 859 // appropriate operator delete. 860 if (D->isVirtual()) 861 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 862 } 863 864 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF, 865 QualType &ResTy, 866 FunctionArgList &Params) { 867 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 868 assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)); 869 870 // Check if we need a VTT parameter as well. 871 if (NeedsVTTParameter(CGF.CurGD)) { 872 ASTContext &Context = getContext(); 873 874 // FIXME: avoid the fake decl 875 QualType T = Context.getPointerType(Context.VoidPtrTy); 876 ImplicitParamDecl *VTTDecl 877 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(), 878 &Context.Idents.get("vtt"), T); 879 Params.insert(Params.begin() + 1, VTTDecl); 880 getStructorImplicitParamDecl(CGF) = VTTDecl; 881 } 882 } 883 884 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 885 /// Initialize the 'this' slot. 886 EmitThisParam(CGF); 887 888 /// Initialize the 'vtt' slot if needed. 889 if (getStructorImplicitParamDecl(CGF)) { 890 getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad( 891 CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt"); 892 } 893 894 /// If this is a function that the ABI specifies returns 'this', initialize 895 /// the return slot to 'this' at the start of the function. 896 /// 897 /// Unlike the setting of return types, this is done within the ABI 898 /// implementation instead of by clients of CGCXXABI because: 899 /// 1) getThisValue is currently protected 900 /// 2) in theory, an ABI could implement 'this' returns some other way; 901 /// HasThisReturn only specifies a contract, not the implementation 902 if (HasThisReturn(CGF.CurGD)) 903 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue); 904 } 905 906 unsigned ItaniumCXXABI::addImplicitConstructorArgs( 907 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, 908 bool ForVirtualBase, bool Delegating, CallArgList &Args) { 909 if (!NeedsVTTParameter(GlobalDecl(D, Type))) 910 return 0; 911 912 // Insert the implicit 'vtt' argument as the second argument. 913 llvm::Value *VTT = 914 CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating); 915 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 916 Args.insert(Args.begin() + 1, 917 CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false)); 918 return 1; // Added one arg. 919 } 920 921 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF, 922 const CXXDestructorDecl *DD, 923 CXXDtorType Type, bool ForVirtualBase, 924 bool Delegating, llvm::Value *This) { 925 GlobalDecl GD(DD, Type); 926 llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating); 927 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy); 928 929 llvm::Value *Callee = 0; 930 if (getContext().getLangOpts().AppleKext) 931 Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent()); 932 933 if (!Callee) 934 Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 935 936 if (DD->isVirtual()) 937 This = adjustThisArgumentForVirtualCall(CGF, GD, This); 938 939 // FIXME: Provide a source location here. 940 CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This, 941 VTT, VTTTy, 0, 0); 942 } 943 944 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT, 945 const CXXRecordDecl *RD) { 946 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits()); 947 if (VTable->hasInitializer()) 948 return; 949 950 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 951 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD); 952 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD); 953 954 // Create and set the initializer. 955 llvm::Constant *Init = CGVT.CreateVTableInitializer( 956 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(), 957 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks()); 958 VTable->setInitializer(Init); 959 960 // Set the correct linkage. 961 VTable->setLinkage(Linkage); 962 963 // Set the right visibility. 964 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable); 965 966 // If this is the magic class __cxxabiv1::__fundamental_type_info, 967 // we will emit the typeinfo for the fundamental types. This is the 968 // same behaviour as GCC. 969 const DeclContext *DC = RD->getDeclContext(); 970 if (RD->getIdentifier() && 971 RD->getIdentifier()->isStr("__fundamental_type_info") && 972 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() && 973 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") && 974 DC->getParent()->isTranslationUnit()) 975 CGM.EmitFundamentalRTTIDescriptors(); 976 } 977 978 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor( 979 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base, 980 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) { 981 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD); 982 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase); 983 984 llvm::Value *VTableAddressPoint; 985 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) { 986 // Get the secondary vpointer index. 987 uint64_t VirtualPointerIndex = 988 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 989 990 /// Load the VTT. 991 llvm::Value *VTT = CGF.LoadCXXVTT(); 992 if (VirtualPointerIndex) 993 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 994 995 // And load the address point from the VTT. 996 VTableAddressPoint = CGF.Builder.CreateLoad(VTT); 997 } else { 998 llvm::Constant *VTable = 999 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits()); 1000 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1001 .getVTableLayout(VTableClass) 1002 .getAddressPoint(Base); 1003 VTableAddressPoint = 1004 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1005 } 1006 1007 return VTableAddressPoint; 1008 } 1009 1010 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr( 1011 BaseSubobject Base, const CXXRecordDecl *VTableClass) { 1012 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits()); 1013 1014 // Find the appropriate vtable within the vtable group. 1015 uint64_t AddressPoint = CGM.getItaniumVTableContext() 1016 .getVTableLayout(VTableClass) 1017 .getAddressPoint(Base); 1018 llvm::Value *Indices[] = { 1019 llvm::ConstantInt::get(CGM.Int64Ty, 0), 1020 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint) 1021 }; 1022 1023 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices); 1024 } 1025 1026 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD, 1027 CharUnits VPtrOffset) { 1028 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets"); 1029 1030 llvm::GlobalVariable *&VTable = VTables[RD]; 1031 if (VTable) 1032 return VTable; 1033 1034 // Queue up this v-table for possible deferred emission. 1035 CGM.addDeferredVTable(RD); 1036 1037 SmallString<256> OutName; 1038 llvm::raw_svector_ostream Out(OutName); 1039 getMangleContext().mangleCXXVTable(RD, Out); 1040 Out.flush(); 1041 StringRef Name = OutName.str(); 1042 1043 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext(); 1044 llvm::ArrayType *ArrayType = llvm::ArrayType::get( 1045 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents()); 1046 1047 VTable = CGM.CreateOrReplaceCXXRuntimeVariable( 1048 Name, ArrayType, llvm::GlobalValue::ExternalLinkage); 1049 VTable->setUnnamedAddr(true); 1050 return VTable; 1051 } 1052 1053 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF, 1054 GlobalDecl GD, 1055 llvm::Value *This, 1056 llvm::Type *Ty) { 1057 GD = GD.getCanonicalDecl(); 1058 Ty = Ty->getPointerTo()->getPointerTo(); 1059 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty); 1060 1061 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 1062 llvm::Value *VFuncPtr = 1063 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 1064 return CGF.Builder.CreateLoad(VFuncPtr); 1065 } 1066 1067 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF, 1068 const CXXDestructorDecl *Dtor, 1069 CXXDtorType DtorType, 1070 SourceLocation CallLoc, 1071 llvm::Value *This) { 1072 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete); 1073 1074 const CGFunctionInfo *FInfo 1075 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType); 1076 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo); 1077 llvm::Value *Callee = 1078 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty); 1079 1080 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This, 1081 /*ImplicitParam=*/0, QualType(), 0, 0); 1082 } 1083 1084 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) { 1085 CodeGenVTables &VTables = CGM.getVTables(); 1086 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD); 1087 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD); 1088 } 1089 1090 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF, 1091 llvm::Value *Ptr, 1092 int64_t NonVirtualAdjustment, 1093 int64_t VirtualAdjustment, 1094 bool IsReturnAdjustment) { 1095 if (!NonVirtualAdjustment && !VirtualAdjustment) 1096 return Ptr; 1097 1098 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 1099 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy); 1100 1101 if (NonVirtualAdjustment && !IsReturnAdjustment) { 1102 // Perform the non-virtual adjustment for a base-to-derived cast. 1103 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1104 } 1105 1106 if (VirtualAdjustment) { 1107 llvm::Type *PtrDiffTy = 1108 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 1109 1110 // Perform the virtual adjustment. 1111 llvm::Value *VTablePtrPtr = 1112 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo()); 1113 1114 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr); 1115 1116 llvm::Value *OffsetPtr = 1117 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 1118 1119 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo()); 1120 1121 // Load the adjustment offset from the vtable. 1122 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr); 1123 1124 // Adjust our pointer. 1125 V = CGF.Builder.CreateInBoundsGEP(V, Offset); 1126 } 1127 1128 if (NonVirtualAdjustment && IsReturnAdjustment) { 1129 // Perform the non-virtual adjustment for a derived-to-base cast. 1130 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment); 1131 } 1132 1133 // Cast back to the original type. 1134 return CGF.Builder.CreateBitCast(V, Ptr->getType()); 1135 } 1136 1137 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF, 1138 llvm::Value *This, 1139 const ThisAdjustment &TA) { 1140 return performTypeAdjustment(CGF, This, TA.NonVirtual, 1141 TA.Virtual.Itanium.VCallOffsetOffset, 1142 /*IsReturnAdjustment=*/false); 1143 } 1144 1145 llvm::Value * 1146 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret, 1147 const ReturnAdjustment &RA) { 1148 return performTypeAdjustment(CGF, Ret, RA.NonVirtual, 1149 RA.Virtual.Itanium.VBaseOffsetOffset, 1150 /*IsReturnAdjustment=*/true); 1151 } 1152 1153 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 1154 RValue RV, QualType ResultType) { 1155 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 1156 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 1157 1158 // Destructor thunks in the ARM ABI have indeterminate results. 1159 llvm::Type *T = 1160 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 1161 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 1162 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 1163 } 1164 1165 /************************** Array allocation cookies **************************/ 1166 1167 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1168 // The array cookie is a size_t; pad that up to the element alignment. 1169 // The cookie is actually right-justified in that space. 1170 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes), 1171 CGM.getContext().getTypeAlignInChars(elementType)); 1172 } 1173 1174 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1175 llvm::Value *NewPtr, 1176 llvm::Value *NumElements, 1177 const CXXNewExpr *expr, 1178 QualType ElementType) { 1179 assert(requiresArrayCookie(expr)); 1180 1181 unsigned AS = NewPtr->getType()->getPointerAddressSpace(); 1182 1183 ASTContext &Ctx = getContext(); 1184 QualType SizeTy = Ctx.getSizeType(); 1185 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 1186 1187 // The size of the cookie. 1188 CharUnits CookieSize = 1189 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 1190 assert(CookieSize == getArrayCookieSizeImpl(ElementType)); 1191 1192 // Compute an offset to the cookie. 1193 llvm::Value *CookiePtr = NewPtr; 1194 CharUnits CookieOffset = CookieSize - SizeSize; 1195 if (!CookieOffset.isZero()) 1196 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 1197 CookieOffset.getQuantity()); 1198 1199 // Write the number of elements into the appropriate slot. 1200 llvm::Value *NumElementsPtr 1201 = CGF.Builder.CreateBitCast(CookiePtr, 1202 CGF.ConvertType(SizeTy)->getPointerTo(AS)); 1203 CGF.Builder.CreateStore(NumElements, NumElementsPtr); 1204 1205 // Finally, compute a pointer to the actual data buffer by skipping 1206 // over the cookie completely. 1207 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 1208 CookieSize.getQuantity()); 1209 } 1210 1211 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1212 llvm::Value *allocPtr, 1213 CharUnits cookieSize) { 1214 // The element size is right-justified in the cookie. 1215 llvm::Value *numElementsPtr = allocPtr; 1216 CharUnits numElementsOffset = 1217 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes); 1218 if (!numElementsOffset.isZero()) 1219 numElementsPtr = 1220 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr, 1221 numElementsOffset.getQuantity()); 1222 1223 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1224 numElementsPtr = 1225 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1226 return CGF.Builder.CreateLoad(numElementsPtr); 1227 } 1228 1229 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) { 1230 // ARM says that the cookie is always: 1231 // struct array_cookie { 1232 // std::size_t element_size; // element_size != 0 1233 // std::size_t element_count; 1234 // }; 1235 // But the base ABI doesn't give anything an alignment greater than 1236 // 8, so we can dismiss this as typical ABI-author blindness to 1237 // actual language complexity and round up to the element alignment. 1238 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes), 1239 CGM.getContext().getTypeAlignInChars(elementType)); 1240 } 1241 1242 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 1243 llvm::Value *newPtr, 1244 llvm::Value *numElements, 1245 const CXXNewExpr *expr, 1246 QualType elementType) { 1247 assert(requiresArrayCookie(expr)); 1248 1249 // NewPtr is a char*, but we generalize to arbitrary addrspaces. 1250 unsigned AS = newPtr->getType()->getPointerAddressSpace(); 1251 1252 // The cookie is always at the start of the buffer. 1253 llvm::Value *cookie = newPtr; 1254 1255 // The first element is the element size. 1256 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS)); 1257 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy, 1258 getContext().getTypeSizeInChars(elementType).getQuantity()); 1259 CGF.Builder.CreateStore(elementSize, cookie); 1260 1261 // The second element is the element count. 1262 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1); 1263 CGF.Builder.CreateStore(numElements, cookie); 1264 1265 // Finally, compute a pointer to the actual data buffer by skipping 1266 // over the cookie completely. 1267 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType); 1268 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr, 1269 cookieSize.getQuantity()); 1270 } 1271 1272 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF, 1273 llvm::Value *allocPtr, 1274 CharUnits cookieSize) { 1275 // The number of elements is at offset sizeof(size_t) relative to 1276 // the allocated pointer. 1277 llvm::Value *numElementsPtr 1278 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes); 1279 1280 unsigned AS = allocPtr->getType()->getPointerAddressSpace(); 1281 numElementsPtr = 1282 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS)); 1283 return CGF.Builder.CreateLoad(numElementsPtr); 1284 } 1285 1286 /*********************** Static local initialization **************************/ 1287 1288 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1289 llvm::PointerType *GuardPtrTy) { 1290 // int __cxa_guard_acquire(__guard *guard_object); 1291 llvm::FunctionType *FTy = 1292 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1293 GuardPtrTy, /*isVarArg=*/false); 1294 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire", 1295 llvm::AttributeSet::get(CGM.getLLVMContext(), 1296 llvm::AttributeSet::FunctionIndex, 1297 llvm::Attribute::NoUnwind)); 1298 } 1299 1300 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1301 llvm::PointerType *GuardPtrTy) { 1302 // void __cxa_guard_release(__guard *guard_object); 1303 llvm::FunctionType *FTy = 1304 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1305 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release", 1306 llvm::AttributeSet::get(CGM.getLLVMContext(), 1307 llvm::AttributeSet::FunctionIndex, 1308 llvm::Attribute::NoUnwind)); 1309 } 1310 1311 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1312 llvm::PointerType *GuardPtrTy) { 1313 // void __cxa_guard_abort(__guard *guard_object); 1314 llvm::FunctionType *FTy = 1315 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false); 1316 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort", 1317 llvm::AttributeSet::get(CGM.getLLVMContext(), 1318 llvm::AttributeSet::FunctionIndex, 1319 llvm::Attribute::NoUnwind)); 1320 } 1321 1322 namespace { 1323 struct CallGuardAbort : EHScopeStack::Cleanup { 1324 llvm::GlobalVariable *Guard; 1325 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1326 1327 void Emit(CodeGenFunction &CGF, Flags flags) { 1328 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()), 1329 Guard); 1330 } 1331 }; 1332 } 1333 1334 /// The ARM code here follows the Itanium code closely enough that we 1335 /// just special-case it at particular places. 1336 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1337 const VarDecl &D, 1338 llvm::GlobalVariable *var, 1339 bool shouldPerformInit) { 1340 CGBuilderTy &Builder = CGF.Builder; 1341 1342 // We only need to use thread-safe statics for local non-TLS variables; 1343 // global initialization is always single-threaded. 1344 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics && 1345 D.isLocalVarDecl() && !D.getTLSKind(); 1346 1347 // If we have a global variable with internal linkage and thread-safe statics 1348 // are disabled, we can just let the guard variable be of type i8. 1349 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage(); 1350 1351 llvm::IntegerType *guardTy; 1352 if (useInt8GuardVariable) { 1353 guardTy = CGF.Int8Ty; 1354 } else { 1355 // Guard variables are 64 bits in the generic ABI and size width on ARM 1356 // (i.e. 32-bit on AArch32, 64-bit on AArch64). 1357 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty); 1358 } 1359 llvm::PointerType *guardPtrTy = guardTy->getPointerTo(); 1360 1361 // Create the guard variable if we don't already have it (as we 1362 // might if we're double-emitting this function body). 1363 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D); 1364 if (!guard) { 1365 // Mangle the name for the guard. 1366 SmallString<256> guardName; 1367 { 1368 llvm::raw_svector_ostream out(guardName); 1369 getMangleContext().mangleStaticGuardVariable(&D, out); 1370 out.flush(); 1371 } 1372 1373 // Create the guard variable with a zero-initializer. 1374 // Just absorb linkage and visibility from the guarded variable. 1375 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy, 1376 false, var->getLinkage(), 1377 llvm::ConstantInt::get(guardTy, 0), 1378 guardName.str()); 1379 guard->setVisibility(var->getVisibility()); 1380 // If the variable is thread-local, so is its guard variable. 1381 guard->setThreadLocalMode(var->getThreadLocalMode()); 1382 1383 CGM.setStaticLocalDeclGuardAddress(&D, guard); 1384 } 1385 1386 // Test whether the variable has completed initialization. 1387 llvm::Value *isInitialized; 1388 1389 // ARM C++ ABI 3.2.3.1: 1390 // To support the potential use of initialization guard variables 1391 // as semaphores that are the target of ARM SWP and LDREX/STREX 1392 // synchronizing instructions we define a static initialization 1393 // guard variable to be a 4-byte aligned, 4- byte word with the 1394 // following inline access protocol. 1395 // #define INITIALIZED 1 1396 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1397 // if (__cxa_guard_acquire(&obj_guard)) 1398 // ... 1399 // } 1400 if (UseARMGuardVarABI && !useInt8GuardVariable) { 1401 llvm::Value *V = Builder.CreateLoad(guard); 1402 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1); 1403 V = Builder.CreateAnd(V, Test1); 1404 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1405 1406 // Itanium C++ ABI 3.3.2: 1407 // The following is pseudo-code showing how these functions can be used: 1408 // if (obj_guard.first_byte == 0) { 1409 // if ( __cxa_guard_acquire (&obj_guard) ) { 1410 // try { 1411 // ... initialize the object ...; 1412 // } catch (...) { 1413 // __cxa_guard_abort (&obj_guard); 1414 // throw; 1415 // } 1416 // ... queue object destructor with __cxa_atexit() ...; 1417 // __cxa_guard_release (&obj_guard); 1418 // } 1419 // } 1420 } else { 1421 // Load the first byte of the guard variable. 1422 llvm::LoadInst *LI = 1423 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy)); 1424 LI->setAlignment(1); 1425 1426 // Itanium ABI: 1427 // An implementation supporting thread-safety on multiprocessor 1428 // systems must also guarantee that references to the initialized 1429 // object do not occur before the load of the initialization flag. 1430 // 1431 // In LLVM, we do this by marking the load Acquire. 1432 if (threadsafe) 1433 LI->setAtomic(llvm::Acquire); 1434 1435 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized"); 1436 } 1437 1438 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1439 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1440 1441 // Check if the first byte of the guard variable is zero. 1442 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock); 1443 1444 CGF.EmitBlock(InitCheckBlock); 1445 1446 // Variables used when coping with thread-safe statics and exceptions. 1447 if (threadsafe) { 1448 // Call __cxa_guard_acquire. 1449 llvm::Value *V 1450 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard); 1451 1452 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1453 1454 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1455 InitBlock, EndBlock); 1456 1457 // Call __cxa_guard_abort along the exceptional edge. 1458 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard); 1459 1460 CGF.EmitBlock(InitBlock); 1461 } 1462 1463 // Emit the initializer and add a global destructor if appropriate. 1464 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit); 1465 1466 if (threadsafe) { 1467 // Pop the guard-abort cleanup if we pushed one. 1468 CGF.PopCleanupBlock(); 1469 1470 // Call __cxa_guard_release. This cannot throw. 1471 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard); 1472 } else { 1473 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard); 1474 } 1475 1476 CGF.EmitBlock(EndBlock); 1477 } 1478 1479 /// Register a global destructor using __cxa_atexit. 1480 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF, 1481 llvm::Constant *dtor, 1482 llvm::Constant *addr, 1483 bool TLS) { 1484 const char *Name = "__cxa_atexit"; 1485 if (TLS) { 1486 const llvm::Triple &T = CGF.getTarget().getTriple(); 1487 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit"; 1488 } 1489 1490 // We're assuming that the destructor function is something we can 1491 // reasonably call with the default CC. Go ahead and cast it to the 1492 // right prototype. 1493 llvm::Type *dtorTy = 1494 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo(); 1495 1496 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d); 1497 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy }; 1498 llvm::FunctionType *atexitTy = 1499 llvm::FunctionType::get(CGF.IntTy, paramTys, false); 1500 1501 // Fetch the actual function. 1502 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name); 1503 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit)) 1504 fn->setDoesNotThrow(); 1505 1506 // Create a variable that binds the atexit to this shared object. 1507 llvm::Constant *handle = 1508 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle"); 1509 1510 llvm::Value *args[] = { 1511 llvm::ConstantExpr::getBitCast(dtor, dtorTy), 1512 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy), 1513 handle 1514 }; 1515 CGF.EmitNounwindRuntimeCall(atexit, args); 1516 } 1517 1518 /// Register a global destructor as best as we know how. 1519 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, 1520 const VarDecl &D, 1521 llvm::Constant *dtor, 1522 llvm::Constant *addr) { 1523 // Use __cxa_atexit if available. 1524 if (CGM.getCodeGenOpts().CXAAtExit) 1525 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind()); 1526 1527 if (D.getTLSKind()) 1528 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction"); 1529 1530 // In Apple kexts, we want to add a global destructor entry. 1531 // FIXME: shouldn't this be guarded by some variable? 1532 if (CGM.getLangOpts().AppleKext) { 1533 // Generate a global destructor entry. 1534 return CGM.AddCXXDtorEntry(dtor, addr); 1535 } 1536 1537 CGF.registerGlobalDtorWithAtExit(D, dtor, addr); 1538 } 1539 1540 /// Get the appropriate linkage for the wrapper function. This is essentially 1541 /// the weak form of the variable's linkage; every translation unit which wneeds 1542 /// the wrapper emits a copy, and we want the linker to merge them. 1543 static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage( 1544 llvm::GlobalValue::LinkageTypes VarLinkage) { 1545 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage)) 1546 return llvm::GlobalValue::LinkerPrivateWeakLinkage; 1547 // For internal linkage variables, we don't need an external or weak wrapper. 1548 if (llvm::GlobalValue::isLocalLinkage(VarLinkage)) 1549 return VarLinkage; 1550 return llvm::GlobalValue::WeakODRLinkage; 1551 } 1552 1553 llvm::Function * 1554 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD, 1555 llvm::GlobalVariable *Var) { 1556 // Mangle the name for the thread_local wrapper function. 1557 SmallString<256> WrapperName; 1558 { 1559 llvm::raw_svector_ostream Out(WrapperName); 1560 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out); 1561 Out.flush(); 1562 } 1563 1564 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName)) 1565 return cast<llvm::Function>(V); 1566 1567 llvm::Type *RetTy = Var->getType(); 1568 if (VD->getType()->isReferenceType()) 1569 RetTy = RetTy->getPointerElementType(); 1570 1571 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false); 1572 llvm::Function *Wrapper = llvm::Function::Create( 1573 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(), 1574 &CGM.getModule()); 1575 // Always resolve references to the wrapper at link time. 1576 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility); 1577 return Wrapper; 1578 } 1579 1580 void ItaniumCXXABI::EmitThreadLocalInitFuncs( 1581 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls, 1582 llvm::Function *InitFunc) { 1583 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 1584 const VarDecl *VD = Decls[I].first; 1585 llvm::GlobalVariable *Var = Decls[I].second; 1586 1587 // Mangle the name for the thread_local initialization function. 1588 SmallString<256> InitFnName; 1589 { 1590 llvm::raw_svector_ostream Out(InitFnName); 1591 getMangleContext().mangleItaniumThreadLocalInit(VD, Out); 1592 Out.flush(); 1593 } 1594 1595 // If we have a definition for the variable, emit the initialization 1596 // function as an alias to the global Init function (if any). Otherwise, 1597 // produce a declaration of the initialization function. 1598 llvm::GlobalValue *Init = 0; 1599 bool InitIsInitFunc = false; 1600 if (VD->hasDefinition()) { 1601 InitIsInitFunc = true; 1602 if (InitFunc) 1603 Init = 1604 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(), 1605 InitFnName.str(), InitFunc, &CGM.getModule()); 1606 } else { 1607 // Emit a weak global function referring to the initialization function. 1608 // This function will not exist if the TU defining the thread_local 1609 // variable in question does not need any dynamic initialization for 1610 // its thread_local variables. 1611 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false); 1612 Init = llvm::Function::Create( 1613 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(), 1614 &CGM.getModule()); 1615 } 1616 1617 if (Init) 1618 Init->setVisibility(Var->getVisibility()); 1619 1620 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var); 1621 llvm::LLVMContext &Context = CGM.getModule().getContext(); 1622 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper); 1623 CGBuilderTy Builder(Entry); 1624 if (InitIsInitFunc) { 1625 if (Init) 1626 Builder.CreateCall(Init); 1627 } else { 1628 // Don't know whether we have an init function. Call it if it exists. 1629 llvm::Value *Have = Builder.CreateIsNotNull(Init); 1630 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1631 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper); 1632 Builder.CreateCondBr(Have, InitBB, ExitBB); 1633 1634 Builder.SetInsertPoint(InitBB); 1635 Builder.CreateCall(Init); 1636 Builder.CreateBr(ExitBB); 1637 1638 Builder.SetInsertPoint(ExitBB); 1639 } 1640 1641 // For a reference, the result of the wrapper function is a pointer to 1642 // the referenced object. 1643 llvm::Value *Val = Var; 1644 if (VD->getType()->isReferenceType()) { 1645 llvm::LoadInst *LI = Builder.CreateLoad(Val); 1646 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity()); 1647 Val = LI; 1648 } 1649 1650 Builder.CreateRet(Val); 1651 } 1652 } 1653 1654 LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF, 1655 const DeclRefExpr *DRE) { 1656 const VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1657 QualType T = VD->getType(); 1658 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T); 1659 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty); 1660 llvm::Function *Wrapper = 1661 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val)); 1662 1663 Val = CGF.Builder.CreateCall(Wrapper); 1664 1665 LValue LV; 1666 if (VD->getType()->isReferenceType()) 1667 LV = CGF.MakeNaturalAlignAddrLValue(Val, T); 1668 else 1669 LV = CGF.MakeAddrLValue(Val, DRE->getType(), 1670 CGF.getContext().getDeclAlign(VD)); 1671 // FIXME: need setObjCGCLValueClass? 1672 return LV; 1673 } 1674 1675 /// Return whether the given global decl needs a VTT parameter, which it does 1676 /// if it's a base constructor or destructor with virtual bases. 1677 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) { 1678 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1679 1680 // We don't have any virtual bases, just return early. 1681 if (!MD->getParent()->getNumVBases()) 1682 return false; 1683 1684 // Check if we have a base constructor. 1685 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 1686 return true; 1687 1688 // Check if we have a base destructor. 1689 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 1690 return true; 1691 1692 return false; 1693 } 1694