ItaniumCXXABI.cpp revision f0be979bddb8baa28e77693a3dc931e487b2a9f2
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 targetting 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/Target/TargetData.h> 28#include <llvm/Value.h> 29 30using namespace clang; 31using namespace CodeGen; 32 33namespace { 34class ItaniumCXXABI : public CodeGen::CGCXXABI { 35private: 36 const llvm::IntegerType *PtrDiffTy; 37protected: 38 bool IsARM; 39 40 // It's a little silly for us to cache this. 41 const llvm::IntegerType *getPtrDiffTy() { 42 if (!PtrDiffTy) { 43 QualType T = getContext().getPointerDiffType(); 44 const llvm::Type *Ty = CGM.getTypes().ConvertTypeRecursive(T); 45 PtrDiffTy = cast<llvm::IntegerType>(Ty); 46 } 47 return PtrDiffTy; 48 } 49 50 bool NeedsArrayCookie(const CXXNewExpr *expr); 51 bool NeedsArrayCookie(const CXXDeleteExpr *expr, 52 QualType elementType); 53 54public: 55 ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) : 56 CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { } 57 58 bool isZeroInitializable(const MemberPointerType *MPT); 59 60 const llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT); 61 62 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 63 llvm::Value *&This, 64 llvm::Value *MemFnPtr, 65 const MemberPointerType *MPT); 66 67 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF, 68 llvm::Value *Base, 69 llvm::Value *MemPtr, 70 const MemberPointerType *MPT); 71 72 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF, 73 const CastExpr *E, 74 llvm::Value *Src); 75 76 llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C, 77 const CastExpr *E); 78 79 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT); 80 81 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD); 82 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT, 83 CharUnits offset); 84 85 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF, 86 llvm::Value *L, 87 llvm::Value *R, 88 const MemberPointerType *MPT, 89 bool Inequality); 90 91 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 92 llvm::Value *Addr, 93 const MemberPointerType *MPT); 94 95 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 96 CXXCtorType T, 97 CanQualType &ResTy, 98 llvm::SmallVectorImpl<CanQualType> &ArgTys); 99 100 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 101 CXXDtorType T, 102 CanQualType &ResTy, 103 llvm::SmallVectorImpl<CanQualType> &ArgTys); 104 105 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 106 QualType &ResTy, 107 FunctionArgList &Params); 108 109 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 110 111 CharUnits GetArrayCookieSize(const CXXNewExpr *expr); 112 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 113 llvm::Value *NewPtr, 114 llvm::Value *NumElements, 115 const CXXNewExpr *expr, 116 QualType ElementType); 117 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr, 118 const CXXDeleteExpr *expr, 119 QualType ElementType, llvm::Value *&NumElements, 120 llvm::Value *&AllocPtr, CharUnits &CookieSize); 121 122 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D, 123 llvm::GlobalVariable *DeclPtr); 124}; 125 126class ARMCXXABI : public ItaniumCXXABI { 127public: 128 ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {} 129 130 void BuildConstructorSignature(const CXXConstructorDecl *Ctor, 131 CXXCtorType T, 132 CanQualType &ResTy, 133 llvm::SmallVectorImpl<CanQualType> &ArgTys); 134 135 void BuildDestructorSignature(const CXXDestructorDecl *Dtor, 136 CXXDtorType T, 137 CanQualType &ResTy, 138 llvm::SmallVectorImpl<CanQualType> &ArgTys); 139 140 void BuildInstanceFunctionParams(CodeGenFunction &CGF, 141 QualType &ResTy, 142 FunctionArgList &Params); 143 144 void EmitInstanceFunctionProlog(CodeGenFunction &CGF); 145 146 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy); 147 148 CharUnits GetArrayCookieSize(const CXXNewExpr *expr); 149 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF, 150 llvm::Value *NewPtr, 151 llvm::Value *NumElements, 152 const CXXNewExpr *expr, 153 QualType ElementType); 154 void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr, 155 const CXXDeleteExpr *expr, 156 QualType ElementType, llvm::Value *&NumElements, 157 llvm::Value *&AllocPtr, CharUnits &CookieSize); 158 159private: 160 /// \brief Returns true if the given instance method is one of the 161 /// kinds that the ARM ABI says returns 'this'. 162 static bool HasThisReturn(GlobalDecl GD) { 163 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 164 return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) || 165 (isa<CXXConstructorDecl>(MD))); 166 } 167}; 168} 169 170CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) { 171 return new ItaniumCXXABI(CGM); 172} 173 174CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) { 175 return new ARMCXXABI(CGM); 176} 177 178const llvm::Type * 179ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 180 if (MPT->isMemberDataPointer()) 181 return getPtrDiffTy(); 182 else 183 return llvm::StructType::get(CGM.getLLVMContext(), 184 getPtrDiffTy(), getPtrDiffTy(), NULL); 185} 186 187/// In the Itanium and ARM ABIs, method pointers have the form: 188/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr; 189/// 190/// In the Itanium ABI: 191/// - method pointers are virtual if (memptr.ptr & 1) is nonzero 192/// - the this-adjustment is (memptr.adj) 193/// - the virtual offset is (memptr.ptr - 1) 194/// 195/// In the ARM ABI: 196/// - method pointers are virtual if (memptr.adj & 1) is nonzero 197/// - the this-adjustment is (memptr.adj >> 1) 198/// - the virtual offset is (memptr.ptr) 199/// ARM uses 'adj' for the virtual flag because Thumb functions 200/// may be only single-byte aligned. 201/// 202/// If the member is virtual, the adjusted 'this' pointer points 203/// to a vtable pointer from which the virtual offset is applied. 204/// 205/// If the member is non-virtual, memptr.ptr is the address of 206/// the function to call. 207llvm::Value * 208ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 209 llvm::Value *&This, 210 llvm::Value *MemFnPtr, 211 const MemberPointerType *MPT) { 212 CGBuilderTy &Builder = CGF.Builder; 213 214 const FunctionProtoType *FPT = 215 MPT->getPointeeType()->getAs<FunctionProtoType>(); 216 const CXXRecordDecl *RD = 217 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 218 219 const llvm::FunctionType *FTy = 220 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT), 221 FPT->isVariadic()); 222 223 const llvm::IntegerType *ptrdiff = getPtrDiffTy(); 224 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1); 225 226 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual"); 227 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual"); 228 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end"); 229 230 // Extract memptr.adj, which is in the second field. 231 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj"); 232 233 // Compute the true adjustment. 234 llvm::Value *Adj = RawAdj; 235 if (IsARM) 236 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted"); 237 238 // Apply the adjustment and cast back to the original struct type 239 // for consistency. 240 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy()); 241 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj); 242 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted"); 243 244 // Load the function pointer. 245 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr"); 246 247 // If the LSB in the function pointer is 1, the function pointer points to 248 // a virtual function. 249 llvm::Value *IsVirtual; 250 if (IsARM) 251 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1); 252 else 253 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1); 254 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual"); 255 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 256 257 // In the virtual path, the adjustment left 'This' pointing to the 258 // vtable of the correct base subobject. The "function pointer" is an 259 // offset within the vtable (+1 for the virtual flag on non-ARM). 260 CGF.EmitBlock(FnVirtual); 261 262 // Cast the adjusted this to a pointer to vtable pointer and load. 263 const llvm::Type *VTableTy = Builder.getInt8PtrTy(); 264 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo()); 265 VTable = Builder.CreateLoad(VTable, "memptr.vtable"); 266 267 // Apply the offset. 268 llvm::Value *VTableOffset = FnAsInt; 269 if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1); 270 VTable = Builder.CreateGEP(VTable, VTableOffset); 271 272 // Load the virtual function to call. 273 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo()); 274 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn"); 275 CGF.EmitBranch(FnEnd); 276 277 // In the non-virtual path, the function pointer is actually a 278 // function pointer. 279 CGF.EmitBlock(FnNonVirtual); 280 llvm::Value *NonVirtualFn = 281 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn"); 282 283 // We're done. 284 CGF.EmitBlock(FnEnd); 285 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo()); 286 Callee->reserveOperandSpace(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 // FIXME: We shouldn't use / 8 here. 519 uint64_t PointerWidthInBytes = 520 getContext().Target.getPointerWidth(0) / 8; 521 uint64_t VTableOffset = (Index * PointerWidthInBytes); 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()->getAs<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), FPT->isVariadic()); 547 } else { 548 // Use an arbitrary non-function type to tell GetAddrOfFunction that the 549 // function type is incomplete. 550 Ty = ptrdiff_t; 551 } 552 553 llvm::Constant *Addr = CGM.GetAddrOfFunction(MD, Ty); 554 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(Addr, ptrdiff_t); 555 MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, 0); 556 } 557 558 return llvm::ConstantStruct::get(CGM.getLLVMContext(), 559 MemPtr, 2, /*Packed=*/false); 560} 561 562/// The comparison algorithm is pretty easy: the member pointers are 563/// the same if they're either bitwise identical *or* both null. 564/// 565/// ARM is different here only because null-ness is more complicated. 566llvm::Value * 567ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 568 llvm::Value *L, 569 llvm::Value *R, 570 const MemberPointerType *MPT, 571 bool Inequality) { 572 CGBuilderTy &Builder = CGF.Builder; 573 574 llvm::ICmpInst::Predicate Eq; 575 llvm::Instruction::BinaryOps And, Or; 576 if (Inequality) { 577 Eq = llvm::ICmpInst::ICMP_NE; 578 And = llvm::Instruction::Or; 579 Or = llvm::Instruction::And; 580 } else { 581 Eq = llvm::ICmpInst::ICMP_EQ; 582 And = llvm::Instruction::And; 583 Or = llvm::Instruction::Or; 584 } 585 586 // Member data pointers are easy because there's a unique null 587 // value, so it just comes down to bitwise equality. 588 if (MPT->isMemberDataPointer()) 589 return Builder.CreateICmp(Eq, L, R); 590 591 // For member function pointers, the tautologies are more complex. 592 // The Itanium tautology is: 593 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj)) 594 // The ARM tautology is: 595 // (L == R) <==> (L.ptr == R.ptr && 596 // (L.adj == R.adj || 597 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0))) 598 // The inequality tautologies have exactly the same structure, except 599 // applying De Morgan's laws. 600 601 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr"); 602 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr"); 603 604 // This condition tests whether L.ptr == R.ptr. This must always be 605 // true for equality to hold. 606 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr"); 607 608 // This condition, together with the assumption that L.ptr == R.ptr, 609 // tests whether the pointers are both null. ARM imposes an extra 610 // condition. 611 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType()); 612 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null"); 613 614 // This condition tests whether L.adj == R.adj. If this isn't 615 // true, the pointers are unequal unless they're both null. 616 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj"); 617 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj"); 618 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj"); 619 620 // Null member function pointers on ARM clear the low bit of Adj, 621 // so the zero condition has to check that neither low bit is set. 622 if (IsARM) { 623 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1); 624 625 // Compute (l.adj | r.adj) & 1 and test it against zero. 626 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj"); 627 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One); 628 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero, 629 "cmp.or.adj"); 630 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero); 631 } 632 633 // Tie together all our conditions. 634 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq); 635 Result = Builder.CreateBinOp(And, PtrEq, Result, 636 Inequality ? "memptr.ne" : "memptr.eq"); 637 return Result; 638} 639 640llvm::Value * 641ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 642 llvm::Value *MemPtr, 643 const MemberPointerType *MPT) { 644 CGBuilderTy &Builder = CGF.Builder; 645 646 /// For member data pointers, this is just a check against -1. 647 if (MPT->isMemberDataPointer()) { 648 assert(MemPtr->getType() == getPtrDiffTy()); 649 llvm::Value *NegativeOne = 650 llvm::Constant::getAllOnesValue(MemPtr->getType()); 651 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool"); 652 } 653 654 // In Itanium, a member function pointer is null if 'ptr' is null. 655 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr"); 656 657 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0); 658 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool"); 659 660 // In ARM, it's that, plus the low bit of 'adj' must be zero. 661 if (IsARM) { 662 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1); 663 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj"); 664 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit"); 665 llvm::Value *IsNotVirtual = Builder.CreateICmpEQ(VirtualBit, Zero, 666 "memptr.notvirtual"); 667 Result = Builder.CreateAnd(Result, IsNotVirtual); 668 } 669 670 return Result; 671} 672 673/// The Itanium ABI requires non-zero initialization only for data 674/// member pointers, for which '0' is a valid offset. 675bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 676 return MPT->getPointeeType()->isFunctionType(); 677} 678 679/// The generic ABI passes 'this', plus a VTT if it's initializing a 680/// base subobject. 681void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 682 CXXCtorType Type, 683 CanQualType &ResTy, 684 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 685 ASTContext &Context = getContext(); 686 687 // 'this' is already there. 688 689 // Check if we need to add a VTT parameter (which has type void **). 690 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0) 691 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 692} 693 694/// The ARM ABI does the same as the Itanium ABI, but returns 'this'. 695void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor, 696 CXXCtorType Type, 697 CanQualType &ResTy, 698 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 699 ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys); 700 ResTy = ArgTys[0]; 701} 702 703/// The generic ABI passes 'this', plus a VTT if it's destroying a 704/// base subobject. 705void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 706 CXXDtorType Type, 707 CanQualType &ResTy, 708 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 709 ASTContext &Context = getContext(); 710 711 // 'this' is already there. 712 713 // Check if we need to add a VTT parameter (which has type void **). 714 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0) 715 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy)); 716} 717 718/// The ARM ABI does the same as the Itanium ABI, but returns 'this' 719/// for non-deleting destructors. 720void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor, 721 CXXDtorType Type, 722 CanQualType &ResTy, 723 llvm::SmallVectorImpl<CanQualType> &ArgTys) { 724 ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys); 725 726 if (Type != Dtor_Deleting) 727 ResTy = ArgTys[0]; 728} 729 730void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 731 QualType &ResTy, 732 FunctionArgList &Params) { 733 /// Create the 'this' variable. 734 BuildThisParam(CGF, Params); 735 736 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 737 assert(MD->isInstance()); 738 739 // Check if we need a VTT parameter as well. 740 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) { 741 ASTContext &Context = getContext(); 742 743 // FIXME: avoid the fake decl 744 QualType T = Context.getPointerType(Context.VoidPtrTy); 745 ImplicitParamDecl *VTTDecl 746 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(), 747 &Context.Idents.get("vtt"), T); 748 Params.push_back(std::make_pair(VTTDecl, VTTDecl->getType())); 749 getVTTDecl(CGF) = VTTDecl; 750 } 751} 752 753void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF, 754 QualType &ResTy, 755 FunctionArgList &Params) { 756 ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params); 757 758 // Return 'this' from certain constructors and destructors. 759 if (HasThisReturn(CGF.CurGD)) 760 ResTy = Params[0].second; 761} 762 763void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 764 /// Initialize the 'this' slot. 765 EmitThisParam(CGF); 766 767 /// Initialize the 'vtt' slot if needed. 768 if (getVTTDecl(CGF)) { 769 getVTTValue(CGF) 770 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)), 771 "vtt"); 772 } 773} 774 775void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) { 776 ItaniumCXXABI::EmitInstanceFunctionProlog(CGF); 777 778 /// Initialize the return slot to 'this' at the start of the 779 /// function. 780 if (HasThisReturn(CGF.CurGD)) 781 CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue); 782} 783 784void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 785 RValue RV, QualType ResultType) { 786 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl())) 787 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType); 788 789 // Destructor thunks in the ARM ABI have indeterminate results. 790 const llvm::Type *T = 791 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType(); 792 RValue Undef = RValue::get(llvm::UndefValue::get(T)); 793 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType); 794} 795 796/************************** Array allocation cookies **************************/ 797 798bool ItaniumCXXABI::NeedsArrayCookie(const CXXNewExpr *expr) { 799 // If the class's usual deallocation function takes two arguments, 800 // it needs a cookie. 801 if (expr->doesUsualArrayDeleteWantSize()) 802 return true; 803 804 // Otherwise, if the class has a non-trivial destructor, it always 805 // needs a cookie. 806 const CXXRecordDecl *record = 807 expr->getAllocatedType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 808 return (record && !record->hasTrivialDestructor()); 809} 810 811bool ItaniumCXXABI::NeedsArrayCookie(const CXXDeleteExpr *expr, 812 QualType elementType) { 813 // If the class's usual deallocation function takes two arguments, 814 // it needs a cookie. 815 if (expr->doesUsualArrayDeleteWantSize()) 816 return true; 817 818 // Otherwise, if the class has a non-trivial destructor, it always 819 // needs a cookie. 820 const CXXRecordDecl *record = 821 elementType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 822 return (record && !record->hasTrivialDestructor()); 823} 824 825CharUnits ItaniumCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { 826 if (!NeedsArrayCookie(expr)) 827 return CharUnits::Zero(); 828 829 // Padding is the maximum of sizeof(size_t) and alignof(elementType) 830 ASTContext &Ctx = getContext(); 831 return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()), 832 Ctx.getTypeAlignInChars(expr->getAllocatedType())); 833} 834 835llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 836 llvm::Value *NewPtr, 837 llvm::Value *NumElements, 838 const CXXNewExpr *expr, 839 QualType ElementType) { 840 assert(NeedsArrayCookie(expr)); 841 842 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace(); 843 844 ASTContext &Ctx = getContext(); 845 QualType SizeTy = Ctx.getSizeType(); 846 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy); 847 848 // The size of the cookie. 849 CharUnits CookieSize = 850 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType)); 851 852 // Compute an offset to the cookie. 853 llvm::Value *CookiePtr = NewPtr; 854 CharUnits CookieOffset = CookieSize - SizeSize; 855 if (!CookieOffset.isZero()) 856 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr, 857 CookieOffset.getQuantity()); 858 859 // Write the number of elements into the appropriate slot. 860 llvm::Value *NumElementsPtr 861 = CGF.Builder.CreateBitCast(CookiePtr, 862 CGF.ConvertType(SizeTy)->getPointerTo(AS)); 863 CGF.Builder.CreateStore(NumElements, NumElementsPtr); 864 865 // Finally, compute a pointer to the actual data buffer by skipping 866 // over the cookie completely. 867 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 868 CookieSize.getQuantity()); 869} 870 871void ItaniumCXXABI::ReadArrayCookie(CodeGenFunction &CGF, 872 llvm::Value *Ptr, 873 const CXXDeleteExpr *expr, 874 QualType ElementType, 875 llvm::Value *&NumElements, 876 llvm::Value *&AllocPtr, 877 CharUnits &CookieSize) { 878 // Derive a char* in the same address space as the pointer. 879 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 880 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS); 881 882 // If we don't need an array cookie, bail out early. 883 if (!NeedsArrayCookie(expr, ElementType)) { 884 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 885 NumElements = 0; 886 CookieSize = CharUnits::Zero(); 887 return; 888 } 889 890 QualType SizeTy = getContext().getSizeType(); 891 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy); 892 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy); 893 894 CookieSize 895 = std::max(SizeSize, getContext().getTypeAlignInChars(ElementType)); 896 897 CharUnits NumElementsOffset = CookieSize - SizeSize; 898 899 // Compute the allocated pointer. 900 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 901 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 902 -CookieSize.getQuantity()); 903 904 llvm::Value *NumElementsPtr = AllocPtr; 905 if (!NumElementsOffset.isZero()) 906 NumElementsPtr = 907 CGF.Builder.CreateConstInBoundsGEP1_64(NumElementsPtr, 908 NumElementsOffset.getQuantity()); 909 NumElementsPtr = 910 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS)); 911 NumElements = CGF.Builder.CreateLoad(NumElementsPtr); 912} 913 914CharUnits ARMCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) { 915 if (!NeedsArrayCookie(expr)) 916 return CharUnits::Zero(); 917 918 // On ARM, the cookie is always: 919 // struct array_cookie { 920 // std::size_t element_size; // element_size != 0 921 // std::size_t element_count; 922 // }; 923 // TODO: what should we do if the allocated type actually wants 924 // greater alignment? 925 return getContext().getTypeSizeInChars(getContext().getSizeType()) * 2; 926} 927 928llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 929 llvm::Value *NewPtr, 930 llvm::Value *NumElements, 931 const CXXNewExpr *expr, 932 QualType ElementType) { 933 assert(NeedsArrayCookie(expr)); 934 935 // NewPtr is a char*. 936 937 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace(); 938 939 ASTContext &Ctx = getContext(); 940 CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType()); 941 const llvm::IntegerType *SizeTy = 942 cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType())); 943 944 // The cookie is always at the start of the buffer. 945 llvm::Value *CookiePtr = NewPtr; 946 947 // The first element is the element size. 948 CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS)); 949 llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy, 950 Ctx.getTypeSizeInChars(ElementType).getQuantity()); 951 CGF.Builder.CreateStore(ElementSize, CookiePtr); 952 953 // The second element is the element count. 954 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1); 955 CGF.Builder.CreateStore(NumElements, CookiePtr); 956 957 // Finally, compute a pointer to the actual data buffer by skipping 958 // over the cookie completely. 959 CharUnits CookieSize = 2 * SizeSize; 960 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr, 961 CookieSize.getQuantity()); 962} 963 964void ARMCXXABI::ReadArrayCookie(CodeGenFunction &CGF, 965 llvm::Value *Ptr, 966 const CXXDeleteExpr *expr, 967 QualType ElementType, 968 llvm::Value *&NumElements, 969 llvm::Value *&AllocPtr, 970 CharUnits &CookieSize) { 971 // Derive a char* in the same address space as the pointer. 972 unsigned AS = cast<llvm::PointerType>(Ptr->getType())->getAddressSpace(); 973 const llvm::Type *CharPtrTy = CGF.Builder.getInt8Ty()->getPointerTo(AS); 974 975 // If we don't need an array cookie, bail out early. 976 if (!NeedsArrayCookie(expr, ElementType)) { 977 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 978 NumElements = 0; 979 CookieSize = CharUnits::Zero(); 980 return; 981 } 982 983 QualType SizeTy = getContext().getSizeType(); 984 CharUnits SizeSize = getContext().getTypeSizeInChars(SizeTy); 985 const llvm::Type *SizeLTy = CGF.ConvertType(SizeTy); 986 987 // The cookie size is always 2 * sizeof(size_t). 988 CookieSize = 2 * SizeSize; 989 990 // The allocated pointer is the input ptr, minus that amount. 991 AllocPtr = CGF.Builder.CreateBitCast(Ptr, CharPtrTy); 992 AllocPtr = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 993 -CookieSize.getQuantity()); 994 995 // The number of elements is at offset sizeof(size_t) relative to that. 996 llvm::Value *NumElementsPtr 997 = CGF.Builder.CreateConstInBoundsGEP1_64(AllocPtr, 998 SizeSize.getQuantity()); 999 NumElementsPtr = 1000 CGF.Builder.CreateBitCast(NumElementsPtr, SizeLTy->getPointerTo(AS)); 1001 NumElements = CGF.Builder.CreateLoad(NumElementsPtr); 1002} 1003 1004/*********************** Static local initialization **************************/ 1005 1006static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM, 1007 const llvm::PointerType *GuardPtrTy) { 1008 // int __cxa_guard_acquire(__guard *guard_object); 1009 1010 std::vector<const llvm::Type*> Args(1, GuardPtrTy); 1011 const llvm::FunctionType *FTy = 1012 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy), 1013 Args, /*isVarArg=*/false); 1014 1015 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire"); 1016} 1017 1018static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM, 1019 const llvm::PointerType *GuardPtrTy) { 1020 // void __cxa_guard_release(__guard *guard_object); 1021 1022 std::vector<const llvm::Type*> Args(1, GuardPtrTy); 1023 1024 const llvm::FunctionType *FTy = 1025 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 1026 Args, /*isVarArg=*/false); 1027 1028 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release"); 1029} 1030 1031static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM, 1032 const llvm::PointerType *GuardPtrTy) { 1033 // void __cxa_guard_abort(__guard *guard_object); 1034 1035 std::vector<const llvm::Type*> Args(1, GuardPtrTy); 1036 1037 const llvm::FunctionType *FTy = 1038 llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 1039 Args, /*isVarArg=*/false); 1040 1041 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort"); 1042} 1043 1044namespace { 1045 struct CallGuardAbort : EHScopeStack::Cleanup { 1046 llvm::GlobalVariable *Guard; 1047 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {} 1048 1049 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1050 CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard) 1051 ->setDoesNotThrow(); 1052 } 1053 }; 1054} 1055 1056/// The ARM code here follows the Itanium code closely enough that we 1057/// just special-case it at particular places. 1058void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF, 1059 const VarDecl &D, 1060 llvm::GlobalVariable *GV) { 1061 CGBuilderTy &Builder = CGF.Builder; 1062 1063 // We only need to use thread-safe statics for local variables; 1064 // global initialization is always single-threaded. 1065 bool ThreadsafeStatics = (getContext().getLangOptions().ThreadsafeStatics && 1066 D.isLocalVarDecl()); 1067 1068 // Guard variables are 64 bits in the generic ABI and 32 bits on ARM. 1069 const llvm::IntegerType *GuardTy 1070 = (IsARM ? Builder.getInt32Ty() : Builder.getInt64Ty()); 1071 const llvm::PointerType *GuardPtrTy = GuardTy->getPointerTo(); 1072 1073 // Create the guard variable. 1074 llvm::SmallString<256> GuardVName; 1075 llvm::raw_svector_ostream Out(GuardVName); 1076 getMangleContext().mangleItaniumGuardVariable(&D, Out); 1077 Out.flush(); 1078 1079 // Just absorb linkage and visibility from the variable. 1080 llvm::GlobalVariable *GuardVariable = 1081 new llvm::GlobalVariable(CGM.getModule(), GuardTy, 1082 false, GV->getLinkage(), 1083 llvm::ConstantInt::get(GuardTy, 0), 1084 GuardVName.str()); 1085 GuardVariable->setVisibility(GV->getVisibility()); 1086 1087 // Test whether the variable has completed initialization. 1088 llvm::Value *IsInitialized; 1089 1090 // ARM C++ ABI 3.2.3.1: 1091 // To support the potential use of initialization guard variables 1092 // as semaphores that are the target of ARM SWP and LDREX/STREX 1093 // synchronizing instructions we define a static initialization 1094 // guard variable to be a 4-byte aligned, 4- byte word with the 1095 // following inline access protocol. 1096 // #define INITIALIZED 1 1097 // if ((obj_guard & INITIALIZED) != INITIALIZED) { 1098 // if (__cxa_guard_acquire(&obj_guard)) 1099 // ... 1100 // } 1101 if (IsARM) { 1102 llvm::Value *V = Builder.CreateLoad(GuardVariable); 1103 V = Builder.CreateAnd(V, Builder.getInt32(1)); 1104 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1105 1106 // Itanium C++ ABI 3.3.2: 1107 // The following is pseudo-code showing how these functions can be used: 1108 // if (obj_guard.first_byte == 0) { 1109 // if ( __cxa_guard_acquire (&obj_guard) ) { 1110 // try { 1111 // ... initialize the object ...; 1112 // } catch (...) { 1113 // __cxa_guard_abort (&obj_guard); 1114 // throw; 1115 // } 1116 // ... queue object destructor with __cxa_atexit() ...; 1117 // __cxa_guard_release (&obj_guard); 1118 // } 1119 // } 1120 } else { 1121 // Load the first byte of the guard variable. 1122 const llvm::Type *PtrTy = Builder.getInt8PtrTy(); 1123 llvm::Value *V = 1124 Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy), "tmp"); 1125 1126 IsInitialized = Builder.CreateIsNull(V, "guard.uninitialized"); 1127 } 1128 1129 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check"); 1130 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end"); 1131 1132 // Check if the first byte of the guard variable is zero. 1133 Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock); 1134 1135 CGF.EmitBlock(InitCheckBlock); 1136 1137 // Variables used when coping with thread-safe statics and exceptions. 1138 if (ThreadsafeStatics) { 1139 // Call __cxa_guard_acquire. 1140 llvm::Value *V 1141 = Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVariable); 1142 1143 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init"); 1144 1145 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"), 1146 InitBlock, EndBlock); 1147 1148 // Call __cxa_guard_abort along the exceptional edge. 1149 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable); 1150 1151 CGF.EmitBlock(InitBlock); 1152 } 1153 1154 // Emit the initializer and add a global destructor if appropriate. 1155 CGF.EmitCXXGlobalVarDeclInit(D, GV); 1156 1157 if (ThreadsafeStatics) { 1158 // Pop the guard-abort cleanup if we pushed one. 1159 CGF.PopCleanupBlock(); 1160 1161 // Call __cxa_guard_release. This cannot throw. 1162 Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable); 1163 } else { 1164 Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable); 1165 } 1166 1167 CGF.EmitBlock(EndBlock); 1168} 1169