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 "CGVTables.h"
00024 #include "CodeGenFunction.h"
00025 #include "CodeGenModule.h"
00026 #include "clang/AST/Mangle.h"
00027 #include "clang/AST/Type.h"
00028 #include "llvm/IR/CallSite.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/Intrinsics.h"
00031 #include "llvm/IR/Value.h"
00032 
00033 using namespace clang;
00034 using namespace CodeGen;
00035 
00036 namespace {
00037 class ItaniumCXXABI : public CodeGen::CGCXXABI {
00038   /// VTables - All the vtables which have been defined.
00039   llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
00040 
00041 protected:
00042   bool UseARMMethodPtrABI;
00043   bool UseARMGuardVarABI;
00044 
00045   ItaniumMangleContext &getMangleContext() {
00046     return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
00047   }
00048 
00049 public:
00050   ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
00051                 bool UseARMMethodPtrABI = false,
00052                 bool UseARMGuardVarABI = false) :
00053     CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
00054     UseARMGuardVarABI(UseARMGuardVarABI) { }
00055 
00056   bool classifyReturnType(CGFunctionInfo &FI) const override;
00057 
00058   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
00059     // Structures with either a non-trivial destructor or a non-trivial
00060     // copy constructor are always indirect.
00061     // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
00062     // special members.
00063     if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
00064       return RAA_Indirect;
00065     return RAA_Default;
00066   }
00067 
00068   bool isZeroInitializable(const MemberPointerType *MPT) override;
00069 
00070   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
00071 
00072   llvm::Value *
00073     EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
00074                                     const Expr *E,
00075                                     llvm::Value *&This,
00076                                     llvm::Value *MemFnPtr,
00077                                     const MemberPointerType *MPT) override;
00078 
00079   llvm::Value *
00080     EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
00081                                  llvm::Value *Base,
00082                                  llvm::Value *MemPtr,
00083                                  const MemberPointerType *MPT) override;
00084 
00085   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
00086                                            const CastExpr *E,
00087                                            llvm::Value *Src) override;
00088   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
00089                                               llvm::Constant *Src) override;
00090 
00091   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
00092 
00093   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
00094   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
00095                                         CharUnits offset) override;
00096   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
00097   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
00098                                      CharUnits ThisAdjustment);
00099 
00100   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
00101                                            llvm::Value *L, llvm::Value *R,
00102                                            const MemberPointerType *MPT,
00103                                            bool Inequality) override;
00104 
00105   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
00106                                          llvm::Value *Addr,
00107                                          const MemberPointerType *MPT) override;
00108 
00109   void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
00110                                llvm::Value *Ptr, QualType ElementType,
00111                                const CXXDestructorDecl *Dtor) override;
00112 
00113   void EmitFundamentalRTTIDescriptor(QualType Type);
00114   void EmitFundamentalRTTIDescriptors();
00115   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
00116 
00117   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
00118   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
00119   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
00120                           llvm::Value *ThisPtr,
00121                           llvm::Type *StdTypeInfoPtrTy) override;
00122 
00123   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
00124                                           QualType SrcRecordTy) override;
00125 
00126   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
00127                                    QualType SrcRecordTy, QualType DestTy,
00128                                    QualType DestRecordTy,
00129                                    llvm::BasicBlock *CastEnd) override;
00130 
00131   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
00132                                      QualType SrcRecordTy,
00133                                      QualType DestTy) override;
00134 
00135   bool EmitBadCastCall(CodeGenFunction &CGF) override;
00136 
00137   llvm::Value *
00138     GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
00139                               const CXXRecordDecl *ClassDecl,
00140                               const CXXRecordDecl *BaseClassDecl) override;
00141 
00142   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
00143 
00144   void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
00145                               SmallVectorImpl<CanQualType> &ArgTys) override;
00146 
00147   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
00148                               CXXDtorType DT) const override {
00149     // Itanium does not emit any destructor variant as an inline thunk.
00150     // Delegating may occur as an optimization, but all variants are either
00151     // emitted with external linkage or as linkonce if they are inline and used.
00152     return false;
00153   }
00154 
00155   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
00156 
00157   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
00158                                  FunctionArgList &Params) override;
00159 
00160   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
00161 
00162   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
00163                                       const CXXConstructorDecl *D,
00164                                       CXXCtorType Type, bool ForVirtualBase,
00165                                       bool Delegating,
00166                                       CallArgList &Args) override;
00167 
00168   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
00169                           CXXDtorType Type, bool ForVirtualBase,
00170                           bool Delegating, llvm::Value *This) override;
00171 
00172   void emitVTableDefinitions(CodeGenVTables &CGVT,
00173                              const CXXRecordDecl *RD) override;
00174 
00175   llvm::Value *getVTableAddressPointInStructor(
00176       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
00177       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
00178       bool &NeedsVirtualOffset) override;
00179 
00180   llvm::Constant *
00181   getVTableAddressPointForConstExpr(BaseSubobject Base,
00182                                     const CXXRecordDecl *VTableClass) override;
00183 
00184   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
00185                                         CharUnits VPtrOffset) override;
00186 
00187   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
00188                                          llvm::Value *This,
00189                                          llvm::Type *Ty) override;
00190 
00191   llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
00192                                          const CXXDestructorDecl *Dtor,
00193                                          CXXDtorType DtorType,
00194                                          llvm::Value *This,
00195                                          const CXXMemberCallExpr *CE) override;
00196 
00197   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
00198 
00199   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
00200                        bool ReturnAdjustment) override {
00201     // Allow inlining of thunks by emitting them with available_externally
00202     // linkage together with vtables when needed.
00203     if (ForVTable)
00204       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
00205   }
00206 
00207   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
00208                                      const ThisAdjustment &TA) override;
00209 
00210   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
00211                                        const ReturnAdjustment &RA) override;
00212 
00213   size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
00214                               FunctionArgList &Args) const override {
00215     assert(!Args.empty() && "expected the arglist to not be empty!");
00216     return Args.size() - 1;
00217   }
00218 
00219   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
00220   StringRef GetDeletedVirtualCallName() override
00221     { return "__cxa_deleted_virtual"; }
00222 
00223   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
00224   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
00225                                      llvm::Value *NewPtr,
00226                                      llvm::Value *NumElements,
00227                                      const CXXNewExpr *expr,
00228                                      QualType ElementType) override;
00229   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
00230                                    llvm::Value *allocPtr,
00231                                    CharUnits cookieSize) override;
00232 
00233   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
00234                        llvm::GlobalVariable *DeclPtr,
00235                        bool PerformInit) override;
00236   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
00237                           llvm::Constant *dtor, llvm::Constant *addr) override;
00238 
00239   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
00240                                                 llvm::Value *Val);
00241   void EmitThreadLocalInitFuncs(
00242       CodeGenModule &CGM,
00243       ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
00244           CXXThreadLocals,
00245       ArrayRef<llvm::Function *> CXXThreadLocalInits,
00246       ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) override;
00247 
00248   bool usesThreadWrapperFunction() const override { return true; }
00249   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
00250                                       QualType LValType) override;
00251 
00252   bool NeedsVTTParameter(GlobalDecl GD) override;
00253 
00254   /**************************** RTTI Uniqueness ******************************/
00255 
00256 protected:
00257   /// Returns true if the ABI requires RTTI type_info objects to be unique
00258   /// across a program.
00259   virtual bool shouldRTTIBeUnique() const { return true; }
00260 
00261 public:
00262   /// What sort of unique-RTTI behavior should we use?
00263   enum RTTIUniquenessKind {
00264     /// We are guaranteeing, or need to guarantee, that the RTTI string
00265     /// is unique.
00266     RUK_Unique,
00267 
00268     /// We are not guaranteeing uniqueness for the RTTI string, so we
00269     /// can demote to hidden visibility but must use string comparisons.
00270     RUK_NonUniqueHidden,
00271 
00272     /// We are not guaranteeing uniqueness for the RTTI string, so we
00273     /// have to use string comparisons, but we also have to emit it with
00274     /// non-hidden visibility.
00275     RUK_NonUniqueVisible
00276   };
00277 
00278   /// Return the required visibility status for the given type and linkage in
00279   /// the current ABI.
00280   RTTIUniquenessKind
00281   classifyRTTIUniqueness(QualType CanTy,
00282                          llvm::GlobalValue::LinkageTypes Linkage) const;
00283   friend class ItaniumRTTIBuilder;
00284 
00285   void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
00286 };
00287 
00288 class ARMCXXABI : public ItaniumCXXABI {
00289 public:
00290   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
00291     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
00292                   /* UseARMGuardVarABI = */ true) {}
00293 
00294   bool HasThisReturn(GlobalDecl GD) const override {
00295     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
00296               isa<CXXDestructorDecl>(GD.getDecl()) &&
00297               GD.getDtorType() != Dtor_Deleting));
00298   }
00299 
00300   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
00301                            QualType ResTy) override;
00302 
00303   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
00304   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
00305                                      llvm::Value *NewPtr,
00306                                      llvm::Value *NumElements,
00307                                      const CXXNewExpr *expr,
00308                                      QualType ElementType) override;
00309   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
00310                                    CharUnits cookieSize) override;
00311 };
00312 
00313 class iOS64CXXABI : public ARMCXXABI {
00314 public:
00315   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
00316 
00317   // ARM64 libraries are prepared for non-unique RTTI.
00318   bool shouldRTTIBeUnique() const override { return false; }
00319 };
00320 }
00321 
00322 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
00323   switch (CGM.getTarget().getCXXABI().getKind()) {
00324   // For IR-generation purposes, there's no significant difference
00325   // between the ARM and iOS ABIs.
00326   case TargetCXXABI::GenericARM:
00327   case TargetCXXABI::iOS:
00328     return new ARMCXXABI(CGM);
00329 
00330   case TargetCXXABI::iOS64:
00331     return new iOS64CXXABI(CGM);
00332 
00333   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
00334   // include the other 32-bit ARM oddities: constructor/destructor return values
00335   // and array cookies.
00336   case TargetCXXABI::GenericAArch64:
00337     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
00338                              /* UseARMGuardVarABI = */ true);
00339 
00340   case TargetCXXABI::GenericItanium:
00341     if (CGM.getContext().getTargetInfo().getTriple().getArch()
00342         == llvm::Triple::le32) {
00343       // For PNaCl, use ARM-style method pointers so that PNaCl code
00344       // does not assume anything about the alignment of function
00345       // pointers.
00346       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
00347                                /* UseARMGuardVarABI = */ false);
00348     }
00349     return new ItaniumCXXABI(CGM);
00350 
00351   case TargetCXXABI::Microsoft:
00352     llvm_unreachable("Microsoft ABI is not Itanium-based");
00353   }
00354   llvm_unreachable("bad ABI kind");
00355 }
00356 
00357 llvm::Type *
00358 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
00359   if (MPT->isMemberDataPointer())
00360     return CGM.PtrDiffTy;
00361   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
00362 }
00363 
00364 /// In the Itanium and ARM ABIs, method pointers have the form:
00365 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
00366 ///
00367 /// In the Itanium ABI:
00368 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
00369 ///  - the this-adjustment is (memptr.adj)
00370 ///  - the virtual offset is (memptr.ptr - 1)
00371 ///
00372 /// In the ARM ABI:
00373 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
00374 ///  - the this-adjustment is (memptr.adj >> 1)
00375 ///  - the virtual offset is (memptr.ptr)
00376 /// ARM uses 'adj' for the virtual flag because Thumb functions
00377 /// may be only single-byte aligned.
00378 ///
00379 /// If the member is virtual, the adjusted 'this' pointer points
00380 /// to a vtable pointer from which the virtual offset is applied.
00381 ///
00382 /// If the member is non-virtual, memptr.ptr is the address of
00383 /// the function to call.
00384 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
00385     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
00386     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
00387   CGBuilderTy &Builder = CGF.Builder;
00388 
00389   const FunctionProtoType *FPT = 
00390     MPT->getPointeeType()->getAs<FunctionProtoType>();
00391   const CXXRecordDecl *RD = 
00392     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
00393 
00394   llvm::FunctionType *FTy = 
00395     CGM.getTypes().GetFunctionType(
00396       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
00397 
00398   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
00399 
00400   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
00401   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
00402   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
00403 
00404   // Extract memptr.adj, which is in the second field.
00405   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
00406 
00407   // Compute the true adjustment.
00408   llvm::Value *Adj = RawAdj;
00409   if (UseARMMethodPtrABI)
00410     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
00411 
00412   // Apply the adjustment and cast back to the original struct type
00413   // for consistency.
00414   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
00415   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
00416   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
00417   
00418   // Load the function pointer.
00419   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
00420   
00421   // If the LSB in the function pointer is 1, the function pointer points to
00422   // a virtual function.
00423   llvm::Value *IsVirtual;
00424   if (UseARMMethodPtrABI)
00425     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
00426   else
00427     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
00428   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
00429   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
00430 
00431   // In the virtual path, the adjustment left 'This' pointing to the
00432   // vtable of the correct base subobject.  The "function pointer" is an
00433   // offset within the vtable (+1 for the virtual flag on non-ARM).
00434   CGF.EmitBlock(FnVirtual);
00435 
00436   // Cast the adjusted this to a pointer to vtable pointer and load.
00437   llvm::Type *VTableTy = Builder.getInt8PtrTy();
00438   llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
00439 
00440   // Apply the offset.
00441   llvm::Value *VTableOffset = FnAsInt;
00442   if (!UseARMMethodPtrABI)
00443     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
00444   VTable = Builder.CreateGEP(VTable, VTableOffset);
00445 
00446   // Load the virtual function to call.
00447   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
00448   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
00449   CGF.EmitBranch(FnEnd);
00450 
00451   // In the non-virtual path, the function pointer is actually a
00452   // function pointer.
00453   CGF.EmitBlock(FnNonVirtual);
00454   llvm::Value *NonVirtualFn =
00455     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
00456   
00457   // We're done.
00458   CGF.EmitBlock(FnEnd);
00459   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
00460   Callee->addIncoming(VirtualFn, FnVirtual);
00461   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
00462   return Callee;
00463 }
00464 
00465 /// Compute an l-value by applying the given pointer-to-member to a
00466 /// base object.
00467 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
00468     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
00469     const MemberPointerType *MPT) {
00470   assert(MemPtr->getType() == CGM.PtrDiffTy);
00471 
00472   CGBuilderTy &Builder = CGF.Builder;
00473 
00474   unsigned AS = Base->getType()->getPointerAddressSpace();
00475 
00476   // Cast to char*.
00477   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
00478 
00479   // Apply the offset, which we assume is non-null.
00480   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
00481 
00482   // Cast the address to the appropriate pointer type, adopting the
00483   // address space of the base pointer.
00484   llvm::Type *PType
00485     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
00486   return Builder.CreateBitCast(Addr, PType);
00487 }
00488 
00489 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
00490 /// conversion.
00491 ///
00492 /// Bitcast conversions are always a no-op under Itanium.
00493 ///
00494 /// Obligatory offset/adjustment diagram:
00495 ///         <-- offset -->          <-- adjustment -->
00496 ///   |--------------------------|----------------------|--------------------|
00497 ///   ^Derived address point     ^Base address point    ^Member address point
00498 ///
00499 /// So when converting a base member pointer to a derived member pointer,
00500 /// we add the offset to the adjustment because the address point has
00501 /// decreased;  and conversely, when converting a derived MP to a base MP
00502 /// we subtract the offset from the adjustment because the address point
00503 /// has increased.
00504 ///
00505 /// The standard forbids (at compile time) conversion to and from
00506 /// virtual bases, which is why we don't have to consider them here.
00507 ///
00508 /// The standard forbids (at run time) casting a derived MP to a base
00509 /// MP when the derived MP does not point to a member of the base.
00510 /// This is why -1 is a reasonable choice for null data member
00511 /// pointers.
00512 llvm::Value *
00513 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
00514                                            const CastExpr *E,
00515                                            llvm::Value *src) {
00516   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
00517          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
00518          E->getCastKind() == CK_ReinterpretMemberPointer);
00519 
00520   // Under Itanium, reinterprets don't require any additional processing.
00521   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
00522 
00523   // Use constant emission if we can.
00524   if (isa<llvm::Constant>(src))
00525     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
00526 
00527   llvm::Constant *adj = getMemberPointerAdjustment(E);
00528   if (!adj) return src;
00529 
00530   CGBuilderTy &Builder = CGF.Builder;
00531   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
00532 
00533   const MemberPointerType *destTy =
00534     E->getType()->castAs<MemberPointerType>();
00535 
00536   // For member data pointers, this is just a matter of adding the
00537   // offset if the source is non-null.
00538   if (destTy->isMemberDataPointer()) {
00539     llvm::Value *dst;
00540     if (isDerivedToBase)
00541       dst = Builder.CreateNSWSub(src, adj, "adj");
00542     else
00543       dst = Builder.CreateNSWAdd(src, adj, "adj");
00544 
00545     // Null check.
00546     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
00547     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
00548     return Builder.CreateSelect(isNull, src, dst);
00549   }
00550 
00551   // The this-adjustment is left-shifted by 1 on ARM.
00552   if (UseARMMethodPtrABI) {
00553     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
00554     offset <<= 1;
00555     adj = llvm::ConstantInt::get(adj->getType(), offset);
00556   }
00557 
00558   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
00559   llvm::Value *dstAdj;
00560   if (isDerivedToBase)
00561     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
00562   else
00563     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
00564 
00565   return Builder.CreateInsertValue(src, dstAdj, 1);
00566 }
00567 
00568 llvm::Constant *
00569 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
00570                                            llvm::Constant *src) {
00571   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
00572          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
00573          E->getCastKind() == CK_ReinterpretMemberPointer);
00574 
00575   // Under Itanium, reinterprets don't require any additional processing.
00576   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
00577 
00578   // If the adjustment is trivial, we don't need to do anything.
00579   llvm::Constant *adj = getMemberPointerAdjustment(E);
00580   if (!adj) return src;
00581 
00582   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
00583 
00584   const MemberPointerType *destTy =
00585     E->getType()->castAs<MemberPointerType>();
00586 
00587   // For member data pointers, this is just a matter of adding the
00588   // offset if the source is non-null.
00589   if (destTy->isMemberDataPointer()) {
00590     // null maps to null.
00591     if (src->isAllOnesValue()) return src;
00592 
00593     if (isDerivedToBase)
00594       return llvm::ConstantExpr::getNSWSub(src, adj);
00595     else
00596       return llvm::ConstantExpr::getNSWAdd(src, adj);
00597   }
00598 
00599   // The this-adjustment is left-shifted by 1 on ARM.
00600   if (UseARMMethodPtrABI) {
00601     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
00602     offset <<= 1;
00603     adj = llvm::ConstantInt::get(adj->getType(), offset);
00604   }
00605 
00606   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
00607   llvm::Constant *dstAdj;
00608   if (isDerivedToBase)
00609     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
00610   else
00611     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
00612 
00613   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
00614 }
00615 
00616 llvm::Constant *
00617 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
00618   // Itanium C++ ABI 2.3:
00619   //   A NULL pointer is represented as -1.
00620   if (MPT->isMemberDataPointer()) 
00621     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
00622 
00623   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
00624   llvm::Constant *Values[2] = { Zero, Zero };
00625   return llvm::ConstantStruct::getAnon(Values);
00626 }
00627 
00628 llvm::Constant *
00629 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
00630                                      CharUnits offset) {
00631   // Itanium C++ ABI 2.3:
00632   //   A pointer to data member is an offset from the base address of
00633   //   the class object containing it, represented as a ptrdiff_t
00634   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
00635 }
00636 
00637 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
00638   return BuildMemberPointer(MD, CharUnits::Zero());
00639 }
00640 
00641 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
00642                                                   CharUnits ThisAdjustment) {
00643   assert(MD->isInstance() && "Member function must not be static!");
00644   MD = MD->getCanonicalDecl();
00645 
00646   CodeGenTypes &Types = CGM.getTypes();
00647 
00648   // Get the function pointer (or index if this is a virtual function).
00649   llvm::Constant *MemPtr[2];
00650   if (MD->isVirtual()) {
00651     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
00652 
00653     const ASTContext &Context = getContext();
00654     CharUnits PointerWidth =
00655       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
00656     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
00657 
00658     if (UseARMMethodPtrABI) {
00659       // ARM C++ ABI 3.2.1:
00660       //   This ABI specifies that adj contains twice the this
00661       //   adjustment, plus 1 if the member function is virtual. The
00662       //   least significant bit of adj then makes exactly the same
00663       //   discrimination as the least significant bit of ptr does for
00664       //   Itanium.
00665       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
00666       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
00667                                          2 * ThisAdjustment.getQuantity() + 1);
00668     } else {
00669       // Itanium C++ ABI 2.3:
00670       //   For a virtual function, [the pointer field] is 1 plus the
00671       //   virtual table offset (in bytes) of the function,
00672       //   represented as a ptrdiff_t.
00673       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
00674       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
00675                                          ThisAdjustment.getQuantity());
00676     }
00677   } else {
00678     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
00679     llvm::Type *Ty;
00680     // Check whether the function has a computable LLVM signature.
00681     if (Types.isFuncTypeConvertible(FPT)) {
00682       // The function has a computable LLVM signature; use the correct type.
00683       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
00684     } else {
00685       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
00686       // function type is incomplete.
00687       Ty = CGM.PtrDiffTy;
00688     }
00689     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
00690 
00691     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
00692     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
00693                                        (UseARMMethodPtrABI ? 2 : 1) *
00694                                        ThisAdjustment.getQuantity());
00695   }
00696   
00697   return llvm::ConstantStruct::getAnon(MemPtr);
00698 }
00699 
00700 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
00701                                                  QualType MPType) {
00702   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
00703   const ValueDecl *MPD = MP.getMemberPointerDecl();
00704   if (!MPD)
00705     return EmitNullMemberPointer(MPT);
00706 
00707   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
00708 
00709   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
00710     return BuildMemberPointer(MD, ThisAdjustment);
00711 
00712   CharUnits FieldOffset =
00713     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
00714   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
00715 }
00716 
00717 /// The comparison algorithm is pretty easy: the member pointers are
00718 /// the same if they're either bitwise identical *or* both null.
00719 ///
00720 /// ARM is different here only because null-ness is more complicated.
00721 llvm::Value *
00722 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
00723                                            llvm::Value *L,
00724                                            llvm::Value *R,
00725                                            const MemberPointerType *MPT,
00726                                            bool Inequality) {
00727   CGBuilderTy &Builder = CGF.Builder;
00728 
00729   llvm::ICmpInst::Predicate Eq;
00730   llvm::Instruction::BinaryOps And, Or;
00731   if (Inequality) {
00732     Eq = llvm::ICmpInst::ICMP_NE;
00733     And = llvm::Instruction::Or;
00734     Or = llvm::Instruction::And;
00735   } else {
00736     Eq = llvm::ICmpInst::ICMP_EQ;
00737     And = llvm::Instruction::And;
00738     Or = llvm::Instruction::Or;
00739   }
00740 
00741   // Member data pointers are easy because there's a unique null
00742   // value, so it just comes down to bitwise equality.
00743   if (MPT->isMemberDataPointer())
00744     return Builder.CreateICmp(Eq, L, R);
00745 
00746   // For member function pointers, the tautologies are more complex.
00747   // The Itanium tautology is:
00748   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
00749   // The ARM tautology is:
00750   //   (L == R) <==> (L.ptr == R.ptr &&
00751   //                  (L.adj == R.adj ||
00752   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
00753   // The inequality tautologies have exactly the same structure, except
00754   // applying De Morgan's laws.
00755   
00756   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
00757   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
00758 
00759   // This condition tests whether L.ptr == R.ptr.  This must always be
00760   // true for equality to hold.
00761   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
00762 
00763   // This condition, together with the assumption that L.ptr == R.ptr,
00764   // tests whether the pointers are both null.  ARM imposes an extra
00765   // condition.
00766   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
00767   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
00768 
00769   // This condition tests whether L.adj == R.adj.  If this isn't
00770   // true, the pointers are unequal unless they're both null.
00771   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
00772   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
00773   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
00774 
00775   // Null member function pointers on ARM clear the low bit of Adj,
00776   // so the zero condition has to check that neither low bit is set.
00777   if (UseARMMethodPtrABI) {
00778     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
00779 
00780     // Compute (l.adj | r.adj) & 1 and test it against zero.
00781     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
00782     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
00783     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
00784                                                       "cmp.or.adj");
00785     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
00786   }
00787 
00788   // Tie together all our conditions.
00789   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
00790   Result = Builder.CreateBinOp(And, PtrEq, Result,
00791                                Inequality ? "memptr.ne" : "memptr.eq");
00792   return Result;
00793 }
00794 
00795 llvm::Value *
00796 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
00797                                           llvm::Value *MemPtr,
00798                                           const MemberPointerType *MPT) {
00799   CGBuilderTy &Builder = CGF.Builder;
00800 
00801   /// For member data pointers, this is just a check against -1.
00802   if (MPT->isMemberDataPointer()) {
00803     assert(MemPtr->getType() == CGM.PtrDiffTy);
00804     llvm::Value *NegativeOne =
00805       llvm::Constant::getAllOnesValue(MemPtr->getType());
00806     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
00807   }
00808   
00809   // In Itanium, a member function pointer is not null if 'ptr' is not null.
00810   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
00811 
00812   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
00813   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
00814 
00815   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
00816   // (the virtual bit) is set.
00817   if (UseARMMethodPtrABI) {
00818     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
00819     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
00820     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
00821     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
00822                                                   "memptr.isvirtual");
00823     Result = Builder.CreateOr(Result, IsVirtual);
00824   }
00825 
00826   return Result;
00827 }
00828 
00829 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
00830   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
00831   if (!RD)
00832     return false;
00833 
00834   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
00835   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
00836   // special members.
00837   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
00838     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
00839     return true;
00840   }
00841   return false;
00842 }
00843 
00844 /// The Itanium ABI requires non-zero initialization only for data
00845 /// member pointers, for which '0' is a valid offset.
00846 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
00847   return MPT->getPointeeType()->isFunctionType();
00848 }
00849 
00850 /// The Itanium ABI always places an offset to the complete object
00851 /// at entry -2 in the vtable.
00852 void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
00853                                             const CXXDeleteExpr *DE,
00854                                             llvm::Value *Ptr,
00855                                             QualType ElementType,
00856                                             const CXXDestructorDecl *Dtor) {
00857   bool UseGlobalDelete = DE->isGlobalDelete();
00858   if (UseGlobalDelete) {
00859     // Derive the complete-object pointer, which is what we need
00860     // to pass to the deallocation function.
00861 
00862     // Grab the vtable pointer as an intptr_t*.
00863     llvm::Value *VTable = CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo());
00864 
00865     // Track back to entry -2 and pull out the offset there.
00866     llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
00867         VTable, -2, "complete-offset.ptr");
00868     llvm::LoadInst *Offset = CGF.Builder.CreateLoad(OffsetPtr);
00869     Offset->setAlignment(CGF.PointerAlignInBytes);
00870 
00871     // Apply the offset.
00872     llvm::Value *CompletePtr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
00873     CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
00874 
00875     // If we're supposed to call the global delete, make sure we do so
00876     // even if the destructor throws.
00877     CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
00878                                     ElementType);
00879   }
00880 
00881   // FIXME: Provide a source location here even though there's no
00882   // CXXMemberCallExpr for dtor call.
00883   CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
00884   EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, /*CE=*/nullptr);
00885 
00886   if (UseGlobalDelete)
00887     CGF.PopCleanupBlock();
00888 }
00889 
00890 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
00891   // void *__dynamic_cast(const void *sub,
00892   //                      const abi::__class_type_info *src,
00893   //                      const abi::__class_type_info *dst,
00894   //                      std::ptrdiff_t src2dst_offset);
00895   
00896   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
00897   llvm::Type *PtrDiffTy = 
00898     CGF.ConvertType(CGF.getContext().getPointerDiffType());
00899 
00900   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
00901 
00902   llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
00903 
00904   // Mark the function as nounwind readonly.
00905   llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
00906                                             llvm::Attribute::ReadOnly };
00907   llvm::AttributeSet Attrs = llvm::AttributeSet::get(
00908       CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
00909 
00910   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
00911 }
00912 
00913 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
00914   // void __cxa_bad_cast();
00915   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
00916   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
00917 }
00918 
00919 /// \brief Compute the src2dst_offset hint as described in the
00920 /// Itanium C++ ABI [2.9.7]
00921 static CharUnits computeOffsetHint(ASTContext &Context,
00922                                    const CXXRecordDecl *Src,
00923                                    const CXXRecordDecl *Dst) {
00924   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
00925                      /*DetectVirtual=*/false);
00926 
00927   // If Dst is not derived from Src we can skip the whole computation below and
00928   // return that Src is not a public base of Dst.  Record all inheritance paths.
00929   if (!Dst->isDerivedFrom(Src, Paths))
00930     return CharUnits::fromQuantity(-2ULL);
00931 
00932   unsigned NumPublicPaths = 0;
00933   CharUnits Offset;
00934 
00935   // Now walk all possible inheritance paths.
00936   for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
00937        ++I) {
00938     if (I->Access != AS_public) // Ignore non-public inheritance.
00939       continue;
00940 
00941     ++NumPublicPaths;
00942 
00943     for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
00944       // If the path contains a virtual base class we can't give any hint.
00945       // -1: no hint.
00946       if (J->Base->isVirtual())
00947         return CharUnits::fromQuantity(-1ULL);
00948 
00949       if (NumPublicPaths > 1) // Won't use offsets, skip computation.
00950         continue;
00951 
00952       // Accumulate the base class offsets.
00953       const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
00954       Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
00955     }
00956   }
00957 
00958   // -2: Src is not a public base of Dst.
00959   if (NumPublicPaths == 0)
00960     return CharUnits::fromQuantity(-2ULL);
00961 
00962   // -3: Src is a multiple public base type but never a virtual base type.
00963   if (NumPublicPaths > 1)
00964     return CharUnits::fromQuantity(-3ULL);
00965 
00966   // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
00967   // Return the offset of Src from the origin of Dst.
00968   return Offset;
00969 }
00970 
00971 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
00972   // void __cxa_bad_typeid();
00973   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
00974 
00975   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
00976 }
00977 
00978 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
00979                                               QualType SrcRecordTy) {
00980   return IsDeref;
00981 }
00982 
00983 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
00984   llvm::Value *Fn = getBadTypeidFn(CGF);
00985   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
00986   CGF.Builder.CreateUnreachable();
00987 }
00988 
00989 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
00990                                        QualType SrcRecordTy,
00991                                        llvm::Value *ThisPtr,
00992                                        llvm::Type *StdTypeInfoPtrTy) {
00993   llvm::Value *Value =
00994       CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
00995 
00996   // Load the type info.
00997   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
00998   return CGF.Builder.CreateLoad(Value);
00999 }
01000 
01001 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
01002                                                        QualType SrcRecordTy) {
01003   return SrcIsPtr;
01004 }
01005 
01006 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
01007     CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
01008     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
01009   llvm::Type *PtrDiffLTy =
01010       CGF.ConvertType(CGF.getContext().getPointerDiffType());
01011   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
01012 
01013   llvm::Value *SrcRTTI =
01014       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
01015   llvm::Value *DestRTTI =
01016       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
01017 
01018   // Compute the offset hint.
01019   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
01020   const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
01021   llvm::Value *OffsetHint = llvm::ConstantInt::get(
01022       PtrDiffLTy,
01023       computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
01024 
01025   // Emit the call to __dynamic_cast.
01026   Value = CGF.EmitCastToVoidPtr(Value);
01027 
01028   llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
01029   Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
01030   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
01031 
01032   /// C++ [expr.dynamic.cast]p9:
01033   ///   A failed cast to reference type throws std::bad_cast
01034   if (DestTy->isReferenceType()) {
01035     llvm::BasicBlock *BadCastBlock =
01036         CGF.createBasicBlock("dynamic_cast.bad_cast");
01037 
01038     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
01039     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
01040 
01041     CGF.EmitBlock(BadCastBlock);
01042     EmitBadCastCall(CGF);
01043   }
01044 
01045   return Value;
01046 }
01047 
01048 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
01049                                                   llvm::Value *Value,
01050                                                   QualType SrcRecordTy,
01051                                                   QualType DestTy) {
01052   llvm::Type *PtrDiffLTy =
01053       CGF.ConvertType(CGF.getContext().getPointerDiffType());
01054   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
01055 
01056   // Get the vtable pointer.
01057   llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
01058 
01059   // Get the offset-to-top from the vtable.
01060   llvm::Value *OffsetToTop =
01061       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
01062   OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
01063 
01064   // Finally, add the offset to the pointer.
01065   Value = CGF.EmitCastToVoidPtr(Value);
01066   Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
01067 
01068   return CGF.Builder.CreateBitCast(Value, DestLTy);
01069 }
01070 
01071 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
01072   llvm::Value *Fn = getBadCastFn(CGF);
01073   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
01074   CGF.Builder.CreateUnreachable();
01075   return true;
01076 }
01077 
01078 llvm::Value *
01079 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
01080                                          llvm::Value *This,
01081                                          const CXXRecordDecl *ClassDecl,
01082                                          const CXXRecordDecl *BaseClassDecl) {
01083   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
01084   CharUnits VBaseOffsetOffset =
01085       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
01086                                                                BaseClassDecl);
01087 
01088   llvm::Value *VBaseOffsetPtr =
01089     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
01090                                    "vbase.offset.ptr");
01091   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
01092                                              CGM.PtrDiffTy->getPointerTo());
01093 
01094   llvm::Value *VBaseOffset =
01095     CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
01096 
01097   return VBaseOffset;
01098 }
01099 
01100 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
01101   // Just make sure we're in sync with TargetCXXABI.
01102   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
01103 
01104   // The constructor used for constructing this as a base class;
01105   // ignores virtual bases.
01106   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
01107 
01108   // The constructor used for constructing this as a complete class;
01109   // constucts the virtual bases, then calls the base constructor.
01110   if (!D->getParent()->isAbstract()) {
01111     // We don't need to emit the complete ctor if the class is abstract.
01112     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
01113   }
01114 }
01115 
01116 void
01117 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
01118                                       SmallVectorImpl<CanQualType> &ArgTys) {
01119   ASTContext &Context = getContext();
01120 
01121   // All parameters are already in place except VTT, which goes after 'this'.
01122   // These are Clang types, so we don't need to worry about sret yet.
01123 
01124   // Check if we need to add a VTT parameter (which has type void **).
01125   if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
01126     ArgTys.insert(ArgTys.begin() + 1,
01127                   Context.getPointerType(Context.VoidPtrTy));
01128 }
01129 
01130 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
01131   // The destructor used for destructing this as a base class; ignores
01132   // virtual bases.
01133   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
01134 
01135   // The destructor used for destructing this as a most-derived class;
01136   // call the base destructor and then destructs any virtual bases.
01137   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
01138 
01139   // The destructor in a virtual table is always a 'deleting'
01140   // destructor, which calls the complete destructor and then uses the
01141   // appropriate operator delete.
01142   if (D->isVirtual())
01143     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
01144 }
01145 
01146 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
01147                                               QualType &ResTy,
01148                                               FunctionArgList &Params) {
01149   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
01150   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
01151 
01152   // Check if we need a VTT parameter as well.
01153   if (NeedsVTTParameter(CGF.CurGD)) {
01154     ASTContext &Context = getContext();
01155 
01156     // FIXME: avoid the fake decl
01157     QualType T = Context.getPointerType(Context.VoidPtrTy);
01158     ImplicitParamDecl *VTTDecl
01159       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
01160                                   &Context.Idents.get("vtt"), T);
01161     Params.insert(Params.begin() + 1, VTTDecl);
01162     getStructorImplicitParamDecl(CGF) = VTTDecl;
01163   }
01164 }
01165 
01166 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
01167   /// Initialize the 'this' slot.
01168   EmitThisParam(CGF);
01169 
01170   /// Initialize the 'vtt' slot if needed.
01171   if (getStructorImplicitParamDecl(CGF)) {
01172     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
01173         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
01174   }
01175 
01176   /// If this is a function that the ABI specifies returns 'this', initialize
01177   /// the return slot to 'this' at the start of the function.
01178   ///
01179   /// Unlike the setting of return types, this is done within the ABI
01180   /// implementation instead of by clients of CGCXXABI because:
01181   /// 1) getThisValue is currently protected
01182   /// 2) in theory, an ABI could implement 'this' returns some other way;
01183   ///    HasThisReturn only specifies a contract, not the implementation
01184   if (HasThisReturn(CGF.CurGD))
01185     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
01186 }
01187 
01188 unsigned ItaniumCXXABI::addImplicitConstructorArgs(
01189     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
01190     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
01191   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
01192     return 0;
01193 
01194   // Insert the implicit 'vtt' argument as the second argument.
01195   llvm::Value *VTT =
01196       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
01197   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
01198   Args.insert(Args.begin() + 1,
01199               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
01200   return 1;  // Added one arg.
01201 }
01202 
01203 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
01204                                        const CXXDestructorDecl *DD,
01205                                        CXXDtorType Type, bool ForVirtualBase,
01206                                        bool Delegating, llvm::Value *This) {
01207   GlobalDecl GD(DD, Type);
01208   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
01209   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
01210 
01211   llvm::Value *Callee = nullptr;
01212   if (getContext().getLangOpts().AppleKext)
01213     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
01214 
01215   if (!Callee)
01216     Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
01217 
01218   CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
01219                                   VTTTy, nullptr);
01220 }
01221 
01222 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
01223                                           const CXXRecordDecl *RD) {
01224   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
01225   if (VTable->hasInitializer())
01226     return;
01227 
01228   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
01229   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
01230   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
01231   llvm::Constant *RTTI =
01232       CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
01233 
01234   // Create and set the initializer.
01235   llvm::Constant *Init = CGVT.CreateVTableInitializer(
01236       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
01237       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
01238   VTable->setInitializer(Init);
01239 
01240   // Set the correct linkage.
01241   VTable->setLinkage(Linkage);
01242 
01243   // Set the right visibility.
01244   CGM.setGlobalVisibility(VTable, RD);
01245 
01246   // Use pointer alignment for the vtable. Otherwise we would align them based
01247   // on the size of the initializer which doesn't make sense as only single
01248   // values are read.
01249   unsigned PAlign = CGM.getTarget().getPointerAlign(0);
01250   VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
01251 
01252   // If this is the magic class __cxxabiv1::__fundamental_type_info,
01253   // we will emit the typeinfo for the fundamental types. This is the
01254   // same behaviour as GCC.
01255   const DeclContext *DC = RD->getDeclContext();
01256   if (RD->getIdentifier() &&
01257       RD->getIdentifier()->isStr("__fundamental_type_info") &&
01258       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
01259       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
01260       DC->getParent()->isTranslationUnit())
01261     EmitFundamentalRTTIDescriptors();
01262 }
01263 
01264 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
01265     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
01266     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
01267   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
01268   NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
01269 
01270   llvm::Value *VTableAddressPoint;
01271   if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
01272     // Get the secondary vpointer index.
01273     uint64_t VirtualPointerIndex =
01274         CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
01275 
01276     /// Load the VTT.
01277     llvm::Value *VTT = CGF.LoadCXXVTT();
01278     if (VirtualPointerIndex)
01279       VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
01280 
01281     // And load the address point from the VTT.
01282     VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
01283   } else {
01284     llvm::Constant *VTable =
01285         CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
01286     uint64_t AddressPoint = CGM.getItaniumVTableContext()
01287                                 .getVTableLayout(VTableClass)
01288                                 .getAddressPoint(Base);
01289     VTableAddressPoint =
01290         CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
01291   }
01292 
01293   return VTableAddressPoint;
01294 }
01295 
01296 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
01297     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
01298   llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
01299 
01300   // Find the appropriate vtable within the vtable group.
01301   uint64_t AddressPoint = CGM.getItaniumVTableContext()
01302                               .getVTableLayout(VTableClass)
01303                               .getAddressPoint(Base);
01304   llvm::Value *Indices[] = {
01305     llvm::ConstantInt::get(CGM.Int64Ty, 0),
01306     llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
01307   };
01308 
01309   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
01310 }
01311 
01312 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
01313                                                      CharUnits VPtrOffset) {
01314   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
01315 
01316   llvm::GlobalVariable *&VTable = VTables[RD];
01317   if (VTable)
01318     return VTable;
01319 
01320   // Queue up this v-table for possible deferred emission.
01321   CGM.addDeferredVTable(RD);
01322 
01323   SmallString<256> OutName;
01324   llvm::raw_svector_ostream Out(OutName);
01325   getMangleContext().mangleCXXVTable(RD, Out);
01326   Out.flush();
01327   StringRef Name = OutName.str();
01328 
01329   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
01330   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
01331       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
01332 
01333   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
01334       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
01335   VTable->setUnnamedAddr(true);
01336 
01337   if (RD->hasAttr<DLLImportAttr>())
01338     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
01339   else if (RD->hasAttr<DLLExportAttr>())
01340     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
01341 
01342   return VTable;
01343 }
01344 
01345 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
01346                                                       GlobalDecl GD,
01347                                                       llvm::Value *This,
01348                                                       llvm::Type *Ty) {
01349   GD = GD.getCanonicalDecl();
01350   Ty = Ty->getPointerTo()->getPointerTo();
01351   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
01352 
01353   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
01354   llvm::Value *VFuncPtr =
01355       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
01356   return CGF.Builder.CreateLoad(VFuncPtr);
01357 }
01358 
01359 llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
01360     CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
01361     llvm::Value *This, const CXXMemberCallExpr *CE) {
01362   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
01363   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
01364 
01365   const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
01366       Dtor, getFromDtorType(DtorType));
01367   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
01368   llvm::Value *Callee =
01369       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
01370 
01371   CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
01372                                   /*ImplicitParam=*/nullptr, QualType(), CE);
01373   return nullptr;
01374 }
01375 
01376 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
01377   CodeGenVTables &VTables = CGM.getVTables();
01378   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
01379   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
01380 }
01381 
01382 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
01383                                           llvm::Value *Ptr,
01384                                           int64_t NonVirtualAdjustment,
01385                                           int64_t VirtualAdjustment,
01386                                           bool IsReturnAdjustment) {
01387   if (!NonVirtualAdjustment && !VirtualAdjustment)
01388     return Ptr;
01389 
01390   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
01391   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
01392 
01393   if (NonVirtualAdjustment && !IsReturnAdjustment) {
01394     // Perform the non-virtual adjustment for a base-to-derived cast.
01395     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
01396   }
01397 
01398   if (VirtualAdjustment) {
01399     llvm::Type *PtrDiffTy =
01400         CGF.ConvertType(CGF.getContext().getPointerDiffType());
01401 
01402     // Perform the virtual adjustment.
01403     llvm::Value *VTablePtrPtr =
01404         CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
01405 
01406     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
01407 
01408     llvm::Value *OffsetPtr =
01409         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
01410 
01411     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
01412 
01413     // Load the adjustment offset from the vtable.
01414     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
01415 
01416     // Adjust our pointer.
01417     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
01418   }
01419 
01420   if (NonVirtualAdjustment && IsReturnAdjustment) {
01421     // Perform the non-virtual adjustment for a derived-to-base cast.
01422     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
01423   }
01424 
01425   // Cast back to the original type.
01426   return CGF.Builder.CreateBitCast(V, Ptr->getType());
01427 }
01428 
01429 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
01430                                                   llvm::Value *This,
01431                                                   const ThisAdjustment &TA) {
01432   return performTypeAdjustment(CGF, This, TA.NonVirtual,
01433                                TA.Virtual.Itanium.VCallOffsetOffset,
01434                                /*IsReturnAdjustment=*/false);
01435 }
01436 
01437 llvm::Value *
01438 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
01439                                        const ReturnAdjustment &RA) {
01440   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
01441                                RA.Virtual.Itanium.VBaseOffsetOffset,
01442                                /*IsReturnAdjustment=*/true);
01443 }
01444 
01445 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
01446                                     RValue RV, QualType ResultType) {
01447   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
01448     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
01449 
01450   // Destructor thunks in the ARM ABI have indeterminate results.
01451   llvm::Type *T =
01452     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
01453   RValue Undef = RValue::get(llvm::UndefValue::get(T));
01454   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
01455 }
01456 
01457 /************************** Array allocation cookies **************************/
01458 
01459 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
01460   // The array cookie is a size_t; pad that up to the element alignment.
01461   // The cookie is actually right-justified in that space.
01462   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
01463                   CGM.getContext().getTypeAlignInChars(elementType));
01464 }
01465 
01466 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
01467                                                   llvm::Value *NewPtr,
01468                                                   llvm::Value *NumElements,
01469                                                   const CXXNewExpr *expr,
01470                                                   QualType ElementType) {
01471   assert(requiresArrayCookie(expr));
01472 
01473   unsigned AS = NewPtr->getType()->getPointerAddressSpace();
01474 
01475   ASTContext &Ctx = getContext();
01476   QualType SizeTy = Ctx.getSizeType();
01477   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
01478 
01479   // The size of the cookie.
01480   CharUnits CookieSize =
01481     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
01482   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
01483 
01484   // Compute an offset to the cookie.
01485   llvm::Value *CookiePtr = NewPtr;
01486   CharUnits CookieOffset = CookieSize - SizeSize;
01487   if (!CookieOffset.isZero())
01488     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
01489                                                  CookieOffset.getQuantity());
01490 
01491   // Write the number of elements into the appropriate slot.
01492   llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
01493   llvm::Value *NumElementsPtr =
01494       CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
01495   llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
01496   if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
01497       expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
01498     // The store to the CookiePtr does not need to be instrumented.
01499     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
01500     llvm::FunctionType *FTy =
01501         llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
01502     llvm::Constant *F =
01503         CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
01504     CGF.Builder.CreateCall(F, NumElementsPtr);
01505   }
01506 
01507   // Finally, compute a pointer to the actual data buffer by skipping
01508   // over the cookie completely.
01509   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
01510                                                 CookieSize.getQuantity());  
01511 }
01512 
01513 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
01514                                                 llvm::Value *allocPtr,
01515                                                 CharUnits cookieSize) {
01516   // The element size is right-justified in the cookie.
01517   llvm::Value *numElementsPtr = allocPtr;
01518   CharUnits numElementsOffset =
01519     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
01520   if (!numElementsOffset.isZero())
01521     numElementsPtr =
01522       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
01523                                              numElementsOffset.getQuantity());
01524 
01525   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
01526   numElementsPtr = 
01527     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
01528   if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
01529     return CGF.Builder.CreateLoad(numElementsPtr);
01530   // In asan mode emit a function call instead of a regular load and let the
01531   // run-time deal with it: if the shadow is properly poisoned return the
01532   // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
01533   // We can't simply ignore this load using nosanitize metadata because
01534   // the metadata may be lost.
01535   llvm::FunctionType *FTy =
01536       llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
01537   llvm::Constant *F =
01538       CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
01539   return CGF.Builder.CreateCall(F, numElementsPtr);
01540 }
01541 
01542 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
01543   // ARM says that the cookie is always:
01544   //   struct array_cookie {
01545   //     std::size_t element_size; // element_size != 0
01546   //     std::size_t element_count;
01547   //   };
01548   // But the base ABI doesn't give anything an alignment greater than
01549   // 8, so we can dismiss this as typical ABI-author blindness to
01550   // actual language complexity and round up to the element alignment.
01551   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
01552                   CGM.getContext().getTypeAlignInChars(elementType));
01553 }
01554 
01555 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
01556                                               llvm::Value *newPtr,
01557                                               llvm::Value *numElements,
01558                                               const CXXNewExpr *expr,
01559                                               QualType elementType) {
01560   assert(requiresArrayCookie(expr));
01561 
01562   // NewPtr is a char*, but we generalize to arbitrary addrspaces.
01563   unsigned AS = newPtr->getType()->getPointerAddressSpace();
01564 
01565   // The cookie is always at the start of the buffer.
01566   llvm::Value *cookie = newPtr;
01567 
01568   // The first element is the element size.
01569   cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
01570   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
01571                  getContext().getTypeSizeInChars(elementType).getQuantity());
01572   CGF.Builder.CreateStore(elementSize, cookie);
01573 
01574   // The second element is the element count.
01575   cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
01576   CGF.Builder.CreateStore(numElements, cookie);
01577 
01578   // Finally, compute a pointer to the actual data buffer by skipping
01579   // over the cookie completely.
01580   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
01581   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
01582                                                 cookieSize.getQuantity());
01583 }
01584 
01585 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
01586                                             llvm::Value *allocPtr,
01587                                             CharUnits cookieSize) {
01588   // The number of elements is at offset sizeof(size_t) relative to
01589   // the allocated pointer.
01590   llvm::Value *numElementsPtr
01591     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
01592 
01593   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
01594   numElementsPtr = 
01595     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
01596   return CGF.Builder.CreateLoad(numElementsPtr);
01597 }
01598 
01599 /*********************** Static local initialization **************************/
01600 
01601 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
01602                                          llvm::PointerType *GuardPtrTy) {
01603   // int __cxa_guard_acquire(__guard *guard_object);
01604   llvm::FunctionType *FTy =
01605     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
01606                             GuardPtrTy, /*isVarArg=*/false);
01607   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
01608                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
01609                                               llvm::AttributeSet::FunctionIndex,
01610                                                  llvm::Attribute::NoUnwind));
01611 }
01612 
01613 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
01614                                          llvm::PointerType *GuardPtrTy) {
01615   // void __cxa_guard_release(__guard *guard_object);
01616   llvm::FunctionType *FTy =
01617     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
01618   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
01619                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
01620                                               llvm::AttributeSet::FunctionIndex,
01621                                                  llvm::Attribute::NoUnwind));
01622 }
01623 
01624 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
01625                                        llvm::PointerType *GuardPtrTy) {
01626   // void __cxa_guard_abort(__guard *guard_object);
01627   llvm::FunctionType *FTy =
01628     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
01629   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
01630                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
01631                                               llvm::AttributeSet::FunctionIndex,
01632                                                  llvm::Attribute::NoUnwind));
01633 }
01634 
01635 namespace {
01636   struct CallGuardAbort : EHScopeStack::Cleanup {
01637     llvm::GlobalVariable *Guard;
01638     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
01639 
01640     void Emit(CodeGenFunction &CGF, Flags flags) override {
01641       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
01642                                   Guard);
01643     }
01644   };
01645 }
01646 
01647 /// The ARM code here follows the Itanium code closely enough that we
01648 /// just special-case it at particular places.
01649 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
01650                                     const VarDecl &D,
01651                                     llvm::GlobalVariable *var,
01652                                     bool shouldPerformInit) {
01653   CGBuilderTy &Builder = CGF.Builder;
01654 
01655   // We only need to use thread-safe statics for local non-TLS variables;
01656   // global initialization is always single-threaded.
01657   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
01658                     D.isLocalVarDecl() && !D.getTLSKind();
01659 
01660   // If we have a global variable with internal linkage and thread-safe statics
01661   // are disabled, we can just let the guard variable be of type i8.
01662   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
01663 
01664   llvm::IntegerType *guardTy;
01665   if (useInt8GuardVariable) {
01666     guardTy = CGF.Int8Ty;
01667   } else {
01668     // Guard variables are 64 bits in the generic ABI and size width on ARM
01669     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
01670     guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
01671   }
01672   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
01673 
01674   // Create the guard variable if we don't already have it (as we
01675   // might if we're double-emitting this function body).
01676   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
01677   if (!guard) {
01678     // Mangle the name for the guard.
01679     SmallString<256> guardName;
01680     {
01681       llvm::raw_svector_ostream out(guardName);
01682       getMangleContext().mangleStaticGuardVariable(&D, out);
01683       out.flush();
01684     }
01685 
01686     // Create the guard variable with a zero-initializer.
01687     // Just absorb linkage and visibility from the guarded variable.
01688     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
01689                                      false, var->getLinkage(),
01690                                      llvm::ConstantInt::get(guardTy, 0),
01691                                      guardName.str());
01692     guard->setVisibility(var->getVisibility());
01693     // If the variable is thread-local, so is its guard variable.
01694     guard->setThreadLocalMode(var->getThreadLocalMode());
01695 
01696     // The ABI says: It is suggested that it be emitted in the same COMDAT group
01697     // as the associated data object
01698     if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) {
01699       llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName());
01700       guard->setComdat(C);
01701       var->setComdat(C);
01702       CGF.CurFn->setComdat(C);
01703     }
01704 
01705     CGM.setStaticLocalDeclGuardAddress(&D, guard);
01706   }
01707 
01708   // Test whether the variable has completed initialization.
01709   //
01710   // Itanium C++ ABI 3.3.2:
01711   //   The following is pseudo-code showing how these functions can be used:
01712   //     if (obj_guard.first_byte == 0) {
01713   //       if ( __cxa_guard_acquire (&obj_guard) ) {
01714   //         try {
01715   //           ... initialize the object ...;
01716   //         } catch (...) {
01717   //            __cxa_guard_abort (&obj_guard);
01718   //            throw;
01719   //         }
01720   //         ... queue object destructor with __cxa_atexit() ...;
01721   //         __cxa_guard_release (&obj_guard);
01722   //       }
01723   //     }
01724 
01725   // Load the first byte of the guard variable.
01726   llvm::LoadInst *LI =
01727       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
01728   LI->setAlignment(1);
01729 
01730   // Itanium ABI:
01731   //   An implementation supporting thread-safety on multiprocessor
01732   //   systems must also guarantee that references to the initialized
01733   //   object do not occur before the load of the initialization flag.
01734   //
01735   // In LLVM, we do this by marking the load Acquire.
01736   if (threadsafe)
01737     LI->setAtomic(llvm::Acquire);
01738 
01739   // For ARM, we should only check the first bit, rather than the entire byte:
01740   //
01741   // ARM C++ ABI 3.2.3.1:
01742   //   To support the potential use of initialization guard variables
01743   //   as semaphores that are the target of ARM SWP and LDREX/STREX
01744   //   synchronizing instructions we define a static initialization
01745   //   guard variable to be a 4-byte aligned, 4-byte word with the
01746   //   following inline access protocol.
01747   //     #define INITIALIZED 1
01748   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
01749   //       if (__cxa_guard_acquire(&obj_guard))
01750   //         ...
01751   //     }
01752   //
01753   // and similarly for ARM64:
01754   //
01755   // ARM64 C++ ABI 3.2.2:
01756   //   This ABI instead only specifies the value bit 0 of the static guard
01757   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
01758   //   variable is not initialized and 1 when it is.
01759   llvm::Value *V =
01760       (UseARMGuardVarABI && !useInt8GuardVariable)
01761           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
01762           : LI;
01763   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
01764 
01765   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
01766   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
01767 
01768   // Check if the first byte of the guard variable is zero.
01769   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
01770 
01771   CGF.EmitBlock(InitCheckBlock);
01772 
01773   // Variables used when coping with thread-safe statics and exceptions.
01774   if (threadsafe) {    
01775     // Call __cxa_guard_acquire.
01776     llvm::Value *V
01777       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
01778                
01779     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
01780   
01781     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
01782                          InitBlock, EndBlock);
01783   
01784     // Call __cxa_guard_abort along the exceptional edge.
01785     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
01786     
01787     CGF.EmitBlock(InitBlock);
01788   }
01789 
01790   // Emit the initializer and add a global destructor if appropriate.
01791   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
01792 
01793   if (threadsafe) {
01794     // Pop the guard-abort cleanup if we pushed one.
01795     CGF.PopCleanupBlock();
01796 
01797     // Call __cxa_guard_release.  This cannot throw.
01798     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
01799   } else {
01800     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
01801   }
01802 
01803   CGF.EmitBlock(EndBlock);
01804 }
01805 
01806 /// Register a global destructor using __cxa_atexit.
01807 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
01808                                         llvm::Constant *dtor,
01809                                         llvm::Constant *addr,
01810                                         bool TLS) {
01811   const char *Name = "__cxa_atexit";
01812   if (TLS) {
01813     const llvm::Triple &T = CGF.getTarget().getTriple();
01814     Name = T.isMacOSX() ?  "_tlv_atexit" : "__cxa_thread_atexit";
01815   }
01816 
01817   // We're assuming that the destructor function is something we can
01818   // reasonably call with the default CC.  Go ahead and cast it to the
01819   // right prototype.
01820   llvm::Type *dtorTy =
01821     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
01822 
01823   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
01824   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
01825   llvm::FunctionType *atexitTy =
01826     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
01827 
01828   // Fetch the actual function.
01829   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
01830   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
01831     fn->setDoesNotThrow();
01832 
01833   // Create a variable that binds the atexit to this shared object.
01834   llvm::Constant *handle =
01835     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
01836 
01837   llvm::Value *args[] = {
01838     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
01839     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
01840     handle
01841   };
01842   CGF.EmitNounwindRuntimeCall(atexit, args);
01843 }
01844 
01845 /// Register a global destructor as best as we know how.
01846 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
01847                                        const VarDecl &D,
01848                                        llvm::Constant *dtor,
01849                                        llvm::Constant *addr) {
01850   // Use __cxa_atexit if available.
01851   if (CGM.getCodeGenOpts().CXAAtExit)
01852     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
01853 
01854   if (D.getTLSKind())
01855     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
01856 
01857   // In Apple kexts, we want to add a global destructor entry.
01858   // FIXME: shouldn't this be guarded by some variable?
01859   if (CGM.getLangOpts().AppleKext) {
01860     // Generate a global destructor entry.
01861     return CGM.AddCXXDtorEntry(dtor, addr);
01862   }
01863 
01864   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
01865 }
01866 
01867 static bool isThreadWrapperReplaceable(const VarDecl *VD,
01868                                        CodeGen::CodeGenModule &CGM) {
01869   assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
01870   // OS X prefers to have references to thread local variables to go through
01871   // the thread wrapper instead of directly referencing the backing variable.
01872   return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
01873          CGM.getTarget().getTriple().isMacOSX();
01874 }
01875 
01876 /// Get the appropriate linkage for the wrapper function. This is essentially
01877 /// the weak form of the variable's linkage; every translation unit which needs
01878 /// the wrapper emits a copy, and we want the linker to merge them.
01879 static llvm::GlobalValue::LinkageTypes
01880 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
01881   llvm::GlobalValue::LinkageTypes VarLinkage =
01882       CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
01883 
01884   // For internal linkage variables, we don't need an external or weak wrapper.
01885   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
01886     return VarLinkage;
01887 
01888   // If the thread wrapper is replaceable, give it appropriate linkage.
01889   if (isThreadWrapperReplaceable(VD, CGM)) {
01890     if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
01891         llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
01892       return llvm::GlobalVariable::WeakAnyLinkage;
01893     return VarLinkage;
01894   }
01895   return llvm::GlobalValue::WeakODRLinkage;
01896 }
01897 
01898 llvm::Function *
01899 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
01900                                              llvm::Value *Val) {
01901   // Mangle the name for the thread_local wrapper function.
01902   SmallString<256> WrapperName;
01903   {
01904     llvm::raw_svector_ostream Out(WrapperName);
01905     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
01906     Out.flush();
01907   }
01908 
01909   if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
01910     return cast<llvm::Function>(V);
01911 
01912   llvm::Type *RetTy = Val->getType();
01913   if (VD->getType()->isReferenceType())
01914     RetTy = RetTy->getPointerElementType();
01915 
01916   llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
01917   llvm::Function *Wrapper =
01918       llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
01919                              WrapperName.str(), &CGM.getModule());
01920   // Always resolve references to the wrapper at link time.
01921   if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
01922     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
01923   return Wrapper;
01924 }
01925 
01926 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
01927     CodeGenModule &CGM,
01928     ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *>>
01929         CXXThreadLocals, ArrayRef<llvm::Function *> CXXThreadLocalInits,
01930     ArrayRef<llvm::GlobalVariable *> CXXThreadLocalInitVars) {
01931   llvm::Function *InitFunc = nullptr;
01932   if (!CXXThreadLocalInits.empty()) {
01933     // Generate a guarded initialization function.
01934     llvm::FunctionType *FTy =
01935         llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
01936     InitFunc = CGM.CreateGlobalInitOrDestructFunction(FTy, "__tls_init",
01937                                                       SourceLocation(),
01938                                                       /*TLS=*/true);
01939     llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
01940         CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
01941         llvm::GlobalVariable::InternalLinkage,
01942         llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
01943     Guard->setThreadLocal(true);
01944     CodeGenFunction(CGM)
01945         .GenerateCXXGlobalInitFunc(InitFunc, CXXThreadLocalInits, Guard);
01946   }
01947   for (unsigned I = 0, N = CXXThreadLocals.size(); I != N; ++I) {
01948     const VarDecl *VD = CXXThreadLocals[I].first;
01949     llvm::GlobalVariable *Var = CXXThreadLocals[I].second;
01950 
01951     // Some targets require that all access to thread local variables go through
01952     // the thread wrapper.  This means that we cannot attempt to create a thread
01953     // wrapper or a thread helper.
01954     if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
01955       continue;
01956 
01957     // Mangle the name for the thread_local initialization function.
01958     SmallString<256> InitFnName;
01959     {
01960       llvm::raw_svector_ostream Out(InitFnName);
01961       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
01962       Out.flush();
01963     }
01964 
01965     // If we have a definition for the variable, emit the initialization
01966     // function as an alias to the global Init function (if any). Otherwise,
01967     // produce a declaration of the initialization function.
01968     llvm::GlobalValue *Init = nullptr;
01969     bool InitIsInitFunc = false;
01970     if (VD->hasDefinition()) {
01971       InitIsInitFunc = true;
01972       if (InitFunc)
01973         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
01974                                          InitFunc);
01975     } else {
01976       // Emit a weak global function referring to the initialization function.
01977       // This function will not exist if the TU defining the thread_local
01978       // variable in question does not need any dynamic initialization for
01979       // its thread_local variables.
01980       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
01981       Init = llvm::Function::Create(
01982           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
01983           &CGM.getModule());
01984     }
01985 
01986     if (Init)
01987       Init->setVisibility(Var->getVisibility());
01988 
01989     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
01990     llvm::LLVMContext &Context = CGM.getModule().getContext();
01991     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
01992     CGBuilderTy Builder(Entry);
01993     if (InitIsInitFunc) {
01994       if (Init)
01995         Builder.CreateCall(Init);
01996     } else {
01997       // Don't know whether we have an init function. Call it if it exists.
01998       llvm::Value *Have = Builder.CreateIsNotNull(Init);
01999       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
02000       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
02001       Builder.CreateCondBr(Have, InitBB, ExitBB);
02002 
02003       Builder.SetInsertPoint(InitBB);
02004       Builder.CreateCall(Init);
02005       Builder.CreateBr(ExitBB);
02006 
02007       Builder.SetInsertPoint(ExitBB);
02008     }
02009 
02010     // For a reference, the result of the wrapper function is a pointer to
02011     // the referenced object.
02012     llvm::Value *Val = Var;
02013     if (VD->getType()->isReferenceType()) {
02014       llvm::LoadInst *LI = Builder.CreateLoad(Val);
02015       LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
02016       Val = LI;
02017     }
02018     if (Val->getType() != Wrapper->getReturnType())
02019       Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
02020           Val, Wrapper->getReturnType(), "");
02021     Builder.CreateRet(Val);
02022   }
02023 }
02024 
02025 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
02026                                                    const VarDecl *VD,
02027                                                    QualType LValType) {
02028   QualType T = VD->getType();
02029   llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
02030   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
02031   llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
02032 
02033   Val = CGF.Builder.CreateCall(Wrapper);
02034 
02035   LValue LV;
02036   if (VD->getType()->isReferenceType())
02037     LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
02038   else
02039     LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
02040   // FIXME: need setObjCGCLValueClass?
02041   return LV;
02042 }
02043 
02044 /// Return whether the given global decl needs a VTT parameter, which it does
02045 /// if it's a base constructor or destructor with virtual bases.
02046 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
02047   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02048   
02049   // We don't have any virtual bases, just return early.
02050   if (!MD->getParent()->getNumVBases())
02051     return false;
02052   
02053   // Check if we have a base constructor.
02054   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
02055     return true;
02056 
02057   // Check if we have a base destructor.
02058   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
02059     return true;
02060   
02061   return false;
02062 }
02063 
02064 namespace {
02065 class ItaniumRTTIBuilder {
02066   CodeGenModule &CGM;  // Per-module state.
02067   llvm::LLVMContext &VMContext;
02068   const ItaniumCXXABI &CXXABI;  // Per-module state.
02069 
02070   /// Fields - The fields of the RTTI descriptor currently being built.
02071   SmallVector<llvm::Constant *, 16> Fields;
02072 
02073   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
02074   llvm::GlobalVariable *
02075   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
02076 
02077   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
02078   /// descriptor of the given type.
02079   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
02080 
02081   /// BuildVTablePointer - Build the vtable pointer for the given type.
02082   void BuildVTablePointer(const Type *Ty);
02083 
02084   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
02085   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
02086   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
02087 
02088   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
02089   /// classes with bases that do not satisfy the abi::__si_class_type_info
02090   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
02091   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
02092 
02093   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
02094   /// for pointer types.
02095   void BuildPointerTypeInfo(QualType PointeeTy);
02096 
02097   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
02098   /// type_info for an object type.
02099   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
02100 
02101   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
02102   /// struct, used for member pointer types.
02103   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
02104 
02105 public:
02106   ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
02107       : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
02108 
02109   // Pointer type info flags.
02110   enum {
02111     /// PTI_Const - Type has const qualifier.
02112     PTI_Const = 0x1,
02113 
02114     /// PTI_Volatile - Type has volatile qualifier.
02115     PTI_Volatile = 0x2,
02116 
02117     /// PTI_Restrict - Type has restrict qualifier.
02118     PTI_Restrict = 0x4,
02119 
02120     /// PTI_Incomplete - Type is incomplete.
02121     PTI_Incomplete = 0x8,
02122 
02123     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
02124     /// (in pointer to member).
02125     PTI_ContainingClassIncomplete = 0x10
02126   };
02127 
02128   // VMI type info flags.
02129   enum {
02130     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
02131     VMI_NonDiamondRepeat = 0x1,
02132 
02133     /// VMI_DiamondShaped - Class is diamond shaped.
02134     VMI_DiamondShaped = 0x2
02135   };
02136 
02137   // Base class type info flags.
02138   enum {
02139     /// BCTI_Virtual - Base class is virtual.
02140     BCTI_Virtual = 0x1,
02141 
02142     /// BCTI_Public - Base class is public.
02143     BCTI_Public = 0x2
02144   };
02145 
02146   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
02147   ///
02148   /// \param Force - true to force the creation of this RTTI value
02149   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
02150 };
02151 }
02152 
02153 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
02154     QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
02155   SmallString<256> OutName;
02156   llvm::raw_svector_ostream Out(OutName);
02157   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
02158   Out.flush();
02159   StringRef Name = OutName.str();
02160 
02161   // We know that the mangled name of the type starts at index 4 of the
02162   // mangled name of the typename, so we can just index into it in order to
02163   // get the mangled name of the type.
02164   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
02165                                                             Name.substr(4));
02166 
02167   llvm::GlobalVariable *GV =
02168     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
02169 
02170   GV->setInitializer(Init);
02171 
02172   return GV;
02173 }
02174 
02175 llvm::Constant *
02176 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
02177   // Mangle the RTTI name.
02178   SmallString<256> OutName;
02179   llvm::raw_svector_ostream Out(OutName);
02180   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
02181   Out.flush();
02182   StringRef Name = OutName.str();
02183 
02184   // Look for an existing global.
02185   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
02186 
02187   if (!GV) {
02188     // Create a new global variable.
02189     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
02190                                   /*Constant=*/true,
02191                                   llvm::GlobalValue::ExternalLinkage, nullptr,
02192                                   Name);
02193     if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
02194       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
02195       if (RD->hasAttr<DLLImportAttr>())
02196         GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
02197     }
02198   }
02199 
02200   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
02201 }
02202 
02203 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
02204 /// info for that type is defined in the standard library.
02205 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
02206   // Itanium C++ ABI 2.9.2:
02207   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
02208   //   the run-time support library. Specifically, the run-time support
02209   //   library should contain type_info objects for the types X, X* and
02210   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
02211   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
02212   //   long, unsigned long, long long, unsigned long long, float, double,
02213   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
02214   //   half-precision floating point types.
02215   switch (Ty->getKind()) {
02216     case BuiltinType::Void:
02217     case BuiltinType::NullPtr:
02218     case BuiltinType::Bool:
02219     case BuiltinType::WChar_S:
02220     case BuiltinType::WChar_U:
02221     case BuiltinType::Char_U:
02222     case BuiltinType::Char_S:
02223     case BuiltinType::UChar:
02224     case BuiltinType::SChar:
02225     case BuiltinType::Short:
02226     case BuiltinType::UShort:
02227     case BuiltinType::Int:
02228     case BuiltinType::UInt:
02229     case BuiltinType::Long:
02230     case BuiltinType::ULong:
02231     case BuiltinType::LongLong:
02232     case BuiltinType::ULongLong:
02233     case BuiltinType::Half:
02234     case BuiltinType::Float:
02235     case BuiltinType::Double:
02236     case BuiltinType::LongDouble:
02237     case BuiltinType::Char16:
02238     case BuiltinType::Char32:
02239     case BuiltinType::Int128:
02240     case BuiltinType::UInt128:
02241     case BuiltinType::OCLImage1d:
02242     case BuiltinType::OCLImage1dArray:
02243     case BuiltinType::OCLImage1dBuffer:
02244     case BuiltinType::OCLImage2d:
02245     case BuiltinType::OCLImage2dArray:
02246     case BuiltinType::OCLImage3d:
02247     case BuiltinType::OCLSampler:
02248     case BuiltinType::OCLEvent:
02249       return true;
02250 
02251     case BuiltinType::Dependent:
02252 #define BUILTIN_TYPE(Id, SingletonId)
02253 #define PLACEHOLDER_TYPE(Id, SingletonId) \
02254     case BuiltinType::Id:
02255 #include "clang/AST/BuiltinTypes.def"
02256       llvm_unreachable("asking for RRTI for a placeholder type!");
02257 
02258     case BuiltinType::ObjCId:
02259     case BuiltinType::ObjCClass:
02260     case BuiltinType::ObjCSel:
02261       llvm_unreachable("FIXME: Objective-C types are unsupported!");
02262   }
02263 
02264   llvm_unreachable("Invalid BuiltinType Kind!");
02265 }
02266 
02267 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
02268   QualType PointeeTy = PointerTy->getPointeeType();
02269   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
02270   if (!BuiltinTy)
02271     return false;
02272 
02273   // Check the qualifiers.
02274   Qualifiers Quals = PointeeTy.getQualifiers();
02275   Quals.removeConst();
02276 
02277   if (!Quals.empty())
02278     return false;
02279 
02280   return TypeInfoIsInStandardLibrary(BuiltinTy);
02281 }
02282 
02283 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
02284 /// information for the given type exists in the standard library.
02285 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
02286   // Type info for builtin types is defined in the standard library.
02287   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
02288     return TypeInfoIsInStandardLibrary(BuiltinTy);
02289 
02290   // Type info for some pointer types to builtin types is defined in the
02291   // standard library.
02292   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
02293     return TypeInfoIsInStandardLibrary(PointerTy);
02294 
02295   return false;
02296 }
02297 
02298 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
02299 /// the given type exists somewhere else, and that we should not emit the type
02300 /// information in this translation unit.  Assumes that it is not a
02301 /// standard-library type.
02302 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
02303                                             QualType Ty) {
02304   ASTContext &Context = CGM.getContext();
02305 
02306   // If RTTI is disabled, assume it might be disabled in the
02307   // translation unit that defines any potential key function, too.
02308   if (!Context.getLangOpts().RTTI) return false;
02309 
02310   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
02311     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
02312     if (!RD->hasDefinition())
02313       return false;
02314 
02315     if (!RD->isDynamicClass())
02316       return false;
02317 
02318     // FIXME: this may need to be reconsidered if the key function
02319     // changes.
02320     if (CGM.getVTables().isVTableExternal(RD))
02321       return true;
02322 
02323     if (RD->hasAttr<DLLImportAttr>())
02324       return true;
02325   }
02326 
02327   return false;
02328 }
02329 
02330 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
02331 static bool IsIncompleteClassType(const RecordType *RecordTy) {
02332   return !RecordTy->getDecl()->isCompleteDefinition();
02333 }
02334 
02335 /// ContainsIncompleteClassType - Returns whether the given type contains an
02336 /// incomplete class type. This is true if
02337 ///
02338 ///   * The given type is an incomplete class type.
02339 ///   * The given type is a pointer type whose pointee type contains an
02340 ///     incomplete class type.
02341 ///   * The given type is a member pointer type whose class is an incomplete
02342 ///     class type.
02343 ///   * The given type is a member pointer type whoise pointee type contains an
02344 ///     incomplete class type.
02345 /// is an indirect or direct pointer to an incomplete class type.
02346 static bool ContainsIncompleteClassType(QualType Ty) {
02347   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
02348     if (IsIncompleteClassType(RecordTy))
02349       return true;
02350   }
02351 
02352   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
02353     return ContainsIncompleteClassType(PointerTy->getPointeeType());
02354 
02355   if (const MemberPointerType *MemberPointerTy =
02356       dyn_cast<MemberPointerType>(Ty)) {
02357     // Check if the class type is incomplete.
02358     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
02359     if (IsIncompleteClassType(ClassType))
02360       return true;
02361 
02362     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
02363   }
02364 
02365   return false;
02366 }
02367 
02368 // CanUseSingleInheritance - Return whether the given record decl has a "single,
02369 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
02370 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
02371 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
02372   // Check the number of bases.
02373   if (RD->getNumBases() != 1)
02374     return false;
02375 
02376   // Get the base.
02377   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
02378 
02379   // Check that the base is not virtual.
02380   if (Base->isVirtual())
02381     return false;
02382 
02383   // Check that the base is public.
02384   if (Base->getAccessSpecifier() != AS_public)
02385     return false;
02386 
02387   // Check that the class is dynamic iff the base is.
02388   const CXXRecordDecl *BaseDecl =
02389     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
02390   if (!BaseDecl->isEmpty() &&
02391       BaseDecl->isDynamicClass() != RD->isDynamicClass())
02392     return false;
02393 
02394   return true;
02395 }
02396 
02397 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
02398   // abi::__class_type_info.
02399   static const char * const ClassTypeInfo =
02400     "_ZTVN10__cxxabiv117__class_type_infoE";
02401   // abi::__si_class_type_info.
02402   static const char * const SIClassTypeInfo =
02403     "_ZTVN10__cxxabiv120__si_class_type_infoE";
02404   // abi::__vmi_class_type_info.
02405   static const char * const VMIClassTypeInfo =
02406     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
02407 
02408   const char *VTableName = nullptr;
02409 
02410   switch (Ty->getTypeClass()) {
02411 #define TYPE(Class, Base)
02412 #define ABSTRACT_TYPE(Class, Base)
02413 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
02414 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
02415 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
02416 #include "clang/AST/TypeNodes.def"
02417     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
02418 
02419   case Type::LValueReference:
02420   case Type::RValueReference:
02421     llvm_unreachable("References shouldn't get here");
02422 
02423   case Type::Auto:
02424     llvm_unreachable("Undeduced auto type shouldn't get here");
02425 
02426   case Type::Builtin:
02427   // GCC treats vector and complex types as fundamental types.
02428   case Type::Vector:
02429   case Type::ExtVector:
02430   case Type::Complex:
02431   case Type::Atomic:
02432   // FIXME: GCC treats block pointers as fundamental types?!
02433   case Type::BlockPointer:
02434     // abi::__fundamental_type_info.
02435     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
02436     break;
02437 
02438   case Type::ConstantArray:
02439   case Type::IncompleteArray:
02440   case Type::VariableArray:
02441     // abi::__array_type_info.
02442     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
02443     break;
02444 
02445   case Type::FunctionNoProto:
02446   case Type::FunctionProto:
02447     // abi::__function_type_info.
02448     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
02449     break;
02450 
02451   case Type::Enum:
02452     // abi::__enum_type_info.
02453     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
02454     break;
02455 
02456   case Type::Record: {
02457     const CXXRecordDecl *RD =
02458       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
02459 
02460     if (!RD->hasDefinition() || !RD->getNumBases()) {
02461       VTableName = ClassTypeInfo;
02462     } else if (CanUseSingleInheritance(RD)) {
02463       VTableName = SIClassTypeInfo;
02464     } else {
02465       VTableName = VMIClassTypeInfo;
02466     }
02467 
02468     break;
02469   }
02470 
02471   case Type::ObjCObject:
02472     // Ignore protocol qualifiers.
02473     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
02474 
02475     // Handle id and Class.
02476     if (isa<BuiltinType>(Ty)) {
02477       VTableName = ClassTypeInfo;
02478       break;
02479     }
02480 
02481     assert(isa<ObjCInterfaceType>(Ty));
02482     // Fall through.
02483 
02484   case Type::ObjCInterface:
02485     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
02486       VTableName = SIClassTypeInfo;
02487     } else {
02488       VTableName = ClassTypeInfo;
02489     }
02490     break;
02491 
02492   case Type::ObjCObjectPointer:
02493   case Type::Pointer:
02494     // abi::__pointer_type_info.
02495     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
02496     break;
02497 
02498   case Type::MemberPointer:
02499     // abi::__pointer_to_member_type_info.
02500     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
02501     break;
02502   }
02503 
02504   llvm::Constant *VTable =
02505     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
02506 
02507   llvm::Type *PtrDiffTy =
02508     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
02509 
02510   // The vtable address point is 2.
02511   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
02512   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
02513   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
02514 
02515   Fields.push_back(VTable);
02516 }
02517 
02518 /// \brief Return the linkage that the type info and type info name constants
02519 /// should have for the given type.
02520 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
02521                                                              QualType Ty) {
02522   // Itanium C++ ABI 2.9.5p7:
02523   //   In addition, it and all of the intermediate abi::__pointer_type_info
02524   //   structs in the chain down to the abi::__class_type_info for the
02525   //   incomplete class type must be prevented from resolving to the
02526   //   corresponding type_info structs for the complete class type, possibly
02527   //   by making them local static objects. Finally, a dummy class RTTI is
02528   //   generated for the incomplete type that will not resolve to the final
02529   //   complete class RTTI (because the latter need not exist), possibly by
02530   //   making it a local static object.
02531   if (ContainsIncompleteClassType(Ty))
02532     return llvm::GlobalValue::InternalLinkage;
02533 
02534   switch (Ty->getLinkage()) {
02535   case NoLinkage:
02536   case InternalLinkage:
02537   case UniqueExternalLinkage:
02538     return llvm::GlobalValue::InternalLinkage;
02539 
02540   case VisibleNoLinkage:
02541   case ExternalLinkage:
02542     if (!CGM.getLangOpts().RTTI) {
02543       // RTTI is not enabled, which means that this type info struct is going
02544       // to be used for exception handling. Give it linkonce_odr linkage.
02545       return llvm::GlobalValue::LinkOnceODRLinkage;
02546     }
02547 
02548     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
02549       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
02550       if (RD->hasAttr<WeakAttr>())
02551         return llvm::GlobalValue::WeakODRLinkage;
02552       if (RD->isDynamicClass())
02553         return CGM.getVTableLinkage(RD);
02554     }
02555 
02556     return llvm::GlobalValue::LinkOnceODRLinkage;
02557   }
02558 
02559   llvm_unreachable("Invalid linkage!");
02560 }
02561 
02562 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
02563   // We want to operate on the canonical type.
02564   Ty = CGM.getContext().getCanonicalType(Ty);
02565 
02566   // Check if we've already emitted an RTTI descriptor for this type.
02567   SmallString<256> OutName;
02568   llvm::raw_svector_ostream Out(OutName);
02569   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
02570   Out.flush();
02571   StringRef Name = OutName.str();
02572 
02573   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
02574   if (OldGV && !OldGV->isDeclaration()) {
02575     assert(!OldGV->hasAvailableExternallyLinkage() &&
02576            "available_externally typeinfos not yet implemented");
02577 
02578     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
02579   }
02580 
02581   // Check if there is already an external RTTI descriptor for this type.
02582   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
02583   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
02584     return GetAddrOfExternalRTTIDescriptor(Ty);
02585 
02586   // Emit the standard library with external linkage.
02587   llvm::GlobalVariable::LinkageTypes Linkage;
02588   if (IsStdLib)
02589     Linkage = llvm::GlobalValue::ExternalLinkage;
02590   else
02591     Linkage = getTypeInfoLinkage(CGM, Ty);
02592 
02593   // Add the vtable pointer.
02594   BuildVTablePointer(cast<Type>(Ty));
02595 
02596   // And the name.
02597   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
02598   llvm::Constant *TypeNameField;
02599 
02600   // If we're supposed to demote the visibility, be sure to set a flag
02601   // to use a string comparison for type_info comparisons.
02602   ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
02603       CXXABI.classifyRTTIUniqueness(Ty, Linkage);
02604   if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
02605     // The flag is the sign bit, which on ARM64 is defined to be clear
02606     // for global pointers.  This is very ARM64-specific.
02607     TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
02608     llvm::Constant *flag =
02609         llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
02610     TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
02611     TypeNameField =
02612         llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
02613   } else {
02614     TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
02615   }
02616   Fields.push_back(TypeNameField);
02617 
02618   switch (Ty->getTypeClass()) {
02619 #define TYPE(Class, Base)
02620 #define ABSTRACT_TYPE(Class, Base)
02621 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
02622 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
02623 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
02624 #include "clang/AST/TypeNodes.def"
02625     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
02626 
02627   // GCC treats vector types as fundamental types.
02628   case Type::Builtin:
02629   case Type::Vector:
02630   case Type::ExtVector:
02631   case Type::Complex:
02632   case Type::BlockPointer:
02633     // Itanium C++ ABI 2.9.5p4:
02634     // abi::__fundamental_type_info adds no data members to std::type_info.
02635     break;
02636 
02637   case Type::LValueReference:
02638   case Type::RValueReference:
02639     llvm_unreachable("References shouldn't get here");
02640 
02641   case Type::Auto:
02642     llvm_unreachable("Undeduced auto type shouldn't get here");
02643 
02644   case Type::ConstantArray:
02645   case Type::IncompleteArray:
02646   case Type::VariableArray:
02647     // Itanium C++ ABI 2.9.5p5:
02648     // abi::__array_type_info adds no data members to std::type_info.
02649     break;
02650 
02651   case Type::FunctionNoProto:
02652   case Type::FunctionProto:
02653     // Itanium C++ ABI 2.9.5p5:
02654     // abi::__function_type_info adds no data members to std::type_info.
02655     break;
02656 
02657   case Type::Enum:
02658     // Itanium C++ ABI 2.9.5p5:
02659     // abi::__enum_type_info adds no data members to std::type_info.
02660     break;
02661 
02662   case Type::Record: {
02663     const CXXRecordDecl *RD =
02664       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
02665     if (!RD->hasDefinition() || !RD->getNumBases()) {
02666       // We don't need to emit any fields.
02667       break;
02668     }
02669 
02670     if (CanUseSingleInheritance(RD))
02671       BuildSIClassTypeInfo(RD);
02672     else
02673       BuildVMIClassTypeInfo(RD);
02674 
02675     break;
02676   }
02677 
02678   case Type::ObjCObject:
02679   case Type::ObjCInterface:
02680     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
02681     break;
02682 
02683   case Type::ObjCObjectPointer:
02684     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
02685     break;
02686 
02687   case Type::Pointer:
02688     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
02689     break;
02690 
02691   case Type::MemberPointer:
02692     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
02693     break;
02694 
02695   case Type::Atomic:
02696     // No fields, at least for the moment.
02697     break;
02698   }
02699 
02700   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
02701 
02702   llvm::GlobalVariable *GV =
02703     new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
02704                              /*Constant=*/true, Linkage, Init, Name);
02705 
02706   // If there's already an old global variable, replace it with the new one.
02707   if (OldGV) {
02708     GV->takeName(OldGV);
02709     llvm::Constant *NewPtr =
02710       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
02711     OldGV->replaceAllUsesWith(NewPtr);
02712     OldGV->eraseFromParent();
02713   }
02714 
02715   // The Itanium ABI specifies that type_info objects must be globally
02716   // unique, with one exception: if the type is an incomplete class
02717   // type or a (possibly indirect) pointer to one.  That exception
02718   // affects the general case of comparing type_info objects produced
02719   // by the typeid operator, which is why the comparison operators on
02720   // std::type_info generally use the type_info name pointers instead
02721   // of the object addresses.  However, the language's built-in uses
02722   // of RTTI generally require class types to be complete, even when
02723   // manipulating pointers to those class types.  This allows the
02724   // implementation of dynamic_cast to rely on address equality tests,
02725   // which is much faster.
02726 
02727   // All of this is to say that it's important that both the type_info
02728   // object and the type_info name be uniqued when weakly emitted.
02729 
02730   // Give the type_info object and name the formal visibility of the
02731   // type itself.
02732   llvm::GlobalValue::VisibilityTypes llvmVisibility;
02733   if (llvm::GlobalValue::isLocalLinkage(Linkage))
02734     // If the linkage is local, only default visibility makes sense.
02735     llvmVisibility = llvm::GlobalValue::DefaultVisibility;
02736   else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
02737     llvmVisibility = llvm::GlobalValue::HiddenVisibility;
02738   else
02739     llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
02740   TypeName->setVisibility(llvmVisibility);
02741   GV->setVisibility(llvmVisibility);
02742 
02743   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
02744 }
02745 
02746 /// ComputeQualifierFlags - Compute the pointer type info flags from the
02747 /// given qualifier.
02748 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
02749   unsigned Flags = 0;
02750 
02751   if (Quals.hasConst())
02752     Flags |= ItaniumRTTIBuilder::PTI_Const;
02753   if (Quals.hasVolatile())
02754     Flags |= ItaniumRTTIBuilder::PTI_Volatile;
02755   if (Quals.hasRestrict())
02756     Flags |= ItaniumRTTIBuilder::PTI_Restrict;
02757 
02758   return Flags;
02759 }
02760 
02761 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
02762 /// for the given Objective-C object type.
02763 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
02764   // Drop qualifiers.
02765   const Type *T = OT->getBaseType().getTypePtr();
02766   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
02767 
02768   // The builtin types are abi::__class_type_infos and don't require
02769   // extra fields.
02770   if (isa<BuiltinType>(T)) return;
02771 
02772   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
02773   ObjCInterfaceDecl *Super = Class->getSuperClass();
02774 
02775   // Root classes are also __class_type_info.
02776   if (!Super) return;
02777 
02778   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
02779 
02780   // Everything else is single inheritance.
02781   llvm::Constant *BaseTypeInfo =
02782       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
02783   Fields.push_back(BaseTypeInfo);
02784 }
02785 
02786 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
02787 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
02788 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
02789   // Itanium C++ ABI 2.9.5p6b:
02790   // It adds to abi::__class_type_info a single member pointing to the
02791   // type_info structure for the base type,
02792   llvm::Constant *BaseTypeInfo =
02793     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
02794   Fields.push_back(BaseTypeInfo);
02795 }
02796 
02797 namespace {
02798   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
02799   /// a class hierarchy.
02800   struct SeenBases {
02801     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
02802     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
02803   };
02804 }
02805 
02806 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
02807 /// abi::__vmi_class_type_info.
02808 ///
02809 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
02810                                              SeenBases &Bases) {
02811 
02812   unsigned Flags = 0;
02813 
02814   const CXXRecordDecl *BaseDecl =
02815     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
02816 
02817   if (Base->isVirtual()) {
02818     // Mark the virtual base as seen.
02819     if (!Bases.VirtualBases.insert(BaseDecl)) {
02820       // If this virtual base has been seen before, then the class is diamond
02821       // shaped.
02822       Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
02823     } else {
02824       if (Bases.NonVirtualBases.count(BaseDecl))
02825         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
02826     }
02827   } else {
02828     // Mark the non-virtual base as seen.
02829     if (!Bases.NonVirtualBases.insert(BaseDecl)) {
02830       // If this non-virtual base has been seen before, then the class has non-
02831       // diamond shaped repeated inheritance.
02832       Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
02833     } else {
02834       if (Bases.VirtualBases.count(BaseDecl))
02835         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
02836     }
02837   }
02838 
02839   // Walk all bases.
02840   for (const auto &I : BaseDecl->bases())
02841     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
02842 
02843   return Flags;
02844 }
02845 
02846 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
02847   unsigned Flags = 0;
02848   SeenBases Bases;
02849 
02850   // Walk all bases.
02851   for (const auto &I : RD->bases())
02852     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
02853 
02854   return Flags;
02855 }
02856 
02857 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
02858 /// classes with bases that do not satisfy the abi::__si_class_type_info
02859 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
02860 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
02861   llvm::Type *UnsignedIntLTy =
02862     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
02863 
02864   // Itanium C++ ABI 2.9.5p6c:
02865   //   __flags is a word with flags describing details about the class
02866   //   structure, which may be referenced by using the __flags_masks
02867   //   enumeration. These flags refer to both direct and indirect bases.
02868   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
02869   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
02870 
02871   // Itanium C++ ABI 2.9.5p6c:
02872   //   __base_count is a word with the number of direct proper base class
02873   //   descriptions that follow.
02874   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
02875 
02876   if (!RD->getNumBases())
02877     return;
02878 
02879   llvm::Type *LongLTy =
02880     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
02881 
02882   // Now add the base class descriptions.
02883 
02884   // Itanium C++ ABI 2.9.5p6c:
02885   //   __base_info[] is an array of base class descriptions -- one for every
02886   //   direct proper base. Each description is of the type:
02887   //
02888   //   struct abi::__base_class_type_info {
02889   //   public:
02890   //     const __class_type_info *__base_type;
02891   //     long __offset_flags;
02892   //
02893   //     enum __offset_flags_masks {
02894   //       __virtual_mask = 0x1,
02895   //       __public_mask = 0x2,
02896   //       __offset_shift = 8
02897   //     };
02898   //   };
02899   for (const auto &Base : RD->bases()) {
02900     // The __base_type member points to the RTTI for the base type.
02901     Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
02902 
02903     const CXXRecordDecl *BaseDecl =
02904       cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
02905 
02906     int64_t OffsetFlags = 0;
02907 
02908     // All but the lower 8 bits of __offset_flags are a signed offset.
02909     // For a non-virtual base, this is the offset in the object of the base
02910     // subobject. For a virtual base, this is the offset in the virtual table of
02911     // the virtual base offset for the virtual base referenced (negative).
02912     CharUnits Offset;
02913     if (Base.isVirtual())
02914       Offset =
02915         CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
02916     else {
02917       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
02918       Offset = Layout.getBaseClassOffset(BaseDecl);
02919     };
02920 
02921     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
02922 
02923     // The low-order byte of __offset_flags contains flags, as given by the
02924     // masks from the enumeration __offset_flags_masks.
02925     if (Base.isVirtual())
02926       OffsetFlags |= BCTI_Virtual;
02927     if (Base.getAccessSpecifier() == AS_public)
02928       OffsetFlags |= BCTI_Public;
02929 
02930     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
02931   }
02932 }
02933 
02934 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
02935 /// used for pointer types.
02936 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
02937   Qualifiers Quals;
02938   QualType UnqualifiedPointeeTy =
02939     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
02940 
02941   // Itanium C++ ABI 2.9.5p7:
02942   //   __flags is a flag word describing the cv-qualification and other
02943   //   attributes of the type pointed to
02944   unsigned Flags = ComputeQualifierFlags(Quals);
02945 
02946   // Itanium C++ ABI 2.9.5p7:
02947   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
02948   //   incomplete class type, the incomplete target type flag is set.
02949   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
02950     Flags |= PTI_Incomplete;
02951 
02952   llvm::Type *UnsignedIntLTy =
02953     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
02954   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
02955 
02956   // Itanium C++ ABI 2.9.5p7:
02957   //  __pointee is a pointer to the std::type_info derivation for the
02958   //  unqualified type being pointed to.
02959   llvm::Constant *PointeeTypeInfo =
02960     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
02961   Fields.push_back(PointeeTypeInfo);
02962 }
02963 
02964 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
02965 /// struct, used for member pointer types.
02966 void
02967 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
02968   QualType PointeeTy = Ty->getPointeeType();
02969 
02970   Qualifiers Quals;
02971   QualType UnqualifiedPointeeTy =
02972     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
02973 
02974   // Itanium C++ ABI 2.9.5p7:
02975   //   __flags is a flag word describing the cv-qualification and other
02976   //   attributes of the type pointed to.
02977   unsigned Flags = ComputeQualifierFlags(Quals);
02978 
02979   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
02980 
02981   // Itanium C++ ABI 2.9.5p7:
02982   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
02983   //   incomplete class type, the incomplete target type flag is set.
02984   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
02985     Flags |= PTI_Incomplete;
02986 
02987   if (IsIncompleteClassType(ClassType))
02988     Flags |= PTI_ContainingClassIncomplete;
02989 
02990   llvm::Type *UnsignedIntLTy =
02991     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
02992   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
02993 
02994   // Itanium C++ ABI 2.9.5p7:
02995   //   __pointee is a pointer to the std::type_info derivation for the
02996   //   unqualified type being pointed to.
02997   llvm::Constant *PointeeTypeInfo =
02998     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
02999   Fields.push_back(PointeeTypeInfo);
03000 
03001   // Itanium C++ ABI 2.9.5p9:
03002   //   __context is a pointer to an abi::__class_type_info corresponding to the
03003   //   class type containing the member pointed to
03004   //   (e.g., the "A" in "int A::*").
03005   Fields.push_back(
03006       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
03007 }
03008 
03009 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
03010   return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
03011 }
03012 
03013 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
03014   QualType PointerType = getContext().getPointerType(Type);
03015   QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
03016   ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
03017   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
03018   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
03019 }
03020 
03021 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
03022   QualType FundamentalTypes[] = {
03023       getContext().VoidTy,             getContext().NullPtrTy,
03024       getContext().BoolTy,             getContext().WCharTy,
03025       getContext().CharTy,             getContext().UnsignedCharTy,
03026       getContext().SignedCharTy,       getContext().ShortTy,
03027       getContext().UnsignedShortTy,    getContext().IntTy,
03028       getContext().UnsignedIntTy,      getContext().LongTy,
03029       getContext().UnsignedLongTy,     getContext().LongLongTy,
03030       getContext().UnsignedLongLongTy, getContext().HalfTy,
03031       getContext().FloatTy,            getContext().DoubleTy,
03032       getContext().LongDoubleTy,       getContext().Char16Ty,
03033       getContext().Char32Ty,
03034   };
03035   for (const QualType &FundamentalType : FundamentalTypes)
03036     EmitFundamentalRTTIDescriptor(FundamentalType);
03037 }
03038 
03039 /// What sort of uniqueness rules should we use for the RTTI for the
03040 /// given type?
03041 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
03042     QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
03043   if (shouldRTTIBeUnique())
03044     return RUK_Unique;
03045 
03046   // It's only necessary for linkonce_odr or weak_odr linkage.
03047   if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
03048       Linkage != llvm::GlobalValue::WeakODRLinkage)
03049     return RUK_Unique;
03050 
03051   // It's only necessary with default visibility.
03052   if (CanTy->getVisibility() != DefaultVisibility)
03053     return RUK_Unique;
03054 
03055   // If we're not required to publish this symbol, hide it.
03056   if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
03057     return RUK_NonUniqueHidden;
03058 
03059   // If we're required to publish this symbol, as we might be under an
03060   // explicit instantiation, leave it with default visibility but
03061   // enable string-comparisons.
03062   assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
03063   return RUK_NonUniqueVisible;
03064 }
03065 
03066 // Find out how to codegen the complete destructor and constructor
03067 namespace {
03068 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
03069 }
03070 static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
03071                                        const CXXMethodDecl *MD) {
03072   if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
03073     return StructorCodegen::Emit;
03074 
03075   // The complete and base structors are not equivalent if there are any virtual
03076   // bases, so emit separate functions.
03077   if (MD->getParent()->getNumVBases())
03078     return StructorCodegen::Emit;
03079 
03080   GlobalDecl AliasDecl;
03081   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
03082     AliasDecl = GlobalDecl(DD, Dtor_Complete);
03083   } else {
03084     const auto *CD = cast<CXXConstructorDecl>(MD);
03085     AliasDecl = GlobalDecl(CD, Ctor_Complete);
03086   }
03087   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
03088 
03089   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
03090     return StructorCodegen::RAUW;
03091 
03092   // FIXME: Should we allow available_externally aliases?
03093   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
03094     return StructorCodegen::RAUW;
03095 
03096   if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
03097     // Only ELF supports COMDATs with arbitrary names (C5/D5).
03098     if (CGM.getTarget().getTriple().isOSBinFormatELF())
03099       return StructorCodegen::COMDAT;
03100     return StructorCodegen::Emit;
03101   }
03102 
03103   return StructorCodegen::Alias;
03104 }
03105 
03106 static void emitConstructorDestructorAlias(CodeGenModule &CGM,
03107                                            GlobalDecl AliasDecl,
03108                                            GlobalDecl TargetDecl) {
03109   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
03110 
03111   StringRef MangledName = CGM.getMangledName(AliasDecl);
03112   llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
03113   if (Entry && !Entry->isDeclaration())
03114     return;
03115 
03116   auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
03117   llvm::PointerType *AliasType = Aliasee->getType();
03118 
03119   // Create the alias with no name.
03120   auto *Alias = llvm::GlobalAlias::create(
03121       AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
03122 
03123   // Switch any previous uses to the alias.
03124   if (Entry) {
03125     assert(Entry->getType() == AliasType &&
03126            "declaration exists with different type");
03127     Alias->takeName(Entry);
03128     Entry->replaceAllUsesWith(Alias);
03129     Entry->eraseFromParent();
03130   } else {
03131     Alias->setName(MangledName);
03132   }
03133 
03134   // Finally, set up the alias with its proper name and attributes.
03135   CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
03136 }
03137 
03138 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
03139                                     StructorType Type) {
03140   auto *CD = dyn_cast<CXXConstructorDecl>(MD);
03141   const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
03142 
03143   StructorCodegen CGType = getCodegenToUse(CGM, MD);
03144 
03145   if (Type == StructorType::Complete) {
03146     GlobalDecl CompleteDecl;
03147     GlobalDecl BaseDecl;
03148     if (CD) {
03149       CompleteDecl = GlobalDecl(CD, Ctor_Complete);
03150       BaseDecl = GlobalDecl(CD, Ctor_Base);
03151     } else {
03152       CompleteDecl = GlobalDecl(DD, Dtor_Complete);
03153       BaseDecl = GlobalDecl(DD, Dtor_Base);
03154     }
03155 
03156     if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
03157       emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
03158       return;
03159     }
03160 
03161     if (CGType == StructorCodegen::RAUW) {
03162       StringRef MangledName = CGM.getMangledName(CompleteDecl);
03163       auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
03164       CGM.addReplacement(MangledName, Aliasee);
03165       return;
03166     }
03167   }
03168 
03169   // The base destructor is equivalent to the base destructor of its
03170   // base class if there is exactly one non-virtual base class with a
03171   // non-trivial destructor, there are no fields with a non-trivial
03172   // destructor, and the body of the destructor is trivial.
03173   if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
03174       !CGM.TryEmitBaseDestructorAsAlias(DD))
03175     return;
03176 
03177   llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
03178 
03179   if (CGType == StructorCodegen::COMDAT) {
03180     SmallString<256> Buffer;
03181     llvm::raw_svector_ostream Out(Buffer);
03182     if (DD)
03183       getMangleContext().mangleCXXDtorComdat(DD, Out);
03184     else
03185       getMangleContext().mangleCXXCtorComdat(CD, Out);
03186     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
03187     Fn->setComdat(C);
03188   }
03189 }