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