clang API Documentation

CodeGen/ItaniumCXXABI.cpp
Go to the documentation of this file.
00001 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This provides C++ code generation targeting the Itanium C++ ABI.  The class
00011 // in this file generates structures that follow the Itanium C++ ABI, which is
00012 // documented at:
00013 //  http://www.codesourcery.com/public/cxx-abi/abi.html
00014 //  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
00015 //
00016 // It also supports the closely-related ARM ABI, documented at:
00017 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
00018 //
00019 //===----------------------------------------------------------------------===//
00020 
00021 #include "CGCXXABI.h"
00022 #include "CGRecordLayout.h"
00023 #include "CodeGenFunction.h"
00024 #include "CodeGenModule.h"
00025 #include <clang/AST/Mangle.h>
00026 #include <clang/AST/Type.h>
00027 #include <llvm/Intrinsics.h>
00028 #include <llvm/Target/TargetData.h>
00029 #include <llvm/Value.h>
00030 
00031 using namespace clang;
00032 using namespace CodeGen;
00033 
00034 namespace {
00035 class ItaniumCXXABI : public CodeGen::CGCXXABI {
00036 private:
00037   llvm::IntegerType *PtrDiffTy;
00038 protected:
00039   bool IsARM;
00040 
00041   // It's a little silly for us to cache this.
00042   llvm::IntegerType *getPtrDiffTy() {
00043     if (!PtrDiffTy) {
00044       QualType T = getContext().getPointerDiffType();
00045       llvm::Type *Ty = CGM.getTypes().ConvertType(T);
00046       PtrDiffTy = cast<llvm::IntegerType>(Ty);
00047     }
00048     return PtrDiffTy;
00049   }
00050 
00051 public:
00052   ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
00053     CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
00054 
00055   bool isZeroInitializable(const MemberPointerType *MPT);
00056 
00057   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
00058 
00059   llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
00060                                                llvm::Value *&This,
00061                                                llvm::Value *MemFnPtr,
00062                                                const MemberPointerType *MPT);
00063 
00064   llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
00065                                             llvm::Value *Base,
00066                                             llvm::Value *MemPtr,
00067                                             const MemberPointerType *MPT);
00068 
00069   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
00070                                            const CastExpr *E,
00071                                            llvm::Value *Src);
00072   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
00073                                               llvm::Constant *Src);
00074 
00075   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
00076 
00077   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
00078   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
00079                                         CharUnits offset);
00080   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
00081   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
00082                                      CharUnits ThisAdjustment);
00083 
00084   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
00085                                            llvm::Value *L,
00086                                            llvm::Value *R,
00087                                            const MemberPointerType *MPT,
00088                                            bool Inequality);
00089 
00090   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
00091                                           llvm::Value *Addr,
00092                                           const MemberPointerType *MPT);
00093 
00094   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
00095                                  CXXCtorType T,
00096                                  CanQualType &ResTy,
00097                                  SmallVectorImpl<CanQualType> &ArgTys);
00098 
00099   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
00100                                 CXXDtorType T,
00101                                 CanQualType &ResTy,
00102                                 SmallVectorImpl<CanQualType> &ArgTys);
00103 
00104   void BuildInstanceFunctionParams(CodeGenFunction &CGF,
00105                                    QualType &ResTy,
00106                                    FunctionArgList &Params);
00107 
00108   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
00109 
00110   CharUnits getArrayCookieSizeImpl(QualType elementType);
00111   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
00112                                      llvm::Value *NewPtr,
00113                                      llvm::Value *NumElements,
00114                                      const CXXNewExpr *expr,
00115                                      QualType ElementType);
00116   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
00117                                    llvm::Value *allocPtr,
00118                                    CharUnits cookieSize);
00119 
00120   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
00121                        llvm::GlobalVariable *DeclPtr, bool PerformInit);
00122   void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
00123                           llvm::Constant *addr);
00124 };
00125 
00126 class ARMCXXABI : public ItaniumCXXABI {
00127 public:
00128   ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
00129 
00130   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
00131                                  CXXCtorType T,
00132                                  CanQualType &ResTy,
00133                                  SmallVectorImpl<CanQualType> &ArgTys);
00134 
00135   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
00136                                 CXXDtorType T,
00137                                 CanQualType &ResTy,
00138                                 SmallVectorImpl<CanQualType> &ArgTys);
00139 
00140   void BuildInstanceFunctionParams(CodeGenFunction &CGF,
00141                                    QualType &ResTy,
00142                                    FunctionArgList &Params);
00143 
00144   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
00145 
00146   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
00147 
00148   CharUnits getArrayCookieSizeImpl(QualType elementType);
00149   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
00150                                      llvm::Value *NewPtr,
00151                                      llvm::Value *NumElements,
00152                                      const CXXNewExpr *expr,
00153                                      QualType ElementType);
00154   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
00155                                    CharUnits cookieSize);
00156 
00157 private:
00158   /// \brief Returns true if the given instance method is one of the
00159   /// kinds that the ARM ABI says returns 'this'.
00160   static bool HasThisReturn(GlobalDecl GD) {
00161     const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
00162     return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
00163             (isa<CXXConstructorDecl>(MD)));
00164   }
00165 };
00166 }
00167 
00168 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
00169   return new ItaniumCXXABI(CGM);
00170 }
00171 
00172 CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
00173   return new ARMCXXABI(CGM);
00174 }
00175 
00176 llvm::Type *
00177 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
00178   if (MPT->isMemberDataPointer())
00179     return getPtrDiffTy();
00180   return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
00181 }
00182 
00183 /// In the Itanium and ARM ABIs, method pointers have the form:
00184 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
00185 ///
00186 /// In the Itanium ABI:
00187 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
00188 ///  - the this-adjustment is (memptr.adj)
00189 ///  - the virtual offset is (memptr.ptr - 1)
00190 ///
00191 /// In the ARM ABI:
00192 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
00193 ///  - the this-adjustment is (memptr.adj >> 1)
00194 ///  - the virtual offset is (memptr.ptr)
00195 /// ARM uses 'adj' for the virtual flag because Thumb functions
00196 /// may be only single-byte aligned.
00197 ///
00198 /// If the member is virtual, the adjusted 'this' pointer points
00199 /// to a vtable pointer from which the virtual offset is applied.
00200 ///
00201 /// If the member is non-virtual, memptr.ptr is the address of
00202 /// the function to call.
00203 llvm::Value *
00204 ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
00205                                                llvm::Value *&This,
00206                                                llvm::Value *MemFnPtr,
00207                                                const MemberPointerType *MPT) {
00208   CGBuilderTy &Builder = CGF.Builder;
00209 
00210   const FunctionProtoType *FPT = 
00211     MPT->getPointeeType()->getAs<FunctionProtoType>();
00212   const CXXRecordDecl *RD = 
00213     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
00214 
00215   llvm::FunctionType *FTy = 
00216     CGM.getTypes().GetFunctionType(
00217       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
00218 
00219   llvm::IntegerType *ptrdiff = getPtrDiffTy();
00220   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
00221 
00222   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
00223   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
00224   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
00225 
00226   // Extract memptr.adj, which is in the second field.
00227   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
00228 
00229   // Compute the true adjustment.
00230   llvm::Value *Adj = RawAdj;
00231   if (IsARM)
00232     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
00233 
00234   // Apply the adjustment and cast back to the original struct type
00235   // for consistency.
00236   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
00237   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
00238   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
00239   
00240   // Load the function pointer.
00241   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
00242   
00243   // If the LSB in the function pointer is 1, the function pointer points to
00244   // a virtual function.
00245   llvm::Value *IsVirtual;
00246   if (IsARM)
00247     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
00248   else
00249     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
00250   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
00251   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
00252 
00253   // In the virtual path, the adjustment left 'This' pointing to the
00254   // vtable of the correct base subobject.  The "function pointer" is an
00255   // offset within the vtable (+1 for the virtual flag on non-ARM).
00256   CGF.EmitBlock(FnVirtual);
00257 
00258   // Cast the adjusted this to a pointer to vtable pointer and load.
00259   llvm::Type *VTableTy = Builder.getInt8PtrTy();
00260   llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
00261   VTable = Builder.CreateLoad(VTable, "memptr.vtable");
00262 
00263   // Apply the offset.
00264   llvm::Value *VTableOffset = FnAsInt;
00265   if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
00266   VTable = Builder.CreateGEP(VTable, VTableOffset);
00267 
00268   // Load the virtual function to call.
00269   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
00270   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
00271   CGF.EmitBranch(FnEnd);
00272 
00273   // In the non-virtual path, the function pointer is actually a
00274   // function pointer.
00275   CGF.EmitBlock(FnNonVirtual);
00276   llvm::Value *NonVirtualFn =
00277     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
00278   
00279   // We're done.
00280   CGF.EmitBlock(FnEnd);
00281   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
00282   Callee->addIncoming(VirtualFn, FnVirtual);
00283   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
00284   return Callee;
00285 }
00286 
00287 /// Compute an l-value by applying the given pointer-to-member to a
00288 /// base object.
00289 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
00290                                                          llvm::Value *Base,
00291                                                          llvm::Value *MemPtr,
00292                                            const MemberPointerType *MPT) {
00293   assert(MemPtr->getType() == getPtrDiffTy());
00294 
00295   CGBuilderTy &Builder = CGF.Builder;
00296 
00297   unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
00298 
00299   // Cast to char*.
00300   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
00301 
00302   // Apply the offset, which we assume is non-null.
00303   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
00304 
00305   // Cast the address to the appropriate pointer type, adopting the
00306   // address space of the base pointer.
00307   llvm::Type *PType
00308     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
00309   return Builder.CreateBitCast(Addr, PType);
00310 }
00311 
00312 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
00313 /// conversion.
00314 ///
00315 /// Bitcast conversions are always a no-op under Itanium.
00316 ///
00317 /// Obligatory offset/adjustment diagram:
00318 ///         <-- offset -->          <-- adjustment -->
00319 ///   |--------------------------|----------------------|--------------------|
00320 ///   ^Derived address point     ^Base address point    ^Member address point
00321 ///
00322 /// So when converting a base member pointer to a derived member pointer,
00323 /// we add the offset to the adjustment because the address point has
00324 /// decreased;  and conversely, when converting a derived MP to a base MP
00325 /// we subtract the offset from the adjustment because the address point
00326 /// has increased.
00327 ///
00328 /// The standard forbids (at compile time) conversion to and from
00329 /// virtual bases, which is why we don't have to consider them here.
00330 ///
00331 /// The standard forbids (at run time) casting a derived MP to a base
00332 /// MP when the derived MP does not point to a member of the base.
00333 /// This is why -1 is a reasonable choice for null data member
00334 /// pointers.
00335 llvm::Value *
00336 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
00337                                            const CastExpr *E,
00338                                            llvm::Value *src) {
00339   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
00340          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
00341          E->getCastKind() == CK_ReinterpretMemberPointer);
00342 
00343   // Under Itanium, reinterprets don't require any additional processing.
00344   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
00345 
00346   // Use constant emission if we can.
00347   if (isa<llvm::Constant>(src))
00348     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
00349 
00350   llvm::Constant *adj = getMemberPointerAdjustment(E);
00351   if (!adj) return src;
00352 
00353   CGBuilderTy &Builder = CGF.Builder;
00354   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
00355 
00356   const MemberPointerType *destTy =
00357     E->getType()->castAs<MemberPointerType>();
00358 
00359   // For member data pointers, this is just a matter of adding the
00360   // offset if the source is non-null.
00361   if (destTy->isMemberDataPointer()) {
00362     llvm::Value *dst;
00363     if (isDerivedToBase)
00364       dst = Builder.CreateNSWSub(src, adj, "adj");
00365     else
00366       dst = Builder.CreateNSWAdd(src, adj, "adj");
00367 
00368     // Null check.
00369     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
00370     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
00371     return Builder.CreateSelect(isNull, src, dst);
00372   }
00373 
00374   // The this-adjustment is left-shifted by 1 on ARM.
00375   if (IsARM) {
00376     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
00377     offset <<= 1;
00378     adj = llvm::ConstantInt::get(adj->getType(), offset);
00379   }
00380 
00381   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
00382   llvm::Value *dstAdj;
00383   if (isDerivedToBase)
00384     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
00385   else
00386     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
00387 
00388   return Builder.CreateInsertValue(src, dstAdj, 1);
00389 }
00390 
00391 llvm::Constant *
00392 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
00393                                            llvm::Constant *src) {
00394   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
00395          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
00396          E->getCastKind() == CK_ReinterpretMemberPointer);
00397 
00398   // Under Itanium, reinterprets don't require any additional processing.
00399   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
00400 
00401   // If the adjustment is trivial, we don't need to do anything.
00402   llvm::Constant *adj = getMemberPointerAdjustment(E);
00403   if (!adj) return src;
00404 
00405   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
00406 
00407   const MemberPointerType *destTy =
00408     E->getType()->castAs<MemberPointerType>();
00409 
00410   // For member data pointers, this is just a matter of adding the
00411   // offset if the source is non-null.
00412   if (destTy->isMemberDataPointer()) {
00413     // null maps to null.
00414     if (src->isAllOnesValue()) return src;
00415 
00416     if (isDerivedToBase)
00417       return llvm::ConstantExpr::getNSWSub(src, adj);
00418     else
00419       return llvm::ConstantExpr::getNSWAdd(src, adj);
00420   }
00421 
00422   // The this-adjustment is left-shifted by 1 on ARM.
00423   if (IsARM) {
00424     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
00425     offset <<= 1;
00426     adj = llvm::ConstantInt::get(adj->getType(), offset);
00427   }
00428 
00429   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
00430   llvm::Constant *dstAdj;
00431   if (isDerivedToBase)
00432     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
00433   else
00434     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
00435 
00436   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
00437 }
00438 
00439 llvm::Constant *
00440 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
00441   llvm::Type *ptrdiff_t = getPtrDiffTy();
00442 
00443   // Itanium C++ ABI 2.3:
00444   //   A NULL pointer is represented as -1.
00445   if (MPT->isMemberDataPointer()) 
00446     return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
00447 
00448   llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
00449   llvm::Constant *Values[2] = { Zero, Zero };
00450   return llvm::ConstantStruct::getAnon(Values);
00451 }
00452 
00453 llvm::Constant *
00454 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
00455                                      CharUnits offset) {
00456   // Itanium C++ ABI 2.3:
00457   //   A pointer to data member is an offset from the base address of
00458   //   the class object containing it, represented as a ptrdiff_t
00459   return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
00460 }
00461 
00462 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
00463   return BuildMemberPointer(MD, CharUnits::Zero());
00464 }
00465 
00466 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
00467                                                   CharUnits ThisAdjustment) {
00468   assert(MD->isInstance() && "Member function must not be static!");
00469   MD = MD->getCanonicalDecl();
00470 
00471   CodeGenTypes &Types = CGM.getTypes();
00472   llvm::Type *ptrdiff_t = getPtrDiffTy();
00473 
00474   // Get the function pointer (or index if this is a virtual function).
00475   llvm::Constant *MemPtr[2];
00476   if (MD->isVirtual()) {
00477     uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
00478 
00479     const ASTContext &Context = getContext();
00480     CharUnits PointerWidth =
00481       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
00482     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
00483 
00484     if (IsARM) {
00485       // ARM C++ ABI 3.2.1:
00486       //   This ABI specifies that adj contains twice the this
00487       //   adjustment, plus 1 if the member function is virtual. The
00488       //   least significant bit of adj then makes exactly the same
00489       //   discrimination as the least significant bit of ptr does for
00490       //   Itanium.
00491       MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
00492       MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
00493                                          2 * ThisAdjustment.getQuantity() + 1);
00494     } else {
00495       // Itanium C++ ABI 2.3:
00496       //   For a virtual function, [the pointer field] is 1 plus the
00497       //   virtual table offset (in bytes) of the function,
00498       //   represented as a ptrdiff_t.
00499       MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
00500       MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
00501                                          ThisAdjustment.getQuantity());
00502     }
00503   } else {
00504     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
00505     llvm::Type *Ty;
00506     // Check whether the function has a computable LLVM signature.
00507     if (Types.isFuncTypeConvertible(FPT)) {
00508       // The function has a computable LLVM signature; use the correct type.
00509       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
00510     } else {
00511       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
00512       // function type is incomplete.
00513       Ty = ptrdiff_t;
00514     }
00515     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
00516 
00517     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
00518     MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
00519                                        ThisAdjustment.getQuantity());
00520   }
00521   
00522   return llvm::ConstantStruct::getAnon(MemPtr);
00523 }
00524 
00525 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
00526                                                  QualType MPType) {
00527   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
00528   const ValueDecl *MPD = MP.getMemberPointerDecl();
00529   if (!MPD)
00530     return EmitNullMemberPointer(MPT);
00531 
00532   // Compute the this-adjustment.
00533   CharUnits ThisAdjustment = CharUnits::Zero();
00534   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
00535   bool DerivedMember = MP.isMemberPointerToDerivedMember();
00536   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
00537   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
00538     const CXXRecordDecl *Base = RD;
00539     const CXXRecordDecl *Derived = Path[I];
00540     if (DerivedMember)
00541       std::swap(Base, Derived);
00542     ThisAdjustment +=
00543       getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
00544     RD = Path[I];
00545   }
00546   if (DerivedMember)
00547     ThisAdjustment = -ThisAdjustment;
00548 
00549   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
00550     return BuildMemberPointer(MD, ThisAdjustment);
00551 
00552   CharUnits FieldOffset =
00553     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
00554   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
00555 }
00556 
00557 /// The comparison algorithm is pretty easy: the member pointers are
00558 /// the same if they're either bitwise identical *or* both null.
00559 ///
00560 /// ARM is different here only because null-ness is more complicated.
00561 llvm::Value *
00562 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
00563                                            llvm::Value *L,
00564                                            llvm::Value *R,
00565                                            const MemberPointerType *MPT,
00566                                            bool Inequality) {
00567   CGBuilderTy &Builder = CGF.Builder;
00568 
00569   llvm::ICmpInst::Predicate Eq;
00570   llvm::Instruction::BinaryOps And, Or;
00571   if (Inequality) {
00572     Eq = llvm::ICmpInst::ICMP_NE;
00573     And = llvm::Instruction::Or;
00574     Or = llvm::Instruction::And;
00575   } else {
00576     Eq = llvm::ICmpInst::ICMP_EQ;
00577     And = llvm::Instruction::And;
00578     Or = llvm::Instruction::Or;
00579   }
00580 
00581   // Member data pointers are easy because there's a unique null
00582   // value, so it just comes down to bitwise equality.
00583   if (MPT->isMemberDataPointer())
00584     return Builder.CreateICmp(Eq, L, R);
00585 
00586   // For member function pointers, the tautologies are more complex.
00587   // The Itanium tautology is:
00588   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
00589   // The ARM tautology is:
00590   //   (L == R) <==> (L.ptr == R.ptr &&
00591   //                  (L.adj == R.adj ||
00592   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
00593   // The inequality tautologies have exactly the same structure, except
00594   // applying De Morgan's laws.
00595   
00596   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
00597   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
00598 
00599   // This condition tests whether L.ptr == R.ptr.  This must always be
00600   // true for equality to hold.
00601   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
00602 
00603   // This condition, together with the assumption that L.ptr == R.ptr,
00604   // tests whether the pointers are both null.  ARM imposes an extra
00605   // condition.
00606   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
00607   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
00608 
00609   // This condition tests whether L.adj == R.adj.  If this isn't
00610   // true, the pointers are unequal unless they're both null.
00611   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
00612   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
00613   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
00614 
00615   // Null member function pointers on ARM clear the low bit of Adj,
00616   // so the zero condition has to check that neither low bit is set.
00617   if (IsARM) {
00618     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
00619 
00620     // Compute (l.adj | r.adj) & 1 and test it against zero.
00621     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
00622     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
00623     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
00624                                                       "cmp.or.adj");
00625     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
00626   }
00627 
00628   // Tie together all our conditions.
00629   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
00630   Result = Builder.CreateBinOp(And, PtrEq, Result,
00631                                Inequality ? "memptr.ne" : "memptr.eq");
00632   return Result;
00633 }
00634 
00635 llvm::Value *
00636 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
00637                                           llvm::Value *MemPtr,
00638                                           const MemberPointerType *MPT) {
00639   CGBuilderTy &Builder = CGF.Builder;
00640 
00641   /// For member data pointers, this is just a check against -1.
00642   if (MPT->isMemberDataPointer()) {
00643     assert(MemPtr->getType() == getPtrDiffTy());
00644     llvm::Value *NegativeOne =
00645       llvm::Constant::getAllOnesValue(MemPtr->getType());
00646     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
00647   }
00648   
00649   // In Itanium, a member function pointer is not null if 'ptr' is not null.
00650   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
00651 
00652   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
00653   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
00654 
00655   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
00656   // (the virtual bit) is set.
00657   if (IsARM) {
00658     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
00659     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
00660     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
00661     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
00662                                                   "memptr.isvirtual");
00663     Result = Builder.CreateOr(Result, IsVirtual);
00664   }
00665 
00666   return Result;
00667 }
00668 
00669 /// The Itanium ABI requires non-zero initialization only for data
00670 /// member pointers, for which '0' is a valid offset.
00671 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
00672   return MPT->getPointeeType()->isFunctionType();
00673 }
00674 
00675 /// The generic ABI passes 'this', plus a VTT if it's initializing a
00676 /// base subobject.
00677 void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
00678                                               CXXCtorType Type,
00679                                               CanQualType &ResTy,
00680                                 SmallVectorImpl<CanQualType> &ArgTys) {
00681   ASTContext &Context = getContext();
00682 
00683   // 'this' is already there.
00684 
00685   // Check if we need to add a VTT parameter (which has type void **).
00686   if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
00687     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
00688 }
00689 
00690 /// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
00691 void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
00692                                           CXXCtorType Type,
00693                                           CanQualType &ResTy,
00694                                 SmallVectorImpl<CanQualType> &ArgTys) {
00695   ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
00696   ResTy = ArgTys[0];
00697 }
00698 
00699 /// The generic ABI passes 'this', plus a VTT if it's destroying a
00700 /// base subobject.
00701 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
00702                                              CXXDtorType Type,
00703                                              CanQualType &ResTy,
00704                                 SmallVectorImpl<CanQualType> &ArgTys) {
00705   ASTContext &Context = getContext();
00706 
00707   // 'this' is already there.
00708 
00709   // Check if we need to add a VTT parameter (which has type void **).
00710   if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
00711     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
00712 }
00713 
00714 /// The ARM ABI does the same as the Itanium ABI, but returns 'this'
00715 /// for non-deleting destructors.
00716 void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
00717                                          CXXDtorType Type,
00718                                          CanQualType &ResTy,
00719                                 SmallVectorImpl<CanQualType> &ArgTys) {
00720   ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
00721 
00722   if (Type != Dtor_Deleting)
00723     ResTy = ArgTys[0];
00724 }
00725 
00726 void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
00727                                                 QualType &ResTy,
00728                                                 FunctionArgList &Params) {
00729   /// Create the 'this' variable.
00730   BuildThisParam(CGF, Params);
00731 
00732   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
00733   assert(MD->isInstance());
00734 
00735   // Check if we need a VTT parameter as well.
00736   if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
00737     ASTContext &Context = getContext();
00738 
00739     // FIXME: avoid the fake decl
00740     QualType T = Context.getPointerType(Context.VoidPtrTy);
00741     ImplicitParamDecl *VTTDecl
00742       = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
00743                                   &Context.Idents.get("vtt"), T);
00744     Params.push_back(VTTDecl);
00745     getVTTDecl(CGF) = VTTDecl;
00746   }
00747 }
00748 
00749 void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
00750                                             QualType &ResTy,
00751                                             FunctionArgList &Params) {
00752   ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
00753 
00754   // Return 'this' from certain constructors and destructors.
00755   if (HasThisReturn(CGF.CurGD))
00756     ResTy = Params[0]->getType();
00757 }
00758 
00759 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
00760   /// Initialize the 'this' slot.
00761   EmitThisParam(CGF);
00762 
00763   /// Initialize the 'vtt' slot if needed.
00764   if (getVTTDecl(CGF)) {
00765     getVTTValue(CGF)
00766       = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
00767                                "vtt");
00768   }
00769 }
00770 
00771 void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
00772   ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
00773 
00774   /// Initialize the return slot to 'this' at the start of the
00775   /// function.
00776   if (HasThisReturn(CGF.CurGD))
00777     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
00778 }
00779 
00780 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
00781                                     RValue RV, QualType ResultType) {
00782   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
00783     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
00784 
00785   // Destructor thunks in the ARM ABI have indeterminate results.
00786   llvm::Type *T =
00787     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
00788   RValue Undef = RValue::get(llvm::UndefValue::get(T));
00789   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
00790 }
00791 
00792 /************************** Array allocation cookies **************************/
00793 
00794 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
00795   // The array cookie is a size_t; pad that up to the element alignment.
00796   // The cookie is actually right-justified in that space.
00797   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
00798                   CGM.getContext().getTypeAlignInChars(elementType));
00799 }
00800 
00801 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
00802                                                   llvm::Value *NewPtr,
00803                                                   llvm::Value *NumElements,
00804                                                   const CXXNewExpr *expr,
00805                                                   QualType ElementType) {
00806   assert(requiresArrayCookie(expr));
00807 
00808   unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
00809 
00810   ASTContext &Ctx = getContext();
00811   QualType SizeTy = Ctx.getSizeType();
00812   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
00813 
00814   // The size of the cookie.
00815   CharUnits CookieSize =
00816     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
00817   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
00818 
00819   // Compute an offset to the cookie.
00820   llvm::Value *CookiePtr = NewPtr;
00821   CharUnits CookieOffset = CookieSize - SizeSize;
00822   if (!CookieOffset.isZero())
00823     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
00824                                                  CookieOffset.getQuantity());
00825 
00826   // Write the number of elements into the appropriate slot.
00827   llvm::Value *NumElementsPtr
00828     = CGF.Builder.CreateBitCast(CookiePtr,
00829                                 CGF.ConvertType(SizeTy)->getPointerTo(AS));
00830   CGF.Builder.CreateStore(NumElements, NumElementsPtr);
00831 
00832   // Finally, compute a pointer to the actual data buffer by skipping
00833   // over the cookie completely.
00834   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
00835                                                 CookieSize.getQuantity());  
00836 }
00837 
00838 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
00839                                                 llvm::Value *allocPtr,
00840                                                 CharUnits cookieSize) {
00841   // The element size is right-justified in the cookie.
00842   llvm::Value *numElementsPtr = allocPtr;
00843   CharUnits numElementsOffset =
00844     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
00845   if (!numElementsOffset.isZero())
00846     numElementsPtr =
00847       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
00848                                              numElementsOffset.getQuantity());
00849 
00850   unsigned AS = cast<llvm::PointerType>(allocPtr->getType())->getAddressSpace();
00851   numElementsPtr = 
00852     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
00853   return CGF.Builder.CreateLoad(numElementsPtr);
00854 }
00855 
00856 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
00857   // On ARM, the cookie is always:
00858   //   struct array_cookie {
00859   //     std::size_t element_size; // element_size != 0
00860   //     std::size_t element_count;
00861   //   };
00862   // TODO: what should we do if the allocated type actually wants
00863   // greater alignment?
00864   return CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes);
00865 }
00866 
00867 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
00868                                               llvm::Value *NewPtr,
00869                                               llvm::Value *NumElements,
00870                                               const CXXNewExpr *expr,
00871                                               QualType ElementType) {
00872   assert(requiresArrayCookie(expr));
00873 
00874   // NewPtr is a char*.
00875 
00876   unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
00877 
00878   ASTContext &Ctx = getContext();
00879   CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
00880   llvm::IntegerType *SizeTy =
00881     cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
00882 
00883   // The cookie is always at the start of the buffer.
00884   llvm::Value *CookiePtr = NewPtr;
00885 
00886   // The first element is the element size.
00887   CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
00888   llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
00889                           Ctx.getTypeSizeInChars(ElementType).getQuantity());
00890   CGF.Builder.CreateStore(ElementSize, CookiePtr);
00891 
00892   // The second element is the element count.
00893   CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
00894   CGF.Builder.CreateStore(NumElements, CookiePtr);
00895 
00896   // Finally, compute a pointer to the actual data buffer by skipping
00897   // over the cookie completely.
00898   CharUnits CookieSize = 2 * SizeSize;
00899   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
00900                                                 CookieSize.getQuantity());
00901 }
00902 
00903 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
00904                                             llvm::Value *allocPtr,
00905                                             CharUnits cookieSize) {
00906   // The number of elements is at offset sizeof(size_t) relative to
00907   // the allocated pointer.
00908   llvm::Value *numElementsPtr
00909     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
00910 
00911   unsigned AS = cast<llvm::PointerType>(allocPtr->getType())->getAddressSpace();
00912   numElementsPtr = 
00913     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
00914   return CGF.Builder.CreateLoad(numElementsPtr);
00915 }
00916 
00917 /*********************** Static local initialization **************************/
00918 
00919 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
00920                                          llvm::PointerType *GuardPtrTy) {
00921   // int __cxa_guard_acquire(__guard *guard_object);
00922   llvm::FunctionType *FTy =
00923     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
00924                             GuardPtrTy, /*isVarArg=*/false);
00925   
00926   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
00927                                    llvm::Attribute::NoUnwind);
00928 }
00929 
00930 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
00931                                          llvm::PointerType *GuardPtrTy) {
00932   // void __cxa_guard_release(__guard *guard_object);
00933   llvm::FunctionType *FTy =
00934     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
00935   
00936   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
00937                                    llvm::Attribute::NoUnwind);
00938 }
00939 
00940 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
00941                                        llvm::PointerType *GuardPtrTy) {
00942   // void __cxa_guard_abort(__guard *guard_object);
00943   llvm::FunctionType *FTy =
00944     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
00945   
00946   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
00947                                    llvm::Attribute::NoUnwind);
00948 }
00949 
00950 namespace {
00951   struct CallGuardAbort : EHScopeStack::Cleanup {
00952     llvm::GlobalVariable *Guard;
00953     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
00954 
00955     void Emit(CodeGenFunction &CGF, Flags flags) {
00956       CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
00957         ->setDoesNotThrow();
00958     }
00959   };
00960 }
00961 
00962 /// The ARM code here follows the Itanium code closely enough that we
00963 /// just special-case it at particular places.
00964 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
00965                                     const VarDecl &D,
00966                                     llvm::GlobalVariable *var,
00967                                     bool shouldPerformInit) {
00968   CGBuilderTy &Builder = CGF.Builder;
00969 
00970   // We only need to use thread-safe statics for local variables;
00971   // global initialization is always single-threaded.
00972   bool threadsafe =
00973     (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
00974 
00975   // If we have a global variable with internal linkage and thread-safe statics
00976   // are disabled, we can just let the guard variable be of type i8.
00977   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
00978 
00979   llvm::IntegerType *guardTy;
00980   if (useInt8GuardVariable) {
00981     guardTy = CGF.Int8Ty;
00982   } else {
00983     // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
00984     guardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
00985   }
00986   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
00987 
00988   // Create the guard variable if we don't already have it (as we
00989   // might if we're double-emitting this function body).
00990   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
00991   if (!guard) {
00992     // Mangle the name for the guard.
00993     SmallString<256> guardName;
00994     {
00995       llvm::raw_svector_ostream out(guardName);
00996       getMangleContext().mangleItaniumGuardVariable(&D, out);
00997       out.flush();
00998     }
00999 
01000     // Create the guard variable with a zero-initializer.
01001     // Just absorb linkage and visibility from the guarded variable.
01002     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
01003                                      false, var->getLinkage(),
01004                                      llvm::ConstantInt::get(guardTy, 0),
01005                                      guardName.str());
01006     guard->setVisibility(var->getVisibility());
01007 
01008     CGM.setStaticLocalDeclGuardAddress(&D, guard);
01009   }
01010 
01011   // Test whether the variable has completed initialization.
01012   llvm::Value *isInitialized;
01013 
01014   // ARM C++ ABI 3.2.3.1:
01015   //   To support the potential use of initialization guard variables
01016   //   as semaphores that are the target of ARM SWP and LDREX/STREX
01017   //   synchronizing instructions we define a static initialization
01018   //   guard variable to be a 4-byte aligned, 4- byte word with the
01019   //   following inline access protocol.
01020   //     #define INITIALIZED 1
01021   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
01022   //       if (__cxa_guard_acquire(&obj_guard))
01023   //         ...
01024   //     }
01025   if (IsARM && !useInt8GuardVariable) {
01026     llvm::Value *V = Builder.CreateLoad(guard);
01027     V = Builder.CreateAnd(V, Builder.getInt32(1));
01028     isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
01029 
01030   // Itanium C++ ABI 3.3.2:
01031   //   The following is pseudo-code showing how these functions can be used:
01032   //     if (obj_guard.first_byte == 0) {
01033   //       if ( __cxa_guard_acquire (&obj_guard) ) {
01034   //         try {
01035   //           ... initialize the object ...;
01036   //         } catch (...) {
01037   //            __cxa_guard_abort (&obj_guard);
01038   //            throw;
01039   //         }
01040   //         ... queue object destructor with __cxa_atexit() ...;
01041   //         __cxa_guard_release (&obj_guard);
01042   //       }
01043   //     }
01044   } else {
01045     // Load the first byte of the guard variable.
01046     llvm::LoadInst *LI = 
01047       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
01048     LI->setAlignment(1);
01049 
01050     // Itanium ABI:
01051     //   An implementation supporting thread-safety on multiprocessor
01052     //   systems must also guarantee that references to the initialized
01053     //   object do not occur before the load of the initialization flag.
01054     //
01055     // In LLVM, we do this by marking the load Acquire.
01056     if (threadsafe)
01057       LI->setAtomic(llvm::Acquire);
01058 
01059     isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
01060   }
01061 
01062   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
01063   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
01064 
01065   // Check if the first byte of the guard variable is zero.
01066   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
01067 
01068   CGF.EmitBlock(InitCheckBlock);
01069 
01070   // Variables used when coping with thread-safe statics and exceptions.
01071   if (threadsafe) {    
01072     // Call __cxa_guard_acquire.
01073     llvm::Value *V
01074       = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
01075                
01076     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
01077   
01078     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
01079                          InitBlock, EndBlock);
01080   
01081     // Call __cxa_guard_abort along the exceptional edge.
01082     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
01083     
01084     CGF.EmitBlock(InitBlock);
01085   }
01086 
01087   // Emit the initializer and add a global destructor if appropriate.
01088   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
01089 
01090   if (threadsafe) {
01091     // Pop the guard-abort cleanup if we pushed one.
01092     CGF.PopCleanupBlock();
01093 
01094     // Call __cxa_guard_release.  This cannot throw.
01095     Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
01096   } else {
01097     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
01098   }
01099 
01100   CGF.EmitBlock(EndBlock);
01101 }
01102 
01103 /// Register a global destructor using __cxa_atexit.
01104 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
01105                                         llvm::Constant *dtor,
01106                                         llvm::Constant *addr) {
01107   // We're assuming that the destructor function is something we can
01108   // reasonably call with the default CC.  Go ahead and cast it to the
01109   // right prototype.
01110   llvm::Type *dtorTy =
01111     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
01112 
01113   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
01114   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
01115   llvm::FunctionType *atexitTy =
01116     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
01117 
01118   // Fetch the actual function.
01119   llvm::Constant *atexit =
01120     CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
01121   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
01122     fn->setDoesNotThrow();
01123 
01124   // Create a variable that binds the atexit to this shared object.
01125   llvm::Constant *handle =
01126     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
01127 
01128   llvm::Value *args[] = {
01129     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
01130     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
01131     handle
01132   };
01133   CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
01134 }
01135 
01136 /// Register a global destructor as best as we know how.
01137 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
01138                                        llvm::Constant *dtor,
01139                                        llvm::Constant *addr) {
01140   // Use __cxa_atexit if available.
01141   if (CGM.getCodeGenOpts().CXAAtExit) {
01142     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
01143   }
01144 
01145   // In Apple kexts, we want to add a global destructor entry.
01146   // FIXME: shouldn't this be guarded by some variable?
01147   if (CGM.getContext().getLangOpts().AppleKext) {
01148     // Generate a global destructor entry.
01149     return CGM.AddCXXDtorEntry(dtor, addr);
01150   }
01151 
01152   CGF.registerGlobalDtorWithAtExit(dtor, addr);
01153 }