ItaniumCXXABI.cpp revision 0502a224984a26087ea4d64e8e5d2dd4dca432f6
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 "CodeGenFunction.h" 24#include "CodeGenModule.h" 25#include <clang/AST/Mangle.h> 26#include <clang/AST/Type.h> 27#include <llvm/Intrinsics.h> 28#include <llvm/Target/TargetData.h> 29#include <llvm/Value.h> 30 31using namespace clang; 32using namespace CodeGen; 33 34namespace { 35class ItaniumCXXABI : public CodeGen::CGCXXABI { 36private: 37 const llvm::IntegerType *PtrDiffTy; 38protected: 39 bool IsARM; 40 41 // It's a little silly for us to cache this. 42 const llvm::IntegerType *getPtrDiffTy() { 43 if (!PtrDiffTy) { 44 QualType T = getContext().getPointerDiffType(); 45 const llvm::Type *Ty = CGM.getTypes().ConvertTypeRecursive(T); 46 PtrDiffTy = cast<llvm::IntegerType>(Ty); 47 } 48 return PtrDiffTy; 49 } 50 51 bool NeedsArrayCookie(const CXXNewExpr *expr); 52 bool NeedsArrayCookie(const CXXDeleteExpr *expr, 53 QualType elementType); 54 55public: 56 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) : 57 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { } 58 59 bool isZeroInitializable(const MemberPointerType *MPT); 60 61 const llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 62 63 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 64 llvm::Value *&This, 65 llvm::Value *MemFnPtr, 66 const MemberPointerType *MPT); 67 68 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 69 llvm::Value *Base, 70 llvm::Value *MemPtr, 71 const MemberPointerType *MPT); 72 73 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 74 const CastExpr *E, 75 llvm::Value *Src); 76 77 llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C, 78 const CastExpr *E); 79 80 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 81 82 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 83 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 84 CharUnits offset); 85 86 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 87 llvm::Value *L, 88 llvm::Value *R, 89 const MemberPointerType *MPT, 90 bool Inequality); 91 92 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 93 llvm::Value *Addr, 94 const MemberPointerType *MPT); 95 96 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 97 CXXCtorType T, 98 CanQualType &ResTy, 99 llvm::SmallVectorImpl<CanQualType> &ArgTys); 100 101 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 102 CXXDtorType T, 103 CanQualType &ResTy, 104 llvm::SmallVectorImpl<CanQualType> &ArgTys); 105 106 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 107 QualType &ResTy, 108 FunctionArgList &Params); 109 110 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 111 112 CharUnits GetArrayCookieSize(const CXXNewExpr *expr); 113 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 114 llvm::Value *NewPtr, 115 llvm::Value *NumElements, 116 const CXXNewExpr *expr, 117 QualType ElementType); 118 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr, 119 const CXXDeleteExpr *expr, 120 QualType ElementType, llvm::Value *&NumElements, 121 llvm::Value *&AllocPtr, CharUnits &CookieSize); 122 123 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 124 llvm::GlobalVariable *DeclPtr); 125}; 126 127class ARMCXXABI : public ItaniumCXXABI { 128public: 129 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {} 130 131 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 132 CXXCtorType T, 133 CanQualType &ResTy, 134 llvm::SmallVectorImpl<CanQualType> &ArgTys); 135 136 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 137 CXXDtorType T, 138 CanQualType &ResTy, 139 llvm::SmallVectorImpl<CanQualType> &ArgTys); 140 141 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 142 QualType &ResTy, 143 FunctionArgList &Params); 144 145 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 146 147 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy); 148 149 CharUnits GetArrayCookieSize(const CXXNewExpr *expr); 150 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 151 llvm::Value *NewPtr, 152 llvm::Value *NumElements, 153 const CXXNewExpr *expr, 154 QualType ElementType); 155 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr, 156 const CXXDeleteExpr *expr, 157 QualType ElementType, llvm::Value *&NumElements, 158 llvm::Value *&AllocPtr, CharUnits &CookieSize); 159 160private: 161 /// \brief Returns true if the given instance method is one of the 162 /// kinds that the ARM ABI says returns 'this'. 163 static bool HasThisReturn(GlobalDecl GD) { 164 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 165 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) || 166 (isa<CXXConstructorDecl>(MD))); 167 } 168}; 169} 170 171CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 172 return new ItaniumCXXABI(CGM); 173} 174 175CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) { 176 return new ARMCXXABI(CGM); 177} 178 179const llvm::Type * 180ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 181 if (MPT->isMemberDataPointer()) 182 return getPtrDiffTy(); 183 else 184 return llvm::StructType::get(CGM.getLLVMContext(), 185 getPtrDiffTy(), getPtrDiffTy(), NULL); 186} 187 188/// In the Itanium and ARM ABIs, method pointers have the form: 189/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 190/// 191/// In the Itanium ABI: 192/// - method pointers are virtual if (memptr.ptr & 1) is nonzero 193/// - the this-adjustment is (memptr.adj) 194/// - the virtual offset is (memptr.ptr - 1) 195/// 196/// In the ARM ABI: 197/// - method pointers are virtual if (memptr.adj & 1) is nonzero 198/// - the this-adjustment is (memptr.adj >> 1) 199/// - the virtual offset is (memptr.ptr) 200/// ARM uses 'adj' for the virtual flag because Thumb functions 201/// may be only single-byte aligned. 202/// 203/// If the member is virtual, the adjusted 'this' pointer points 204/// to a vtable pointer from which the virtual offset is applied. 205/// 206/// If the member is non-virtual, memptr.ptr is the address of 207/// the function to call. 208llvm::Value * 209ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 210 llvm::Value *&This, 211 llvm::Value *MemFnPtr, 212 const MemberPointerType *MPT) { 213 CGBuilderTy &Builder = CGF.Builder; 214 215 const FunctionProtoType *FPT = 216 MPT->getPointeeType()->getAs<FunctionProtoType>(); 217 const CXXRecordDecl *RD = 218 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 219 220 const llvm::FunctionType *FTy = 221 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT), 222 FPT->isVariadic()); 223 224 const llvm::IntegerType *ptrdiff = getPtrDiffTy(); 225 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1); 226 227 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 228 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 229 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 230 231 // Extract memptr.adj, which is in the second field. 232 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 233 234 // Compute the true adjustment. 235 llvm::Value *Adj = RawAdj; 236 if (IsARM) 237 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 238 239 // Apply the adjustment and cast back to the original struct type 240 // for consistency. 241 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 242 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 243 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 244 245 // Load the function pointer. 246 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 247 248 // If the LSB in the function pointer is 1, the function pointer points to 249 // a virtual function. 250 llvm::Value *IsVirtual; 251 if (IsARM) 252 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 253 else 254 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 255 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 256 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 257 258 // In the virtual path, the adjustment left 'This' pointing to the 259 // vtable of the correct base subobject. The "function pointer" is an 260 // offset within the vtable (+1 for the virtual flag on non-ARM). 261 CGF.EmitBlock(FnVirtual); 262 263 // Cast the adjusted this to a pointer to vtable pointer and load. 264 const llvm::Type *VTableTy = Builder.getInt8PtrTy(); 265 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo()); 266 VTable = Builder.CreateLoad(VTable, "memptr.vtable"); 267 268 // Apply the offset. 269 llvm::Value *VTableOffset = FnAsInt; 270 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 271 VTable = Builder.CreateGEP(VTable, VTableOffset); 272 273 // Load the virtual function to call. 274 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 275 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 276 CGF.EmitBranch(FnEnd); 277 278 // In the non-virtual path, the function pointer is actually a 279 // function pointer. 280 CGF.EmitBlock(FnNonVirtual); 281 llvm::Value *NonVirtualFn = 282 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 283 284 // We're done. 285 CGF.EmitBlock(FnEnd); 286 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2); 287 Callee->addIncoming(VirtualFn, FnVirtual); 288 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 289 return Callee; 290} 291 292/// Compute an l-value by applying the given pointer-to-member to a 293/// base object. 294llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 295 llvm::Value *Base, 296 llvm::Value *MemPtr, 297 const MemberPointerType *MPT) { 298 assert(MemPtr->getType() == getPtrDiffTy()); 299 300 CGBuilderTy &Builder = CGF.Builder; 301 302 unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace(); 303 304 // Cast to char*. 305 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS)); 306 307 // Apply the offset, which we assume is non-null. 308 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset"); 309 310 // Cast the address to the appropriate pointer type, adopting the 311 // address space of the base pointer. 312 const llvm::Type *PType 313 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS); 314 return Builder.CreateBitCast(Addr, PType); 315} 316 317/// Perform a derived-to-base or base-to-derived member pointer conversion. 318/// 319/// Obligatory offset/adjustment diagram: 320/// <-- offset --> <-- adjustment --> 321/// |--------------------------|----------------------|--------------------| 322/// ^Derived address point ^Base address point ^Member address point 323/// 324/// So when converting a base member pointer to a derived member pointer, 325/// we add the offset to the adjustment because the address point has 326/// decreased; and conversely, when converting a derived MP to a base MP 327/// we subtract the offset from the adjustment because the address point 328/// has increased. 329/// 330/// The standard forbids (at compile time) conversion to and from 331/// virtual bases, which is why we don't have to consider them here. 332/// 333/// The standard forbids (at run time) casting a derived MP to a base 334/// MP when the derived MP does not point to a member of the base. 335/// This is why -1 is a reasonable choice for null data member 336/// pointers. 337llvm::Value * 338ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 339 const CastExpr *E, 340 llvm::Value *Src) { 341 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer || 342 E->getCastKind() == CK_BaseToDerivedMemberPointer); 343 344 if (isa<llvm::Constant>(Src)) 345 return EmitMemberPointerConversion(cast<llvm::Constant>(Src), E); 346 347 CGBuilderTy &Builder = CGF.Builder; 348 349 const MemberPointerType *SrcTy = 350 E->getSubExpr()->getType()->getAs<MemberPointerType>(); 351 const MemberPointerType *DestTy = E->getType()->getAs<MemberPointerType>(); 352 353 const CXXRecordDecl *SrcDecl = SrcTy->getClass()->getAsCXXRecordDecl(); 354 const CXXRecordDecl *DestDecl = DestTy->getClass()->getAsCXXRecordDecl(); 355 356 bool DerivedToBase = 357 E->getCastKind() == CK_DerivedToBaseMemberPointer; 358 359 const CXXRecordDecl *DerivedDecl; 360 if (DerivedToBase) 361 DerivedDecl = SrcDecl; 362 else 363 DerivedDecl = DestDecl; 364 365 llvm::Constant *Adj = 366 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, 367 E->path_begin(), 368 E->path_end()); 369 if (!Adj) return Src; 370 371 // For member data pointers, this is just a matter of adding the 372 // offset if the source is non-null. 373 if (SrcTy->isMemberDataPointer()) { 374 llvm::Value *Dst; 375 if (DerivedToBase) 376 Dst = Builder.CreateNSWSub(Src, Adj, "adj"); 377 else 378 Dst = Builder.CreateNSWAdd(Src, Adj, "adj"); 379 380 // Null check. 381 llvm::Value *Null = llvm::Constant::getAllOnesValue(Src->getType()); 382 llvm::Value *IsNull = Builder.CreateICmpEQ(Src, Null, "memptr.isnull"); 383 return Builder.CreateSelect(IsNull, Src, Dst); 384 } 385 386 // The this-adjustment is left-shifted by 1 on ARM. 387 if (IsARM) { 388 uint64_t Offset = cast<llvm::ConstantInt>(Adj)->getZExtValue(); 389 Offset <<= 1; 390 Adj = llvm::ConstantInt::get(Adj->getType(), Offset); 391 } 392 393 llvm::Value *SrcAdj = Builder.CreateExtractValue(Src, 1, "src.adj"); 394 llvm::Value *DstAdj; 395 if (DerivedToBase) 396 DstAdj = Builder.CreateNSWSub(SrcAdj, Adj, "adj"); 397 else 398 DstAdj = Builder.CreateNSWAdd(SrcAdj, Adj, "adj"); 399 400 return Builder.CreateInsertValue(Src, DstAdj, 1); 401} 402 403llvm::Constant * 404ItaniumCXXABI::EmitMemberPointerConversion(llvm::Constant *C, 405 const CastExpr *E) { 406 const MemberPointerType *SrcTy = 407 E->getSubExpr()->getType()->getAs<MemberPointerType>(); 408 const MemberPointerType *DestTy = 409 E->getType()->getAs<MemberPointerType>(); 410 411 bool DerivedToBase = 412 E->getCastKind() == CK_DerivedToBaseMemberPointer; 413 414 const CXXRecordDecl *DerivedDecl; 415 if (DerivedToBase) 416 DerivedDecl = SrcTy->getClass()->getAsCXXRecordDecl(); 417 else 418 DerivedDecl = DestTy->getClass()->getAsCXXRecordDecl(); 419 420 // Calculate the offset to the base class. 421 llvm::Constant *Offset = 422 CGM.GetNonVirtualBaseClassOffset(DerivedDecl, 423 E->path_begin(), 424 E->path_end()); 425 // If there's no offset, we're done. 426 if (!Offset) return C; 427 428 // If the source is a member data pointer, we have to do a null 429 // check and then add the offset. In the common case, we can fold 430 // away the offset. 431 if (SrcTy->isMemberDataPointer()) { 432 assert(C->getType() == getPtrDiffTy()); 433 434 // If it's a constant int, just create a new constant int. 435 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) { 436 int64_t Src = CI->getSExtValue(); 437 438 // Null converts to null. 439 if (Src == -1) return CI; 440 441 // Otherwise, just add the offset. 442 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue(); 443 int64_t Dst = (DerivedToBase ? Src - OffsetV : Src + OffsetV); 444 return llvm::ConstantInt::get(CI->getType(), Dst, /*signed*/ true); 445 } 446 447 // Otherwise, we have to form a constant select expression. 448 llvm::Constant *Null = llvm::Constant::getAllOnesValue(C->getType()); 449 450 llvm::Constant *IsNull = 451 llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, C, Null); 452 453 llvm::Constant *Dst; 454 if (DerivedToBase) 455 Dst = llvm::ConstantExpr::getNSWSub(C, Offset); 456 else 457 Dst = llvm::ConstantExpr::getNSWAdd(C, Offset); 458 459 return llvm::ConstantExpr::getSelect(IsNull, Null, Dst); 460 } 461 462 // The this-adjustment is left-shifted by 1 on ARM. 463 if (IsARM) { 464 int64_t OffsetV = cast<llvm::ConstantInt>(Offset)->getSExtValue(); 465 OffsetV <<= 1; 466 Offset = llvm::ConstantInt::get(Offset->getType(), OffsetV); 467 } 468 469 llvm::ConstantStruct *CS = cast<llvm::ConstantStruct>(C); 470 471 llvm::Constant *Values[2] = { CS->getOperand(0), 0 }; 472 if (DerivedToBase) 473 Values[1] = llvm::ConstantExpr::getSub(CS->getOperand(1), Offset); 474 else 475 Values[1] = llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset); 476 477 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2, 478 /*Packed=*/false); 479} 480 481 482llvm::Constant * 483ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 484 const llvm::Type *ptrdiff_t = getPtrDiffTy(); 485 486 // Itanium C++ ABI 2.3: 487 // A NULL pointer is represented as -1. 488 if (MPT->isMemberDataPointer()) 489 return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true); 490 491 llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0); 492 llvm::Constant *Values[2] = { Zero, Zero }; 493 return llvm::ConstantStruct::get(CGM.getLLVMContext(), Values, 2, 494 /*Packed=*/false); 495} 496 497llvm::Constant * 498ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT, 499 CharUnits offset) { 500 // Itanium C++ ABI 2.3: 501 // A pointer to data member is an offset from the base address of 502 // the class object containing it, represented as a ptrdiff_t 503 return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity()); 504} 505 506llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 507 assert(MD->isInstance() && "Member function must not be static!"); 508 MD = MD->getCanonicalDecl(); 509 510 CodeGenTypes &Types = CGM.getTypes(); 511 const llvm::Type *ptrdiff_t = getPtrDiffTy(); 512 513 // Get the function pointer (or index if this is a virtual function). 514 llvm::Constant *MemPtr[2]; 515 if (MD->isVirtual()) { 516 uint64_t Index = CGM.getVTables().getMethodVTableIndex(MD); 517 518 const ASTContext &Context = getContext(); 519 CharUnits PointerWidth = 520 Context.toCharUnitsFromBits(Context.Target.getPointerWidth(0)); 521 uint64_t VTableOffset = (Index * PointerWidth.getQuantity()); 522 523 if (IsARM) { 524 // ARM C++ ABI 3.2.1: 525 // This ABI specifies that adj contains twice the this 526 // adjustment, plus 1 if the member function is virtual. The 527 // least significant bit of adj then makes exactly the same 528 // discrimination as the least significant bit of ptr does for 529 // Itanium. 530 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset); 531 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 1); 532 } else { 533 // Itanium C++ ABI 2.3: 534 // For a virtual function, [the pointer field] is 1 plus the 535 // virtual table offset (in bytes) of the function, 536 // represented as a ptrdiff_t. 537 MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1); 538 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0); 539 } 540 } else { 541 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 542 const llvm::Type *Ty; 543 // Check whether the function has a computable LLVM signature. 544 if (!CodeGenTypes::VerifyFuncTypeComplete(FPT)) { 545 // The function has a computable LLVM signature; use the correct type. 546 Ty = Types.GetFunctionType(Types.getFunctionInfo(MD), 547 FPT->isVariadic()); 548 } else { 549 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 550 // function type is incomplete. 551 Ty = ptrdiff_t; 552 } 553 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty); 554 555 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t); 556 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0); 557 } 558 559 return llvm::ConstantStruct::get(CGM.getLLVMContext(), 560 MemPtr, 2, /*Packed=*/false); 561} 562 563/// The comparison algorithm is pretty easy: the member pointers are 564/// the same if they're either bitwise identical *or* both null. 565/// 566/// ARM is different here only because null-ness is more complicated. 567llvm::Value * 568ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 569 llvm::Value *L, 570 llvm::Value *R, 571 const MemberPointerType *MPT, 572 bool Inequality) { 573 CGBuilderTy &Builder = CGF.Builder; 574 575 llvm::ICmpInst::Predicate Eq; 576 llvm::Instruction::BinaryOps And, Or; 577 if (Inequality) { 578 Eq = llvm::ICmpInst::ICMP_NE; 579 And = llvm::Instruction::Or; 580 Or = llvm::Instruction::And; 581 } else { 582 Eq = llvm::ICmpInst::ICMP_EQ; 583 And = llvm::Instruction::And; 584 Or = llvm::Instruction::Or; 585 } 586 587 // Member data pointers are easy because there's a unique null 588 // value, so it just comes down to bitwise equality. 589 if (MPT->isMemberDataPointer()) 590 return Builder.CreateICmp(Eq, L, R); 591 592 // For member function pointers, the tautologies are more complex. 593 // The Itanium tautology is: 594 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 595 // The ARM tautology is: 596 // (L == R) <==> (L.ptr == R.ptr && 597 // (L.adj == R.adj || 598 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 599 // The inequality tautologies have exactly the same structure, except 600 // applying De Morgan's laws. 601 602 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 603 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 604 605 // This condition tests whether L.ptr == R.ptr. This must always be 606 // true for equality to hold. 607 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 608 609 // This condition, together with the assumption that L.ptr == R.ptr, 610 // tests whether the pointers are both null. ARM imposes an extra 611 // condition. 612 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 613 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 614 615 // This condition tests whether L.adj == R.adj. If this isn't 616 // true, the pointers are unequal unless they're both null. 617 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 618 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 619 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 620 621 // Null member function pointers on ARM clear the low bit of Adj, 622 // so the zero condition has to check that neither low bit is set. 623 if (IsARM) { 624 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 625 626 // Compute (l.adj | r.adj) & 1 and test it against zero. 627 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 628 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 629 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 630 "cmp.or.adj"); 631 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 632 } 633 634 // Tie together all our conditions. 635 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 636 Result = Builder.CreateBinOp(And, PtrEq, Result, 637 Inequality ? "memptr.ne" : "memptr.eq"); 638 return Result; 639} 640 641llvm::Value * 642ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 643 llvm::Value *MemPtr, 644 const MemberPointerType *MPT) { 645 CGBuilderTy &Builder = CGF.Builder; 646 647 /// For member data pointers, this is just a check against -1. 648 if (MPT->isMemberDataPointer()) { 649 assert(MemPtr->getType() == getPtrDiffTy()); 650 llvm::Value *NegativeOne = 651 llvm::Constant::getAllOnesValue(MemPtr->getType()); 652 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 653 } 654 655 // In Itanium, a member function pointer is not null if 'ptr' is not null. 656 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 657 658 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 659 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 660 661 // On ARM, a member function pointer is also non-null if the low bit of 'adj' 662 // (the virtual bit) is set. 663 if (IsARM) { 664 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 665 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 666 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 667 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero, 668 "memptr.isvirtual"); 669 Result = Builder.CreateOr(Result, IsVirtual); 670 } 671 672 return Result; 673} 674 675/// The Itanium ABI requires non-zero initialization only for data 676/// member pointers, for which '0' is a valid offset. 677bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 678 return MPT->getPointeeType()->isFunctionType(); 679} 680 681/// The generic ABI passes 'this', plus a VTT if it's initializing a 682/// base subobject. 683void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 684 CXXCtorType Type, 685 CanQualType &ResTy, 686 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 687 ASTContext &Context = getContext(); 688 689 // 'this' is already there. 690 691 // Check if we need to add a VTT parameter (which has type void **). 692 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0) 693 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 694} 695 696/// The ARM ABI does the same as the Itanium ABI, but returns 'this'. 697void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 698 CXXCtorType Type, 699 CanQualType &ResTy, 700 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 701 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys); 702 ResTy = ArgTys[0]; 703} 704 705/// The generic ABI passes 'this', plus a VTT if it's destroying a 706/// base subobject. 707void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 708 CXXDtorType Type, 709 CanQualType &ResTy, 710 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 711 ASTContext &Context = getContext(); 712 713 // 'this' is already there. 714 715 // Check if we need to add a VTT parameter (which has type void **). 716 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0) 717 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 718} 719 720/// The ARM ABI does the same as the Itanium ABI, but returns 'this' 721/// for non-deleting destructors. 722void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 723 CXXDtorType Type, 724 CanQualType &ResTy, 725 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 726 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys); 727 728 if (Type != Dtor_Deleting) 729 ResTy = ArgTys[0]; 730} 731 732void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 733 QualType &ResTy, 734 FunctionArgList &Params) { 735 /// Create the 'this' variable. 736 BuildThisParam(CGF, Params); 737 738 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 739 assert(MD->isInstance()); 740 741 // Check if we need a VTT parameter as well. 742 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) { 743 ASTContext &Context = getContext(); 744 745 // FIXME: avoid the fake decl 746 QualType T = Context.getPointerType(Context.VoidPtrTy); 747 ImplicitParamDecl *VTTDecl 748 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(), 749 &Context.Idents.get("vtt"), T); 750 Params.push_back(VTTDecl); 751 getVTTDecl(CGF) = VTTDecl; 752 } 753} 754 755void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 756 QualType &ResTy, 757 FunctionArgList &Params) { 758 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params); 759 760 // Return 'this' from certain constructors and destructors. 761 if (HasThisReturn(CGF.CurGD)) 762 ResTy = Params[0]->getType(); 763} 764 765void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 766 /// Initialize the 'this' slot. 767 EmitThisParam(CGF); 768 769 /// Initialize the 'vtt' slot if needed. 770 if (getVTTDecl(CGF)) { 771 getVTTValue(CGF) 772 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)), 773 "vtt"); 774 } 775} 776 777void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 778 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF); 779 780 /// Initialize the return slot to 'this' at the start of the 781 /// function. 782 if (HasThisReturn(CGF.CurGD)) 783 CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue); 784} 785 786void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 787 RValue RV, QualType ResultType) { 788 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 789 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 790 791 // Destructor thunks in the ARM ABI have indeterminate results. 792 const llvm::Type *T = 793 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 794 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 795 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 796} 797 798/************************** Array allocation cookies **************************/ 799 800bool ItaniumCXXABI::NeedsArrayCookie(const CXXNewExpr *expr) { 801 // If the class's usual deallocation function takes two arguments, 802 // it needs a cookie. 803 if (expr->doesUsualArrayDeleteWantSize()) 804 return true; 805 806 // Automatic Reference Counting: 807 // We need an array cookie for pointers with strong or weak lifetime. 808 QualType AllocatedType = expr->getAllocatedType(); 809 if (getContext().getLangOptions().ObjCAutoRefCount && 810 AllocatedType->isObjCLifetimeType()) { 811 switch (AllocatedType.getObjCLifetime()) { 812 case Qualifiers::OCL_None: 813 case Qualifiers::OCL_ExplicitNone: 814 case Qualifiers::OCL_Autoreleasing: 815 return false; 816 817 case Qualifiers::OCL_Strong: 818 case Qualifiers::OCL_Weak: 819 return true; 820 } 821 } 822 823 // Otherwise, if the class has a non-trivial destructor, it always 824 // needs a cookie. 825 const CXXRecordDecl *record = 826 AllocatedType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 827 return (record && !record->hasTrivialDestructor()); 828} 829 830bool ItaniumCXXABI::NeedsArrayCookie(const CXXDeleteExpr *expr, 831 QualType elementType) { 832 // If the class's usual deallocation function takes two arguments, 833 // it needs a cookie. 834 if (expr->doesUsualArrayDeleteWantSize()) 835 return true; 836 837 // Automatic Reference Counting: 838 // We need an array cookie for pointers with strong or weak lifetime. 839 if (getContext().getLangOptions().ObjCAutoRefCount && 840 elementType->isObjCLifetimeType()) { 841 switch (elementType.getObjCLifetime()) { 842 case Qualifiers::OCL_None: 843 case Qualifiers::OCL_ExplicitNone: 844 case Qualifiers::OCL_Autoreleasing: 845 return false; 846 847 case Qualifiers::OCL_Strong: 848 case Qualifiers::OCL_Weak: 849 return true; 850 } 851 } 852 853 // Otherwise, if the class has a non-trivial destructor, it always 854 // needs a cookie. 855 const CXXRecordDecl *record = 856 elementType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 857 return (record && !record->hasTrivialDestructor()); 858} 859 860CharUnits ItaniumCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { 861 if (!NeedsArrayCookie(expr)) 862 return CharUnits::Zero(); 863 864 // Padding is the maximum of sizeof(size_t) and alignof(elementType) 865 ASTContext &Ctx = getContext(); 866 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 867 Ctx.getTypeAlignInChars(expr->getAllocatedType())); 868} 869 870llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 871 llvm::Value *NewPtr, 872 llvm::Value *NumElements, 873 const CXXNewExpr *expr, 874 QualType ElementType) { 875 assert(NeedsArrayCookie(expr)); 876 877 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace(); 878 879 ASTContext &Ctx = getContext(); 880 QualType SizeTy = Ctx.getSizeType(); 881 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 882 883 // The size of the cookie. 884 CharUnits CookieSize = 885 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 886 887 // Compute an offset to the cookie. 888 llvm::Value *CookiePtr = NewPtr; 889 CharUnits CookieOffset = CookieSize - SizeSize; 890 if (!CookieOffset.isZero()) 891 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 892 CookieOffset.getQuantity()); 893 894 // Write the number of elements into the appropriate slot. 895 llvm::Value *NumElementsPtr 896 = CGF.Builder.CreateBitCast(CookiePtr, 897 CGF.ConvertType(SizeTy)->getPointerTo(AS)); 898 CGF.Builder.CreateStore(NumElements, NumElementsPtr); 899 900 // Finally, compute a pointer to the actual data buffer by skipping 901 // over the cookie completely. 902 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 903 CookieSize.getQuantity()); 904} 905 906void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF, 907 llvm::Value *Ptr, 908 const CXXDeleteExpr *expr, 909 QualType ElementType, 910 llvm::Value *&NumElements, 911 llvm::Value *&AllocPtr, 912 CharUnits &CookieSize) { 913 // Derive a char* in the same address space as the pointer. 914 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 915 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS); 916 917 // If we don't need an array cookie, bail out early. 918 if (!NeedsArrayCookie(expr, ElementType)) { 919 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 920 NumElements = 0; 921 CookieSize = CharUnits::Zero(); 922 return; 923 } 924 925 QualType SizeTy = getContext().getSizeType(); 926 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy); 927 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy); 928 929 CookieSize 930 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType)); 931 932 CharUnits NumElementsOffset = CookieSize - SizeSize; 933 934 // Compute the allocated pointer. 935 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 936 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 937 -CookieSize.getQuantity()); 938 939 llvm::Value *NumElementsPtr = AllocPtr; 940 if (!NumElementsOffset.isZero()) 941 NumElementsPtr = 942 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr, 943 NumElementsOffset.getQuantity()); 944 NumElementsPtr = 945 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS)); 946 NumElements = CGF.Builder.CreateLoad(NumElementsPtr); 947} 948 949CharUnits ARMCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { 950 if (!NeedsArrayCookie(expr)) 951 return CharUnits::Zero(); 952 953 // On ARM, the cookie is always: 954 // struct array_cookie { 955 // std::size_t element_size; // element_size != 0 956 // std::size_t element_count; 957 // }; 958 // TODO: what should we do if the allocated type actually wants 959 // greater alignment? 960 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2; 961} 962 963llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 964 llvm::Value *NewPtr, 965 llvm::Value *NumElements, 966 const CXXNewExpr *expr, 967 QualType ElementType) { 968 assert(NeedsArrayCookie(expr)); 969 970 // NewPtr is a char*. 971 972 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace(); 973 974 ASTContext &Ctx = getContext(); 975 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType()); 976 const llvm::IntegerType *SizeTy = 977 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType())); 978 979 // The cookie is always at the start of the buffer. 980 llvm::Value *CookiePtr = NewPtr; 981 982 // The first element is the element size. 983 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS)); 984 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy, 985 Ctx.getTypeSizeInChars(ElementType).getQuantity()); 986 CGF.Builder.CreateStore(ElementSize, CookiePtr); 987 988 // The second element is the element count. 989 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1); 990 CGF.Builder.CreateStore(NumElements, CookiePtr); 991 992 // Finally, compute a pointer to the actual data buffer by skipping 993 // over the cookie completely. 994 CharUnits CookieSize = 2 * SizeSize; 995 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 996 CookieSize.getQuantity()); 997} 998 999void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF, 1000 llvm::Value *Ptr, 1001 const CXXDeleteExpr *expr, 1002 QualType ElementType, 1003 llvm::Value *&NumElements, 1004 llvm::Value *&AllocPtr, 1005 CharUnits &CookieSize) { 1006 // Derive a char* in the same address space as the pointer. 1007 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 1008 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS); 1009 1010 // If we don't need an array cookie, bail out early. 1011 if (!NeedsArrayCookie(expr, ElementType)) { 1012 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 1013 NumElements = 0; 1014 CookieSize = CharUnits::Zero(); 1015 return; 1016 } 1017 1018 QualType SizeTy = getContext().getSizeType(); 1019 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy); 1020 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy); 1021 1022 // The cookie size is always 2 * sizeof(size_t). 1023 CookieSize = 2 * SizeSize; 1024 1025 // The allocated pointer is the input ptr, minus that amount. 1026 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 1027 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 1028 -CookieSize.getQuantity()); 1029 1030 // The number of elements is at offset sizeof(size_t) relative to that. 1031 llvm::Value *NumElementsPtr 1032 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 1033 SizeSize.getQuantity()); 1034 NumElementsPtr = 1035 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS)); 1036 NumElements = CGF.Builder.CreateLoad(NumElementsPtr); 1037} 1038 1039/*********************** Static local initialization **************************/ 1040 1041static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1042 const llvm::PointerType *GuardPtrTy) { 1043 // int __cxa_guard_acquire(__guard *guard_object); 1044 const llvm::FunctionType *FTy = 1045 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1046 GuardPtrTy, /*isVarArg=*/false); 1047 1048 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire"); 1049} 1050 1051static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1052 const llvm::PointerType *GuardPtrTy) { 1053 // void __cxa_guard_release(__guard *guard_object); 1054 const llvm::FunctionType *FTy = 1055 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 1056 GuardPtrTy, /*isVarArg=*/false); 1057 1058 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release"); 1059} 1060 1061static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1062 const llvm::PointerType *GuardPtrTy) { 1063 // void __cxa_guard_abort(__guard *guard_object); 1064 const llvm::FunctionType *FTy = 1065 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 1066 GuardPtrTy, /*isVarArg=*/false); 1067 1068 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort"); 1069} 1070 1071namespace { 1072 struct CallGuardAbort : EHScopeStack::Cleanup { 1073 llvm::GlobalVariable *Guard; 1074 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1075 1076 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1077 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard) 1078 ->setDoesNotThrow(); 1079 } 1080 }; 1081} 1082 1083/// The ARM code here follows the Itanium code closely enough that we 1084/// just special-case it at particular places. 1085void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1086 const VarDecl &D, 1087 llvm::GlobalVariable *GV) { 1088 CGBuilderTy &Builder = CGF.Builder; 1089 1090 // We only need to use thread-safe statics for local variables; 1091 // global initialization is always single-threaded. 1092 bool threadsafe = 1093 (getContext().getLangOptions().ThreadsafeStatics && D.isLocalVarDecl()); 1094 1095 const llvm::IntegerType *GuardTy; 1096 1097 // If we have a global variable with internal linkage and thread-safe statics 1098 // are disabled, we can just let the guard variable be of type i8. 1099 bool useInt8GuardVariable = !threadsafe && GV->hasInternalLinkage(); 1100 if (useInt8GuardVariable) { 1101 GuardTy = CGF.Int8Ty; 1102 } else { 1103 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM. 1104 GuardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty); 1105 } 1106 const llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo(); 1107 1108 // Create the guard variable. 1109 llvm::SmallString<256> GuardVName; 1110 llvm::raw_svector_ostream Out(GuardVName); 1111 getMangleContext().mangleItaniumGuardVariable(&D, Out); 1112 Out.flush(); 1113 1114 // Just absorb linkage and visibility from the variable. 1115 llvm::GlobalVariable *GuardVariable = 1116 new llvm::GlobalVariable(CGM.getModule(), GuardTy, 1117 false, GV->getLinkage(), 1118 llvm::ConstantInt::get(GuardTy, 0), 1119 GuardVName.str()); 1120 GuardVariable->setVisibility(GV->getVisibility()); 1121 1122 // Test whether the variable has completed initialization. 1123 llvm::Value *IsInitialized; 1124 1125 // ARM C++ ABI 3.2.3.1: 1126 // To support the potential use of initialization guard variables 1127 // as semaphores that are the target of ARM SWP and LDREX/STREX 1128 // synchronizing instructions we define a static initialization 1129 // guard variable to be a 4-byte aligned, 4- byte word with the 1130 // following inline access protocol. 1131 // #define INITIALIZED 1 1132 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1133 // if (__cxa_guard_acquire(&obj_guard)) 1134 // ... 1135 // } 1136 if (IsARM && !useInt8GuardVariable) { 1137 llvm::Value *V = Builder.CreateLoad(GuardVariable); 1138 V = Builder.CreateAnd(V, Builder.getInt32(1)); 1139 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1140 1141 // Itanium C++ ABI 3.3.2: 1142 // The following is pseudo-code showing how these functions can be used: 1143 // if (obj_guard.first_byte == 0) { 1144 // if ( __cxa_guard_acquire (&obj_guard) ) { 1145 // try { 1146 // ... initialize the object ...; 1147 // } catch (...) { 1148 // __cxa_guard_abort (&obj_guard); 1149 // throw; 1150 // } 1151 // ... queue object destructor with __cxa_atexit() ...; 1152 // __cxa_guard_release (&obj_guard); 1153 // } 1154 // } 1155 } else { 1156 // Load the first byte of the guard variable. 1157 const llvm::Type *PtrTy = Builder.getInt8PtrTy(); 1158 llvm::Value *V = 1159 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy), "tmp"); 1160 1161 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1162 } 1163 1164 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1165 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1166 1167 llvm::BasicBlock *NoCheckBlock = EndBlock; 1168 if (threadsafe) NoCheckBlock = CGF.createBasicBlock("init.barrier"); 1169 1170 // Check if the first byte of the guard variable is zero. 1171 Builder.CreateCondBr(IsInitialized, InitCheckBlock, NoCheckBlock); 1172 1173 CGF.EmitBlock(InitCheckBlock); 1174 1175 // Variables used when coping with thread-safe statics and exceptions. 1176 if (threadsafe) { 1177 // Call __cxa_guard_acquire. 1178 llvm::Value *V 1179 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable); 1180 1181 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1182 1183 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1184 InitBlock, EndBlock); 1185 1186 // Call __cxa_guard_abort along the exceptional edge. 1187 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable); 1188 1189 CGF.EmitBlock(InitBlock); 1190 } 1191 1192 // Emit the initializer and add a global destructor if appropriate. 1193 CGF.EmitCXXGlobalVarDeclInit(D, GV); 1194 1195 if (threadsafe) { 1196 // Pop the guard-abort cleanup if we pushed one. 1197 CGF.PopCleanupBlock(); 1198 1199 // Call __cxa_guard_release. This cannot throw. 1200 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable); 1201 } else { 1202 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable); 1203 } 1204 1205 // Emit an acquire memory barrier if using thread-safe statics: 1206 // Itanium ABI: 1207 // An implementation supporting thread-safety on multiprocessor 1208 // systems must also guarantee that references to the initialized 1209 // object do not occur before the load of the initialization flag. 1210 if (threadsafe) { 1211 Builder.CreateBr(EndBlock); 1212 CGF.EmitBlock(NoCheckBlock); 1213 1214 llvm::Value *_false = Builder.getFalse(); 1215 llvm::Value *_true = Builder.getTrue(); 1216 1217 Builder.CreateCall5(CGM.getIntrinsic(llvm::Intrinsic::memory_barrier), 1218 /* load-load, load-store */ _true, _true, 1219 /* store-load, store-store */ _false, _false, 1220 /* device or I/O */ _false); 1221 } 1222 1223 CGF.EmitBlock(EndBlock); 1224} 1225