1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
13 // http://www.codesourcery.com/public/cxx-abi/abi.html
14 // http://www.codesourcery.com/public/cxx-abi/abi-eh.html
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
19 //===----------------------------------------------------------------------===//
22 #include "CGRecordLayout.h"
23 #include "CGVTables.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenModule.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/AST/Type.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Value.h"
32 using namespace clang;
33 using namespace CodeGen;
36 class ItaniumCXXABI : public CodeGen::CGCXXABI {
37 /// VTables - All the vtables which have been defined.
38 llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
41 bool UseARMMethodPtrABI;
42 bool UseARMGuardVarABI;
44 ItaniumMangleContext &getMangleContext() {
45 return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
49 ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
50 bool UseARMMethodPtrABI = false,
51 bool UseARMGuardVarABI = false) :
52 CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
53 UseARMGuardVarABI(UseARMGuardVarABI) { }
55 bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
56 // Structures with either a non-trivial destructor or a non-trivial
57 // copy constructor are always indirect.
58 return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
61 RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
62 // Structures with either a non-trivial destructor or a non-trivial
63 // copy constructor are always indirect.
64 if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
69 bool isZeroInitializable(const MemberPointerType *MPT);
71 llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
73 llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
75 llvm::Value *MemFnPtr,
76 const MemberPointerType *MPT);
78 llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
81 const MemberPointerType *MPT);
83 llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86 llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
89 llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
91 llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
92 llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
94 llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
95 llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
96 CharUnits ThisAdjustment);
98 llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
101 const MemberPointerType *MPT,
104 llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
106 const MemberPointerType *MPT);
108 llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
112 llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
114 const CXXRecordDecl *ClassDecl,
115 const CXXRecordDecl *BaseClassDecl);
117 void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
120 SmallVectorImpl<CanQualType> &ArgTys);
122 void EmitCXXConstructors(const CXXConstructorDecl *D);
124 void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
127 SmallVectorImpl<CanQualType> &ArgTys);
129 bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
130 CXXDtorType DT) const {
131 // Itanium does not emit any destructor variant as an inline thunk.
132 // Delegating may occur as an optimization, but all variants are either
133 // emitted with external linkage or as linkonce if they are inline and used.
137 void EmitCXXDestructors(const CXXDestructorDecl *D);
139 void BuildInstanceFunctionParams(CodeGenFunction &CGF,
141 FunctionArgList &Params);
143 void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
145 void EmitConstructorCall(CodeGenFunction &CGF,
146 const CXXConstructorDecl *D, CXXCtorType Type,
147 bool ForVirtualBase, bool Delegating,
149 CallExpr::const_arg_iterator ArgBeg,
150 CallExpr::const_arg_iterator ArgEnd);
152 void emitVTableDefinitions(CodeGenVTables &CGVT, const CXXRecordDecl *RD);
154 llvm::Value *getVTableAddressPointInStructor(
155 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
156 BaseSubobject Base, const CXXRecordDecl *NearestVBase,
157 bool &NeedsVirtualOffset);
160 getVTableAddressPointForConstExpr(BaseSubobject Base,
161 const CXXRecordDecl *VTableClass);
163 llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
164 CharUnits VPtrOffset);
166 llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
167 llvm::Value *This, llvm::Type *Ty);
169 void EmitVirtualDestructorCall(CodeGenFunction &CGF,
170 const CXXDestructorDecl *Dtor,
171 CXXDtorType DtorType, SourceLocation CallLoc,
174 void emitVirtualInheritanceTables(const CXXRecordDecl *RD);
176 void setThunkLinkage(llvm::Function *Thunk, bool ForVTable) {
177 // Allow inlining of thunks by emitting them with available_externally
178 // linkage together with vtables when needed.
180 Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
183 llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
184 const ThisAdjustment &TA);
186 llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
187 const ReturnAdjustment &RA);
189 StringRef GetPureVirtualCallName() { return "__cxa_pure_virtual"; }
190 StringRef GetDeletedVirtualCallName() { return "__cxa_deleted_virtual"; }
192 CharUnits getArrayCookieSizeImpl(QualType elementType);
193 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
195 llvm::Value *NumElements,
196 const CXXNewExpr *expr,
197 QualType ElementType);
198 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
199 llvm::Value *allocPtr,
200 CharUnits cookieSize);
202 void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
203 llvm::GlobalVariable *DeclPtr, bool PerformInit);
204 void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
205 llvm::Constant *dtor, llvm::Constant *addr);
207 llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
208 llvm::GlobalVariable *Var);
209 void EmitThreadLocalInitFuncs(
210 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
211 llvm::Function *InitFunc);
212 LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
213 const DeclRefExpr *DRE);
215 bool NeedsVTTParameter(GlobalDecl GD);
218 class ARMCXXABI : public ItaniumCXXABI {
220 ARMCXXABI(CodeGen::CodeGenModule &CGM) :
221 ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
222 /* UseARMGuardVarABI = */ true) {}
224 bool HasThisReturn(GlobalDecl GD) const {
225 return (isa<CXXConstructorDecl>(GD.getDecl()) || (
226 isa<CXXDestructorDecl>(GD.getDecl()) &&
227 GD.getDtorType() != Dtor_Deleting));
230 void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
232 CharUnits getArrayCookieSizeImpl(QualType elementType);
233 llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
235 llvm::Value *NumElements,
236 const CXXNewExpr *expr,
237 QualType ElementType);
238 llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
239 CharUnits cookieSize);
243 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
244 switch (CGM.getTarget().getCXXABI().getKind()) {
245 // For IR-generation purposes, there's no significant difference
246 // between the ARM and iOS ABIs.
247 case TargetCXXABI::GenericARM:
248 case TargetCXXABI::iOS:
249 return new ARMCXXABI(CGM);
251 // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
252 // include the other 32-bit ARM oddities: constructor/destructor return values
253 // and array cookies.
254 case TargetCXXABI::GenericAArch64:
255 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
256 /* UseARMGuardVarABI = */ true);
258 case TargetCXXABI::GenericItanium:
259 if (CGM.getContext().getTargetInfo().getTriple().getArch()
260 == llvm::Triple::le32) {
261 // For PNaCl, use ARM-style method pointers so that PNaCl code
262 // does not assume anything about the alignment of function
264 return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
265 /* UseARMGuardVarABI = */ false);
267 return new ItaniumCXXABI(CGM);
269 case TargetCXXABI::Microsoft:
270 llvm_unreachable("Microsoft ABI is not Itanium-based");
272 llvm_unreachable("bad ABI kind");
276 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
277 if (MPT->isMemberDataPointer())
278 return CGM.PtrDiffTy;
279 return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
282 /// In the Itanium and ARM ABIs, method pointers have the form:
283 /// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
285 /// In the Itanium ABI:
286 /// - method pointers are virtual if (memptr.ptr & 1) is nonzero
287 /// - the this-adjustment is (memptr.adj)
288 /// - the virtual offset is (memptr.ptr - 1)
291 /// - method pointers are virtual if (memptr.adj & 1) is nonzero
292 /// - the this-adjustment is (memptr.adj >> 1)
293 /// - the virtual offset is (memptr.ptr)
294 /// ARM uses 'adj' for the virtual flag because Thumb functions
295 /// may be only single-byte aligned.
297 /// If the member is virtual, the adjusted 'this' pointer points
298 /// to a vtable pointer from which the virtual offset is applied.
300 /// If the member is non-virtual, memptr.ptr is the address of
301 /// the function to call.
303 ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
305 llvm::Value *MemFnPtr,
306 const MemberPointerType *MPT) {
307 CGBuilderTy &Builder = CGF.Builder;
309 const FunctionProtoType *FPT =
310 MPT->getPointeeType()->getAs<FunctionProtoType>();
311 const CXXRecordDecl *RD =
312 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
314 llvm::FunctionType *FTy =
315 CGM.getTypes().GetFunctionType(
316 CGM.getTypes().arrangeCXXMethodType(RD, FPT));
318 llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
320 llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
321 llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
322 llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
324 // Extract memptr.adj, which is in the second field.
325 llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
327 // Compute the true adjustment.
328 llvm::Value *Adj = RawAdj;
329 if (UseARMMethodPtrABI)
330 Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
332 // Apply the adjustment and cast back to the original struct type
334 llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
335 Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
336 This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
338 // Load the function pointer.
339 llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
341 // If the LSB in the function pointer is 1, the function pointer points to
342 // a virtual function.
343 llvm::Value *IsVirtual;
344 if (UseARMMethodPtrABI)
345 IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
347 IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
348 IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
349 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
351 // In the virtual path, the adjustment left 'This' pointing to the
352 // vtable of the correct base subobject. The "function pointer" is an
353 // offset within the vtable (+1 for the virtual flag on non-ARM).
354 CGF.EmitBlock(FnVirtual);
356 // Cast the adjusted this to a pointer to vtable pointer and load.
357 llvm::Type *VTableTy = Builder.getInt8PtrTy();
358 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
359 VTable = Builder.CreateLoad(VTable, "memptr.vtable");
362 llvm::Value *VTableOffset = FnAsInt;
363 if (!UseARMMethodPtrABI)
364 VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
365 VTable = Builder.CreateGEP(VTable, VTableOffset);
367 // Load the virtual function to call.
368 VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
369 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
370 CGF.EmitBranch(FnEnd);
372 // In the non-virtual path, the function pointer is actually a
374 CGF.EmitBlock(FnNonVirtual);
375 llvm::Value *NonVirtualFn =
376 Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
379 CGF.EmitBlock(FnEnd);
380 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
381 Callee->addIncoming(VirtualFn, FnVirtual);
382 Callee->addIncoming(NonVirtualFn, FnNonVirtual);
386 /// Compute an l-value by applying the given pointer-to-member to a
388 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
391 const MemberPointerType *MPT) {
392 assert(MemPtr->getType() == CGM.PtrDiffTy);
394 CGBuilderTy &Builder = CGF.Builder;
396 unsigned AS = Base->getType()->getPointerAddressSpace();
399 Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
401 // Apply the offset, which we assume is non-null.
402 llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
404 // Cast the address to the appropriate pointer type, adopting the
405 // address space of the base pointer.
407 = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
408 return Builder.CreateBitCast(Addr, PType);
411 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
414 /// Bitcast conversions are always a no-op under Itanium.
416 /// Obligatory offset/adjustment diagram:
417 /// <-- offset --> <-- adjustment -->
418 /// |--------------------------|----------------------|--------------------|
419 /// ^Derived address point ^Base address point ^Member address point
421 /// So when converting a base member pointer to a derived member pointer,
422 /// we add the offset to the adjustment because the address point has
423 /// decreased; and conversely, when converting a derived MP to a base MP
424 /// we subtract the offset from the adjustment because the address point
427 /// The standard forbids (at compile time) conversion to and from
428 /// virtual bases, which is why we don't have to consider them here.
430 /// The standard forbids (at run time) casting a derived MP to a base
431 /// MP when the derived MP does not point to a member of the base.
432 /// This is why -1 is a reasonable choice for null data member
435 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
438 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
439 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
440 E->getCastKind() == CK_ReinterpretMemberPointer);
442 // Under Itanium, reinterprets don't require any additional processing.
443 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
445 // Use constant emission if we can.
446 if (isa<llvm::Constant>(src))
447 return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
449 llvm::Constant *adj = getMemberPointerAdjustment(E);
450 if (!adj) return src;
452 CGBuilderTy &Builder = CGF.Builder;
453 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
455 const MemberPointerType *destTy =
456 E->getType()->castAs<MemberPointerType>();
458 // For member data pointers, this is just a matter of adding the
459 // offset if the source is non-null.
460 if (destTy->isMemberDataPointer()) {
463 dst = Builder.CreateNSWSub(src, adj, "adj");
465 dst = Builder.CreateNSWAdd(src, adj, "adj");
468 llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
469 llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
470 return Builder.CreateSelect(isNull, src, dst);
473 // The this-adjustment is left-shifted by 1 on ARM.
474 if (UseARMMethodPtrABI) {
475 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
477 adj = llvm::ConstantInt::get(adj->getType(), offset);
480 llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
483 dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
485 dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
487 return Builder.CreateInsertValue(src, dstAdj, 1);
491 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
492 llvm::Constant *src) {
493 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
494 E->getCastKind() == CK_BaseToDerivedMemberPointer ||
495 E->getCastKind() == CK_ReinterpretMemberPointer);
497 // Under Itanium, reinterprets don't require any additional processing.
498 if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
500 // If the adjustment is trivial, we don't need to do anything.
501 llvm::Constant *adj = getMemberPointerAdjustment(E);
502 if (!adj) return src;
504 bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
506 const MemberPointerType *destTy =
507 E->getType()->castAs<MemberPointerType>();
509 // For member data pointers, this is just a matter of adding the
510 // offset if the source is non-null.
511 if (destTy->isMemberDataPointer()) {
512 // null maps to null.
513 if (src->isAllOnesValue()) return src;
516 return llvm::ConstantExpr::getNSWSub(src, adj);
518 return llvm::ConstantExpr::getNSWAdd(src, adj);
521 // The this-adjustment is left-shifted by 1 on ARM.
522 if (UseARMMethodPtrABI) {
523 uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
525 adj = llvm::ConstantInt::get(adj->getType(), offset);
528 llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
529 llvm::Constant *dstAdj;
531 dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
533 dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
535 return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
539 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
540 // Itanium C++ ABI 2.3:
541 // A NULL pointer is represented as -1.
542 if (MPT->isMemberDataPointer())
543 return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
545 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
546 llvm::Constant *Values[2] = { Zero, Zero };
547 return llvm::ConstantStruct::getAnon(Values);
551 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
553 // Itanium C++ ABI 2.3:
554 // A pointer to data member is an offset from the base address of
555 // the class object containing it, represented as a ptrdiff_t
556 return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
559 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
560 return BuildMemberPointer(MD, CharUnits::Zero());
563 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
564 CharUnits ThisAdjustment) {
565 assert(MD->isInstance() && "Member function must not be static!");
566 MD = MD->getCanonicalDecl();
568 CodeGenTypes &Types = CGM.getTypes();
570 // Get the function pointer (or index if this is a virtual function).
571 llvm::Constant *MemPtr[2];
572 if (MD->isVirtual()) {
573 uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
575 const ASTContext &Context = getContext();
576 CharUnits PointerWidth =
577 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
578 uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
580 if (UseARMMethodPtrABI) {
581 // ARM C++ ABI 3.2.1:
582 // This ABI specifies that adj contains twice the this
583 // adjustment, plus 1 if the member function is virtual. The
584 // least significant bit of adj then makes exactly the same
585 // discrimination as the least significant bit of ptr does for
587 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
588 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
589 2 * ThisAdjustment.getQuantity() + 1);
591 // Itanium C++ ABI 2.3:
592 // For a virtual function, [the pointer field] is 1 plus the
593 // virtual table offset (in bytes) of the function,
594 // represented as a ptrdiff_t.
595 MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
596 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
597 ThisAdjustment.getQuantity());
600 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
602 // Check whether the function has a computable LLVM signature.
603 if (Types.isFuncTypeConvertible(FPT)) {
604 // The function has a computable LLVM signature; use the correct type.
605 Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
607 // Use an arbitrary non-function type to tell GetAddrOfFunction that the
608 // function type is incomplete.
611 llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
613 MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
614 MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
615 (UseARMMethodPtrABI ? 2 : 1) *
616 ThisAdjustment.getQuantity());
619 return llvm::ConstantStruct::getAnon(MemPtr);
622 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
624 const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
625 const ValueDecl *MPD = MP.getMemberPointerDecl();
627 return EmitNullMemberPointer(MPT);
629 CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
632 return BuildMemberPointer(MD, ThisAdjustment);
634 CharUnits FieldOffset =
635 getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
636 return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
639 /// The comparison algorithm is pretty easy: the member pointers are
640 /// the same if they're either bitwise identical *or* both null.
642 /// ARM is different here only because null-ness is more complicated.
644 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
647 const MemberPointerType *MPT,
649 CGBuilderTy &Builder = CGF.Builder;
651 llvm::ICmpInst::Predicate Eq;
652 llvm::Instruction::BinaryOps And, Or;
654 Eq = llvm::ICmpInst::ICMP_NE;
655 And = llvm::Instruction::Or;
656 Or = llvm::Instruction::And;
658 Eq = llvm::ICmpInst::ICMP_EQ;
659 And = llvm::Instruction::And;
660 Or = llvm::Instruction::Or;
663 // Member data pointers are easy because there's a unique null
664 // value, so it just comes down to bitwise equality.
665 if (MPT->isMemberDataPointer())
666 return Builder.CreateICmp(Eq, L, R);
668 // For member function pointers, the tautologies are more complex.
669 // The Itanium tautology is:
670 // (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
671 // The ARM tautology is:
672 // (L == R) <==> (L.ptr == R.ptr &&
673 // (L.adj == R.adj ||
674 // (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
675 // The inequality tautologies have exactly the same structure, except
676 // applying De Morgan's laws.
678 llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
679 llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
681 // This condition tests whether L.ptr == R.ptr. This must always be
682 // true for equality to hold.
683 llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
685 // This condition, together with the assumption that L.ptr == R.ptr,
686 // tests whether the pointers are both null. ARM imposes an extra
688 llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
689 llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
691 // This condition tests whether L.adj == R.adj. If this isn't
692 // true, the pointers are unequal unless they're both null.
693 llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
694 llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
695 llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
697 // Null member function pointers on ARM clear the low bit of Adj,
698 // so the zero condition has to check that neither low bit is set.
699 if (UseARMMethodPtrABI) {
700 llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
702 // Compute (l.adj | r.adj) & 1 and test it against zero.
703 llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
704 llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
705 llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
707 EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
710 // Tie together all our conditions.
711 llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
712 Result = Builder.CreateBinOp(And, PtrEq, Result,
713 Inequality ? "memptr.ne" : "memptr.eq");
718 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
720 const MemberPointerType *MPT) {
721 CGBuilderTy &Builder = CGF.Builder;
723 /// For member data pointers, this is just a check against -1.
724 if (MPT->isMemberDataPointer()) {
725 assert(MemPtr->getType() == CGM.PtrDiffTy);
726 llvm::Value *NegativeOne =
727 llvm::Constant::getAllOnesValue(MemPtr->getType());
728 return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
731 // In Itanium, a member function pointer is not null if 'ptr' is not null.
732 llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
734 llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
735 llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
737 // On ARM, a member function pointer is also non-null if the low bit of 'adj'
738 // (the virtual bit) is set.
739 if (UseARMMethodPtrABI) {
740 llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
741 llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
742 llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
743 llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
745 Result = Builder.CreateOr(Result, IsVirtual);
751 /// The Itanium ABI requires non-zero initialization only for data
752 /// member pointers, for which '0' is a valid offset.
753 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
754 return MPT->getPointeeType()->isFunctionType();
757 /// The Itanium ABI always places an offset to the complete object
758 /// at entry -2 in the vtable.
759 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
762 // Grab the vtable pointer as an intptr_t*.
763 llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
765 // Track back to entry -2 and pull out the offset there.
766 llvm::Value *offsetPtr =
767 CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
768 llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
769 offset->setAlignment(CGF.PointerAlignInBytes);
772 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
773 return CGF.Builder.CreateInBoundsGEP(ptr, offset);
777 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
779 const CXXRecordDecl *ClassDecl,
780 const CXXRecordDecl *BaseClassDecl) {
781 llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
782 CharUnits VBaseOffsetOffset =
783 CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
786 llvm::Value *VBaseOffsetPtr =
787 CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
789 VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
790 CGM.PtrDiffTy->getPointerTo());
792 llvm::Value *VBaseOffset =
793 CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
798 /// The generic ABI passes 'this', plus a VTT if it's initializing a
800 void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
803 SmallVectorImpl<CanQualType> &ArgTys) {
804 ASTContext &Context = getContext();
806 // 'this' parameter is already there, as well as 'this' return if
807 // HasThisReturn(GlobalDecl(Ctor, Type)) is true
809 // Check if we need to add a VTT parameter (which has type void **).
810 if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
811 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
814 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
815 // Just make sure we're in sync with TargetCXXABI.
816 assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
818 // The constructor used for constructing this as a complete class;
819 // constucts the virtual bases, then calls the base constructor.
820 if (!D->getParent()->isAbstract()) {
821 // We don't need to emit the complete ctor if the class is abstract.
822 CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
825 // The constructor used for constructing this as a base class;
826 // ignores virtual bases.
827 CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
830 /// The generic ABI passes 'this', plus a VTT if it's destroying a
832 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
835 SmallVectorImpl<CanQualType> &ArgTys) {
836 ASTContext &Context = getContext();
838 // 'this' parameter is already there, as well as 'this' return if
839 // HasThisReturn(GlobalDecl(Dtor, Type)) is true
841 // Check if we need to add a VTT parameter (which has type void **).
842 if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
843 ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
846 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
847 // The destructor in a virtual table is always a 'deleting'
848 // destructor, which calls the complete destructor and then uses the
849 // appropriate operator delete.
851 CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
853 // The destructor used for destructing this as a most-derived class;
854 // call the base destructor and then destructs any virtual bases.
855 CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
857 // The destructor used for destructing this as a base class; ignores
859 CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
862 void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
864 FunctionArgList &Params) {
865 /// Create the 'this' variable.
866 BuildThisParam(CGF, Params);
868 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
869 assert(MD->isInstance());
871 // Check if we need a VTT parameter as well.
872 if (NeedsVTTParameter(CGF.CurGD)) {
873 ASTContext &Context = getContext();
875 // FIXME: avoid the fake decl
876 QualType T = Context.getPointerType(Context.VoidPtrTy);
877 ImplicitParamDecl *VTTDecl
878 = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
879 &Context.Idents.get("vtt"), T);
880 Params.push_back(VTTDecl);
881 getVTTDecl(CGF) = VTTDecl;
885 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
886 /// Initialize the 'this' slot.
889 /// Initialize the 'vtt' slot if needed.
890 if (getVTTDecl(CGF)) {
892 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
896 /// If this is a function that the ABI specifies returns 'this', initialize
897 /// the return slot to 'this' at the start of the function.
899 /// Unlike the setting of return types, this is done within the ABI
900 /// implementation instead of by clients of CGCXXABI because:
901 /// 1) getThisValue is currently protected
902 /// 2) in theory, an ABI could implement 'this' returns some other way;
903 /// HasThisReturn only specifies a contract, not the implementation
904 if (HasThisReturn(CGF.CurGD))
905 CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
908 void ItaniumCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
909 const CXXConstructorDecl *D,
911 bool ForVirtualBase, bool Delegating,
913 CallExpr::const_arg_iterator ArgBeg,
914 CallExpr::const_arg_iterator ArgEnd) {
915 llvm::Value *VTT = CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase,
917 QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
918 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
920 // FIXME: Provide a source location here.
921 CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(),
922 This, VTT, VTTTy, ArgBeg, ArgEnd);
925 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
926 const CXXRecordDecl *RD) {
927 llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
928 if (VTable->hasInitializer())
931 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
932 const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
933 llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
935 // Create and set the initializer.
936 llvm::Constant *Init = CGVT.CreateVTableInitializer(
937 RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
938 VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
939 VTable->setInitializer(Init);
941 // Set the correct linkage.
942 VTable->setLinkage(Linkage);
944 // Set the right visibility.
945 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
947 // If this is the magic class __cxxabiv1::__fundamental_type_info,
948 // we will emit the typeinfo for the fundamental types. This is the
949 // same behaviour as GCC.
950 const DeclContext *DC = RD->getDeclContext();
951 if (RD->getIdentifier() &&
952 RD->getIdentifier()->isStr("__fundamental_type_info") &&
953 isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
954 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
955 DC->getParent()->isTranslationUnit())
956 CGM.EmitFundamentalRTTIDescriptors();
959 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
960 CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
961 const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
962 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
963 NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
965 llvm::Value *VTableAddressPoint;
966 if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
967 // Get the secondary vpointer index.
968 uint64_t VirtualPointerIndex =
969 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
972 llvm::Value *VTT = CGF.LoadCXXVTT();
973 if (VirtualPointerIndex)
974 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
976 // And load the address point from the VTT.
977 VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
979 llvm::Constant *VTable =
980 CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
981 uint64_t AddressPoint = CGM.getItaniumVTableContext()
982 .getVTableLayout(VTableClass)
983 .getAddressPoint(Base);
985 CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
988 return VTableAddressPoint;
991 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
992 BaseSubobject Base, const CXXRecordDecl *VTableClass) {
993 llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
995 // Find the appropriate vtable within the vtable group.
996 uint64_t AddressPoint = CGM.getItaniumVTableContext()
997 .getVTableLayout(VTableClass)
998 .getAddressPoint(Base);
999 llvm::Value *Indices[] = {
1000 llvm::ConstantInt::get(CGM.Int64Ty, 0),
1001 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1004 return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1007 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1008 CharUnits VPtrOffset) {
1009 assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1011 llvm::GlobalVariable *&VTable = VTables[RD];
1015 // Queue up this v-table for possible deferred emission.
1016 CGM.addDeferredVTable(RD);
1018 SmallString<256> OutName;
1019 llvm::raw_svector_ostream Out(OutName);
1020 getMangleContext().mangleCXXVTable(RD, Out);
1022 StringRef Name = OutName.str();
1024 ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1025 llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1026 CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1028 VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1029 Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1030 VTable->setUnnamedAddr(true);
1034 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1038 GD = GD.getCanonicalDecl();
1039 Ty = Ty->getPointerTo()->getPointerTo();
1040 llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1042 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1043 llvm::Value *VFuncPtr =
1044 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1045 return CGF.Builder.CreateLoad(VFuncPtr);
1048 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1049 const CXXDestructorDecl *Dtor,
1050 CXXDtorType DtorType,
1051 SourceLocation CallLoc,
1052 llvm::Value *This) {
1053 assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1055 const CGFunctionInfo *FInfo
1056 = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1057 llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1058 llvm::Value *Callee =
1059 getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
1061 CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1062 /*ImplicitParam=*/0, QualType(), 0, 0);
1065 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1066 CodeGenVTables &VTables = CGM.getVTables();
1067 llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1068 VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1071 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1073 int64_t NonVirtualAdjustment,
1074 int64_t VirtualAdjustment,
1075 bool IsReturnAdjustment) {
1076 if (!NonVirtualAdjustment && !VirtualAdjustment)
1079 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1080 llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1082 if (NonVirtualAdjustment && !IsReturnAdjustment) {
1083 // Perform the non-virtual adjustment for a base-to-derived cast.
1084 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1087 if (VirtualAdjustment) {
1088 llvm::Type *PtrDiffTy =
1089 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1091 // Perform the virtual adjustment.
1092 llvm::Value *VTablePtrPtr =
1093 CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1095 llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1097 llvm::Value *OffsetPtr =
1098 CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1100 OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1102 // Load the adjustment offset from the vtable.
1103 llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1105 // Adjust our pointer.
1106 V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1109 if (NonVirtualAdjustment && IsReturnAdjustment) {
1110 // Perform the non-virtual adjustment for a derived-to-base cast.
1111 V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1114 // Cast back to the original type.
1115 return CGF.Builder.CreateBitCast(V, Ptr->getType());
1118 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1120 const ThisAdjustment &TA) {
1121 return performTypeAdjustment(CGF, This, TA.NonVirtual,
1122 TA.Virtual.Itanium.VCallOffsetOffset,
1123 /*IsReturnAdjustment=*/false);
1127 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1128 const ReturnAdjustment &RA) {
1129 return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1130 RA.Virtual.Itanium.VBaseOffsetOffset,
1131 /*IsReturnAdjustment=*/true);
1134 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1135 RValue RV, QualType ResultType) {
1136 if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1137 return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1139 // Destructor thunks in the ARM ABI have indeterminate results.
1141 cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1142 RValue Undef = RValue::get(llvm::UndefValue::get(T));
1143 return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1146 /************************** Array allocation cookies **************************/
1148 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1149 // The array cookie is a size_t; pad that up to the element alignment.
1150 // The cookie is actually right-justified in that space.
1151 return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1152 CGM.getContext().getTypeAlignInChars(elementType));
1155 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1156 llvm::Value *NewPtr,
1157 llvm::Value *NumElements,
1158 const CXXNewExpr *expr,
1159 QualType ElementType) {
1160 assert(requiresArrayCookie(expr));
1162 unsigned AS = NewPtr->getType()->getPointerAddressSpace();
1164 ASTContext &Ctx = getContext();
1165 QualType SizeTy = Ctx.getSizeType();
1166 CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1168 // The size of the cookie.
1169 CharUnits CookieSize =
1170 std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1171 assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1173 // Compute an offset to the cookie.
1174 llvm::Value *CookiePtr = NewPtr;
1175 CharUnits CookieOffset = CookieSize - SizeSize;
1176 if (!CookieOffset.isZero())
1177 CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1178 CookieOffset.getQuantity());
1180 // Write the number of elements into the appropriate slot.
1181 llvm::Value *NumElementsPtr
1182 = CGF.Builder.CreateBitCast(CookiePtr,
1183 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1184 CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1186 // Finally, compute a pointer to the actual data buffer by skipping
1187 // over the cookie completely.
1188 return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1189 CookieSize.getQuantity());
1192 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1193 llvm::Value *allocPtr,
1194 CharUnits cookieSize) {
1195 // The element size is right-justified in the cookie.
1196 llvm::Value *numElementsPtr = allocPtr;
1197 CharUnits numElementsOffset =
1198 cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1199 if (!numElementsOffset.isZero())
1201 CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1202 numElementsOffset.getQuantity());
1204 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1206 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1207 return CGF.Builder.CreateLoad(numElementsPtr);
1210 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1211 // ARM says that the cookie is always:
1212 // struct array_cookie {
1213 // std::size_t element_size; // element_size != 0
1214 // std::size_t element_count;
1216 // But the base ABI doesn't give anything an alignment greater than
1217 // 8, so we can dismiss this as typical ABI-author blindness to
1218 // actual language complexity and round up to the element alignment.
1219 return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1220 CGM.getContext().getTypeAlignInChars(elementType));
1223 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1224 llvm::Value *newPtr,
1225 llvm::Value *numElements,
1226 const CXXNewExpr *expr,
1227 QualType elementType) {
1228 assert(requiresArrayCookie(expr));
1230 // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1231 unsigned AS = newPtr->getType()->getPointerAddressSpace();
1233 // The cookie is always at the start of the buffer.
1234 llvm::Value *cookie = newPtr;
1236 // The first element is the element size.
1237 cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1238 llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1239 getContext().getTypeSizeInChars(elementType).getQuantity());
1240 CGF.Builder.CreateStore(elementSize, cookie);
1242 // The second element is the element count.
1243 cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1244 CGF.Builder.CreateStore(numElements, cookie);
1246 // Finally, compute a pointer to the actual data buffer by skipping
1247 // over the cookie completely.
1248 CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1249 return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1250 cookieSize.getQuantity());
1253 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1254 llvm::Value *allocPtr,
1255 CharUnits cookieSize) {
1256 // The number of elements is at offset sizeof(size_t) relative to
1257 // the allocated pointer.
1258 llvm::Value *numElementsPtr
1259 = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
1261 unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1263 CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1264 return CGF.Builder.CreateLoad(numElementsPtr);
1267 /*********************** Static local initialization **************************/
1269 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1270 llvm::PointerType *GuardPtrTy) {
1271 // int __cxa_guard_acquire(__guard *guard_object);
1272 llvm::FunctionType *FTy =
1273 llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1274 GuardPtrTy, /*isVarArg=*/false);
1275 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1276 llvm::AttributeSet::get(CGM.getLLVMContext(),
1277 llvm::AttributeSet::FunctionIndex,
1278 llvm::Attribute::NoUnwind));
1281 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1282 llvm::PointerType *GuardPtrTy) {
1283 // void __cxa_guard_release(__guard *guard_object);
1284 llvm::FunctionType *FTy =
1285 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1286 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1287 llvm::AttributeSet::get(CGM.getLLVMContext(),
1288 llvm::AttributeSet::FunctionIndex,
1289 llvm::Attribute::NoUnwind));
1292 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1293 llvm::PointerType *GuardPtrTy) {
1294 // void __cxa_guard_abort(__guard *guard_object);
1295 llvm::FunctionType *FTy =
1296 llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1297 return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1298 llvm::AttributeSet::get(CGM.getLLVMContext(),
1299 llvm::AttributeSet::FunctionIndex,
1300 llvm::Attribute::NoUnwind));
1304 struct CallGuardAbort : EHScopeStack::Cleanup {
1305 llvm::GlobalVariable *Guard;
1306 CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1308 void Emit(CodeGenFunction &CGF, Flags flags) {
1309 CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1315 /// The ARM code here follows the Itanium code closely enough that we
1316 /// just special-case it at particular places.
1317 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1319 llvm::GlobalVariable *var,
1320 bool shouldPerformInit) {
1321 CGBuilderTy &Builder = CGF.Builder;
1323 // We only need to use thread-safe statics for local non-TLS variables;
1324 // global initialization is always single-threaded.
1325 bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1326 D.isLocalVarDecl() && !D.getTLSKind();
1328 // If we have a global variable with internal linkage and thread-safe statics
1329 // are disabled, we can just let the guard variable be of type i8.
1330 bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1332 llvm::IntegerType *guardTy;
1333 if (useInt8GuardVariable) {
1334 guardTy = CGF.Int8Ty;
1336 // Guard variables are 64 bits in the generic ABI and size width on ARM
1337 // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1338 guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
1340 llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1342 // Create the guard variable if we don't already have it (as we
1343 // might if we're double-emitting this function body).
1344 llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1346 // Mangle the name for the guard.
1347 SmallString<256> guardName;
1349 llvm::raw_svector_ostream out(guardName);
1350 getMangleContext().mangleStaticGuardVariable(&D, out);
1354 // Create the guard variable with a zero-initializer.
1355 // Just absorb linkage and visibility from the guarded variable.
1356 guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1357 false, var->getLinkage(),
1358 llvm::ConstantInt::get(guardTy, 0),
1360 guard->setVisibility(var->getVisibility());
1361 // If the variable is thread-local, so is its guard variable.
1362 guard->setThreadLocalMode(var->getThreadLocalMode());
1364 CGM.setStaticLocalDeclGuardAddress(&D, guard);
1367 // Test whether the variable has completed initialization.
1368 llvm::Value *isInitialized;
1370 // ARM C++ ABI 3.2.3.1:
1371 // To support the potential use of initialization guard variables
1372 // as semaphores that are the target of ARM SWP and LDREX/STREX
1373 // synchronizing instructions we define a static initialization
1374 // guard variable to be a 4-byte aligned, 4- byte word with the
1375 // following inline access protocol.
1376 // #define INITIALIZED 1
1377 // if ((obj_guard & INITIALIZED) != INITIALIZED) {
1378 // if (__cxa_guard_acquire(&obj_guard))
1381 if (UseARMGuardVarABI && !useInt8GuardVariable) {
1382 llvm::Value *V = Builder.CreateLoad(guard);
1383 llvm::Value *Test1 = llvm::ConstantInt::get(guardTy, 1);
1384 V = Builder.CreateAnd(V, Test1);
1385 isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1387 // Itanium C++ ABI 3.3.2:
1388 // The following is pseudo-code showing how these functions can be used:
1389 // if (obj_guard.first_byte == 0) {
1390 // if ( __cxa_guard_acquire (&obj_guard) ) {
1392 // ... initialize the object ...;
1394 // __cxa_guard_abort (&obj_guard);
1397 // ... queue object destructor with __cxa_atexit() ...;
1398 // __cxa_guard_release (&obj_guard);
1402 // Load the first byte of the guard variable.
1403 llvm::LoadInst *LI =
1404 Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1405 LI->setAlignment(1);
1408 // An implementation supporting thread-safety on multiprocessor
1409 // systems must also guarantee that references to the initialized
1410 // object do not occur before the load of the initialization flag.
1412 // In LLVM, we do this by marking the load Acquire.
1414 LI->setAtomic(llvm::Acquire);
1416 isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
1419 llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1420 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1422 // Check if the first byte of the guard variable is zero.
1423 Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1425 CGF.EmitBlock(InitCheckBlock);
1427 // Variables used when coping with thread-safe statics and exceptions.
1429 // Call __cxa_guard_acquire.
1431 = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1433 llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1435 Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1436 InitBlock, EndBlock);
1438 // Call __cxa_guard_abort along the exceptional edge.
1439 CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1441 CGF.EmitBlock(InitBlock);
1444 // Emit the initializer and add a global destructor if appropriate.
1445 CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1448 // Pop the guard-abort cleanup if we pushed one.
1449 CGF.PopCleanupBlock();
1451 // Call __cxa_guard_release. This cannot throw.
1452 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1454 Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1457 CGF.EmitBlock(EndBlock);
1460 /// Register a global destructor using __cxa_atexit.
1461 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1462 llvm::Constant *dtor,
1463 llvm::Constant *addr,
1465 const char *Name = "__cxa_atexit";
1467 const llvm::Triple &T = CGF.getTarget().getTriple();
1468 Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
1471 // We're assuming that the destructor function is something we can
1472 // reasonably call with the default CC. Go ahead and cast it to the
1474 llvm::Type *dtorTy =
1475 llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1477 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1478 llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1479 llvm::FunctionType *atexitTy =
1480 llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1482 // Fetch the actual function.
1483 llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
1484 if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1485 fn->setDoesNotThrow();
1487 // Create a variable that binds the atexit to this shared object.
1488 llvm::Constant *handle =
1489 CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1491 llvm::Value *args[] = {
1492 llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1493 llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1496 CGF.EmitNounwindRuntimeCall(atexit, args);
1499 /// Register a global destructor as best as we know how.
1500 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1502 llvm::Constant *dtor,
1503 llvm::Constant *addr) {
1504 // Use __cxa_atexit if available.
1505 if (CGM.getCodeGenOpts().CXAAtExit)
1506 return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1509 CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
1511 // In Apple kexts, we want to add a global destructor entry.
1512 // FIXME: shouldn't this be guarded by some variable?
1513 if (CGM.getLangOpts().AppleKext) {
1514 // Generate a global destructor entry.
1515 return CGM.AddCXXDtorEntry(dtor, addr);
1518 CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
1521 /// Get the appropriate linkage for the wrapper function. This is essentially
1522 /// the weak form of the variable's linkage; every translation unit which wneeds
1523 /// the wrapper emits a copy, and we want the linker to merge them.
1524 static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
1525 llvm::GlobalValue::LinkageTypes VarLinkage) {
1526 if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
1527 return llvm::GlobalValue::LinkerPrivateWeakLinkage;
1528 // For internal linkage variables, we don't need an external or weak wrapper.
1529 if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1531 return llvm::GlobalValue::WeakODRLinkage;
1535 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1536 llvm::GlobalVariable *Var) {
1537 // Mangle the name for the thread_local wrapper function.
1538 SmallString<256> WrapperName;
1540 llvm::raw_svector_ostream Out(WrapperName);
1541 getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1545 if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1546 return cast<llvm::Function>(V);
1548 llvm::Type *RetTy = Var->getType();
1549 if (VD->getType()->isReferenceType())
1550 RetTy = RetTy->getPointerElementType();
1552 llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1553 llvm::Function *Wrapper = llvm::Function::Create(
1554 FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
1556 // Always resolve references to the wrapper at link time.
1557 Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1561 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1562 llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1563 llvm::Function *InitFunc) {
1564 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1565 const VarDecl *VD = Decls[I].first;
1566 llvm::GlobalVariable *Var = Decls[I].second;
1568 // Mangle the name for the thread_local initialization function.
1569 SmallString<256> InitFnName;
1571 llvm::raw_svector_ostream Out(InitFnName);
1572 getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1576 // If we have a definition for the variable, emit the initialization
1577 // function as an alias to the global Init function (if any). Otherwise,
1578 // produce a declaration of the initialization function.
1579 llvm::GlobalValue *Init = 0;
1580 bool InitIsInitFunc = false;
1581 if (VD->hasDefinition()) {
1582 InitIsInitFunc = true;
1585 new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
1586 InitFnName.str(), InitFunc, &CGM.getModule());
1588 // Emit a weak global function referring to the initialization function.
1589 // This function will not exist if the TU defining the thread_local
1590 // variable in question does not need any dynamic initialization for
1591 // its thread_local variables.
1592 llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1593 Init = llvm::Function::Create(
1594 FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1599 Init->setVisibility(Var->getVisibility());
1601 llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1602 llvm::LLVMContext &Context = CGM.getModule().getContext();
1603 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1604 CGBuilderTy Builder(Entry);
1605 if (InitIsInitFunc) {
1607 Builder.CreateCall(Init);
1609 // Don't know whether we have an init function. Call it if it exists.
1610 llvm::Value *Have = Builder.CreateIsNotNull(Init);
1611 llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1612 llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1613 Builder.CreateCondBr(Have, InitBB, ExitBB);
1615 Builder.SetInsertPoint(InitBB);
1616 Builder.CreateCall(Init);
1617 Builder.CreateBr(ExitBB);
1619 Builder.SetInsertPoint(ExitBB);
1622 // For a reference, the result of the wrapper function is a pointer to
1623 // the referenced object.
1624 llvm::Value *Val = Var;
1625 if (VD->getType()->isReferenceType()) {
1626 llvm::LoadInst *LI = Builder.CreateLoad(Val);
1627 LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1631 Builder.CreateRet(Val);
1635 LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
1636 const DeclRefExpr *DRE) {
1637 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1638 QualType T = VD->getType();
1639 llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1640 llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1641 llvm::Function *Wrapper =
1642 getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1644 Val = CGF.Builder.CreateCall(Wrapper);
1647 if (VD->getType()->isReferenceType())
1648 LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
1650 LV = CGF.MakeAddrLValue(Val, DRE->getType(),
1651 CGF.getContext().getDeclAlign(VD));
1652 // FIXME: need setObjCGCLValueClass?
1656 /// Return whether the given global decl needs a VTT parameter, which it does
1657 /// if it's a base constructor or destructor with virtual bases.
1658 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1659 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1661 // We don't have any virtual bases, just return early.
1662 if (!MD->getParent()->getNumVBases())
1665 // Check if we have a base constructor.
1666 if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1669 // Check if we have a base destructor.
1670 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)