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