1 //===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides C++ code generation targeting the Itanium C++ ABI.  The class
11 // in this file generates structures that follow the Itanium C++ ABI, which is
12 // documented at:
13 //  http://www.codesourcery.com/public/cxx-abi/abi.html
14 //  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
15 //
16 // It also supports the closely-related ARM ABI, documented at:
17 // http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041c/IHI0041C_cppabi.pdf
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "CGCXXABI.h"
22 #include "CGRecordLayout.h"
23 #include "CGVTables.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenModule.h"
26 #include "clang/AST/Mangle.h"
27 #include "clang/AST/Type.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Value.h"
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 namespace {
37 class ItaniumCXXABI : public CodeGen::CGCXXABI {
38   /// VTables - All the vtables which have been defined.
39   llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
40 
41 protected:
42   bool UseARMMethodPtrABI;
43   bool UseARMGuardVarABI;
44 
45   ItaniumMangleContext &getMangleContext() {
46     return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
47   }
48 
49 public:
50   ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
51                 bool UseARMMethodPtrABI = false,
52                 bool UseARMGuardVarABI = false) :
53     CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
54     UseARMGuardVarABI(UseARMGuardVarABI) { }
55 
56   bool classifyReturnType(CGFunctionInfo &FI) const override;
57 
58   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
59     // Structures with either a non-trivial destructor or a non-trivial
60     // copy constructor are always indirect.
61     // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
62     // special members.
63     if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
64       return RAA_Indirect;
65     return RAA_Default;
66   }
67 
68   bool isZeroInitializable(const MemberPointerType *MPT) override;
69 
70   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
71 
72   llvm::Value *
73     EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
74                                     const Expr *E,
75                                     llvm::Value *&This,
76                                     llvm::Value *MemFnPtr,
77                                     const MemberPointerType *MPT) override;
78 
79   llvm::Value *
80     EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
81                                  llvm::Value *Base,
82                                  llvm::Value *MemPtr,
83                                  const MemberPointerType *MPT) override;
84 
85   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
86                                            const CastExpr *E,
87                                            llvm::Value *Src) override;
88   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
89                                               llvm::Constant *Src) override;
90 
91   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
92 
93   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
94   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
95                                         CharUnits offset) override;
96   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
97   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
98                                      CharUnits ThisAdjustment);
99 
100   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
101                                            llvm::Value *L, llvm::Value *R,
102                                            const MemberPointerType *MPT,
103                                            bool Inequality) override;
104 
105   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
106                                          llvm::Value *Addr,
107                                          const MemberPointerType *MPT) override;
108 
109   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF, llvm::Value *ptr,
110                                       QualType type) override;
111 
112   void EmitFundamentalRTTIDescriptor(QualType Type);
113   void EmitFundamentalRTTIDescriptors();
114   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
115 
116   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
117   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
118   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
119                           llvm::Value *ThisPtr,
120                           llvm::Type *StdTypeInfoPtrTy) override;
121 
122   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
123                                           QualType SrcRecordTy) override;
124 
125   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
126                                    QualType SrcRecordTy, QualType DestTy,
127                                    QualType DestRecordTy,
128                                    llvm::BasicBlock *CastEnd) override;
129 
130   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
131                                      QualType SrcRecordTy,
132                                      QualType DestTy) override;
133 
134   bool EmitBadCastCall(CodeGenFunction &CGF) override;
135 
136   llvm::Value *
137     GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
138                               const CXXRecordDecl *ClassDecl,
139                               const CXXRecordDecl *BaseClassDecl) override;
140 
141   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
142 
143   void buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
144                               SmallVectorImpl<CanQualType> &ArgTys) override;
145 
146   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
147                               CXXDtorType DT) const override {
148     // Itanium does not emit any destructor variant as an inline thunk.
149     // Delegating may occur as an optimization, but all variants are either
150     // emitted with external linkage or as linkonce if they are inline and used.
151     return false;
152   }
153 
154   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
155 
156   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
157                                  FunctionArgList &Params) override;
158 
159   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
160 
161   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
162                                       const CXXConstructorDecl *D,
163                                       CXXCtorType Type, bool ForVirtualBase,
164                                       bool Delegating,
165                                       CallArgList &Args) override;
166 
167   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
168                           CXXDtorType Type, bool ForVirtualBase,
169                           bool Delegating, llvm::Value *This) override;
170 
171   void emitVTableDefinitions(CodeGenVTables &CGVT,
172                              const CXXRecordDecl *RD) override;
173 
174   llvm::Value *getVTableAddressPointInStructor(
175       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
176       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
177       bool &NeedsVirtualOffset) override;
178 
179   llvm::Constant *
180   getVTableAddressPointForConstExpr(BaseSubobject Base,
181                                     const CXXRecordDecl *VTableClass) override;
182 
183   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
184                                         CharUnits VPtrOffset) override;
185 
186   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
187                                          llvm::Value *This,
188                                          llvm::Type *Ty) override;
189 
190   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
191                                  const CXXDestructorDecl *Dtor,
192                                  CXXDtorType DtorType, llvm::Value *This,
193                                  const CXXMemberCallExpr *CE) override;
194 
195   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
196 
197   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
198                        bool ReturnAdjustment) override {
199     // Allow inlining of thunks by emitting them with available_externally
200     // linkage together with vtables when needed.
201     if (ForVTable)
202       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
203   }
204 
205   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
206                                      const ThisAdjustment &TA) override;
207 
208   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
209                                        const ReturnAdjustment &RA) override;
210 
211   size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
212                               FunctionArgList &Args) const override {
213     assert(!Args.empty() && "expected the arglist to not be empty!");
214     return Args.size() - 1;
215   }
216 
217   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
218   StringRef GetDeletedVirtualCallName() override
219     { return "__cxa_deleted_virtual"; }
220 
221   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
222   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
223                                      llvm::Value *NewPtr,
224                                      llvm::Value *NumElements,
225                                      const CXXNewExpr *expr,
226                                      QualType ElementType) override;
227   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
228                                    llvm::Value *allocPtr,
229                                    CharUnits cookieSize) override;
230 
231   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
232                        llvm::GlobalVariable *DeclPtr,
233                        bool PerformInit) override;
234   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
235                           llvm::Constant *dtor, llvm::Constant *addr) override;
236 
237   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
238                                                 llvm::GlobalVariable *Var);
239   void EmitThreadLocalInitFuncs(
240       ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
241       llvm::Function *InitFunc) override;
242   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
243                                       QualType LValType) override;
244 
245   bool NeedsVTTParameter(GlobalDecl GD) override;
246 
247   /**************************** RTTI Uniqueness ******************************/
248 
249 protected:
250   /// Returns true if the ABI requires RTTI type_info objects to be unique
251   /// across a program.
252   virtual bool shouldRTTIBeUnique() const { return true; }
253 
254 public:
255   /// What sort of unique-RTTI behavior should we use?
256   enum RTTIUniquenessKind {
257     /// We are guaranteeing, or need to guarantee, that the RTTI string
258     /// is unique.
259     RUK_Unique,
260 
261     /// We are not guaranteeing uniqueness for the RTTI string, so we
262     /// can demote to hidden visibility but must use string comparisons.
263     RUK_NonUniqueHidden,
264 
265     /// We are not guaranteeing uniqueness for the RTTI string, so we
266     /// have to use string comparisons, but we also have to emit it with
267     /// non-hidden visibility.
268     RUK_NonUniqueVisible
269   };
270 
271   /// Return the required visibility status for the given type and linkage in
272   /// the current ABI.
273   RTTIUniquenessKind
274   classifyRTTIUniqueness(QualType CanTy,
275                          llvm::GlobalValue::LinkageTypes Linkage) const;
276   friend class ItaniumRTTIBuilder;
277 
278   void emitCXXStructor(const CXXMethodDecl *MD, StructorType Type) override;
279 };
280 
281 class ARMCXXABI : public ItaniumCXXABI {
282 public:
283   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
284     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
285                   /* UseARMGuardVarABI = */ true) {}
286 
287   bool HasThisReturn(GlobalDecl GD) const override {
288     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
289               isa<CXXDestructorDecl>(GD.getDecl()) &&
290               GD.getDtorType() != Dtor_Deleting));
291   }
292 
293   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
294                            QualType ResTy) override;
295 
296   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
297   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
298                                      llvm::Value *NewPtr,
299                                      llvm::Value *NumElements,
300                                      const CXXNewExpr *expr,
301                                      QualType ElementType) override;
302   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
303                                    CharUnits cookieSize) override;
304 };
305 
306 class iOS64CXXABI : public ARMCXXABI {
307 public:
308   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
309 
310   // ARM64 libraries are prepared for non-unique RTTI.
311   bool shouldRTTIBeUnique() const override { return false; }
312 };
313 }
314 
315 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
316   switch (CGM.getTarget().getCXXABI().getKind()) {
317   // For IR-generation purposes, there's no significant difference
318   // between the ARM and iOS ABIs.
319   case TargetCXXABI::GenericARM:
320   case TargetCXXABI::iOS:
321     return new ARMCXXABI(CGM);
322 
323   case TargetCXXABI::iOS64:
324     return new iOS64CXXABI(CGM);
325 
326   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
327   // include the other 32-bit ARM oddities: constructor/destructor return values
328   // and array cookies.
329   case TargetCXXABI::GenericAArch64:
330     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
331                              /* UseARMGuardVarABI = */ true);
332 
333   case TargetCXXABI::GenericItanium:
334     if (CGM.getContext().getTargetInfo().getTriple().getArch()
335         == llvm::Triple::le32) {
336       // For PNaCl, use ARM-style method pointers so that PNaCl code
337       // does not assume anything about the alignment of function
338       // pointers.
339       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
340                                /* UseARMGuardVarABI = */ false);
341     }
342     return new ItaniumCXXABI(CGM);
343 
344   case TargetCXXABI::Microsoft:
345     llvm_unreachable("Microsoft ABI is not Itanium-based");
346   }
347   llvm_unreachable("bad ABI kind");
348 }
349 
350 llvm::Type *
351 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
352   if (MPT->isMemberDataPointer())
353     return CGM.PtrDiffTy;
354   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
355 }
356 
357 /// In the Itanium and ARM ABIs, method pointers have the form:
358 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
359 ///
360 /// In the Itanium ABI:
361 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
362 ///  - the this-adjustment is (memptr.adj)
363 ///  - the virtual offset is (memptr.ptr - 1)
364 ///
365 /// In the ARM ABI:
366 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
367 ///  - the this-adjustment is (memptr.adj >> 1)
368 ///  - the virtual offset is (memptr.ptr)
369 /// ARM uses 'adj' for the virtual flag because Thumb functions
370 /// may be only single-byte aligned.
371 ///
372 /// If the member is virtual, the adjusted 'this' pointer points
373 /// to a vtable pointer from which the virtual offset is applied.
374 ///
375 /// If the member is non-virtual, memptr.ptr is the address of
376 /// the function to call.
377 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
378     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
379     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
380   CGBuilderTy &Builder = CGF.Builder;
381 
382   const FunctionProtoType *FPT =
383     MPT->getPointeeType()->getAs<FunctionProtoType>();
384   const CXXRecordDecl *RD =
385     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
386 
387   llvm::FunctionType *FTy =
388     CGM.getTypes().GetFunctionType(
389       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
390 
391   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
392 
393   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
394   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
395   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
396 
397   // Extract memptr.adj, which is in the second field.
398   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
399 
400   // Compute the true adjustment.
401   llvm::Value *Adj = RawAdj;
402   if (UseARMMethodPtrABI)
403     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
404 
405   // Apply the adjustment and cast back to the original struct type
406   // for consistency.
407   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
408   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
409   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
410 
411   // Load the function pointer.
412   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
413 
414   // If the LSB in the function pointer is 1, the function pointer points to
415   // a virtual function.
416   llvm::Value *IsVirtual;
417   if (UseARMMethodPtrABI)
418     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
419   else
420     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
421   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
422   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
423 
424   // In the virtual path, the adjustment left 'This' pointing to the
425   // vtable of the correct base subobject.  The "function pointer" is an
426   // offset within the vtable (+1 for the virtual flag on non-ARM).
427   CGF.EmitBlock(FnVirtual);
428 
429   // Cast the adjusted this to a pointer to vtable pointer and load.
430   llvm::Type *VTableTy = Builder.getInt8PtrTy();
431   llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
432 
433   // Apply the offset.
434   llvm::Value *VTableOffset = FnAsInt;
435   if (!UseARMMethodPtrABI)
436     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
437   VTable = Builder.CreateGEP(VTable, VTableOffset);
438 
439   // Load the virtual function to call.
440   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
441   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
442   CGF.EmitBranch(FnEnd);
443 
444   // In the non-virtual path, the function pointer is actually a
445   // function pointer.
446   CGF.EmitBlock(FnNonVirtual);
447   llvm::Value *NonVirtualFn =
448     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
449 
450   // We're done.
451   CGF.EmitBlock(FnEnd);
452   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
453   Callee->addIncoming(VirtualFn, FnVirtual);
454   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
455   return Callee;
456 }
457 
458 /// Compute an l-value by applying the given pointer-to-member to a
459 /// base object.
460 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
461     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
462     const MemberPointerType *MPT) {
463   assert(MemPtr->getType() == CGM.PtrDiffTy);
464 
465   CGBuilderTy &Builder = CGF.Builder;
466 
467   unsigned AS = Base->getType()->getPointerAddressSpace();
468 
469   // Cast to char*.
470   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
471 
472   // Apply the offset, which we assume is non-null.
473   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
474 
475   // Cast the address to the appropriate pointer type, adopting the
476   // address space of the base pointer.
477   llvm::Type *PType
478     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
479   return Builder.CreateBitCast(Addr, PType);
480 }
481 
482 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
483 /// conversion.
484 ///
485 /// Bitcast conversions are always a no-op under Itanium.
486 ///
487 /// Obligatory offset/adjustment diagram:
488 ///         <-- offset -->          <-- adjustment -->
489 ///   |--------------------------|----------------------|--------------------|
490 ///   ^Derived address point     ^Base address point    ^Member address point
491 ///
492 /// So when converting a base member pointer to a derived member pointer,
493 /// we add the offset to the adjustment because the address point has
494 /// decreased;  and conversely, when converting a derived MP to a base MP
495 /// we subtract the offset from the adjustment because the address point
496 /// has increased.
497 ///
498 /// The standard forbids (at compile time) conversion to and from
499 /// virtual bases, which is why we don't have to consider them here.
500 ///
501 /// The standard forbids (at run time) casting a derived MP to a base
502 /// MP when the derived MP does not point to a member of the base.
503 /// This is why -1 is a reasonable choice for null data member
504 /// pointers.
505 llvm::Value *
506 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
507                                            const CastExpr *E,
508                                            llvm::Value *src) {
509   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
510          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
511          E->getCastKind() == CK_ReinterpretMemberPointer);
512 
513   // Under Itanium, reinterprets don't require any additional processing.
514   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
515 
516   // Use constant emission if we can.
517   if (isa<llvm::Constant>(src))
518     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
519 
520   llvm::Constant *adj = getMemberPointerAdjustment(E);
521   if (!adj) return src;
522 
523   CGBuilderTy &Builder = CGF.Builder;
524   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
525 
526   const MemberPointerType *destTy =
527     E->getType()->castAs<MemberPointerType>();
528 
529   // For member data pointers, this is just a matter of adding the
530   // offset if the source is non-null.
531   if (destTy->isMemberDataPointer()) {
532     llvm::Value *dst;
533     if (isDerivedToBase)
534       dst = Builder.CreateNSWSub(src, adj, "adj");
535     else
536       dst = Builder.CreateNSWAdd(src, adj, "adj");
537 
538     // Null check.
539     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
540     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
541     return Builder.CreateSelect(isNull, src, dst);
542   }
543 
544   // The this-adjustment is left-shifted by 1 on ARM.
545   if (UseARMMethodPtrABI) {
546     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
547     offset <<= 1;
548     adj = llvm::ConstantInt::get(adj->getType(), offset);
549   }
550 
551   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
552   llvm::Value *dstAdj;
553   if (isDerivedToBase)
554     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
555   else
556     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
557 
558   return Builder.CreateInsertValue(src, dstAdj, 1);
559 }
560 
561 llvm::Constant *
562 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
563                                            llvm::Constant *src) {
564   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
565          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
566          E->getCastKind() == CK_ReinterpretMemberPointer);
567 
568   // Under Itanium, reinterprets don't require any additional processing.
569   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
570 
571   // If the adjustment is trivial, we don't need to do anything.
572   llvm::Constant *adj = getMemberPointerAdjustment(E);
573   if (!adj) return src;
574 
575   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
576 
577   const MemberPointerType *destTy =
578     E->getType()->castAs<MemberPointerType>();
579 
580   // For member data pointers, this is just a matter of adding the
581   // offset if the source is non-null.
582   if (destTy->isMemberDataPointer()) {
583     // null maps to null.
584     if (src->isAllOnesValue()) return src;
585 
586     if (isDerivedToBase)
587       return llvm::ConstantExpr::getNSWSub(src, adj);
588     else
589       return llvm::ConstantExpr::getNSWAdd(src, adj);
590   }
591 
592   // The this-adjustment is left-shifted by 1 on ARM.
593   if (UseARMMethodPtrABI) {
594     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
595     offset <<= 1;
596     adj = llvm::ConstantInt::get(adj->getType(), offset);
597   }
598 
599   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
600   llvm::Constant *dstAdj;
601   if (isDerivedToBase)
602     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
603   else
604     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
605 
606   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
607 }
608 
609 llvm::Constant *
610 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
611   // Itanium C++ ABI 2.3:
612   //   A NULL pointer is represented as -1.
613   if (MPT->isMemberDataPointer())
614     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
615 
616   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
617   llvm::Constant *Values[2] = { Zero, Zero };
618   return llvm::ConstantStruct::getAnon(Values);
619 }
620 
621 llvm::Constant *
622 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
623                                      CharUnits offset) {
624   // Itanium C++ ABI 2.3:
625   //   A pointer to data member is an offset from the base address of
626   //   the class object containing it, represented as a ptrdiff_t
627   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
628 }
629 
630 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
631   return BuildMemberPointer(MD, CharUnits::Zero());
632 }
633 
634 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
635                                                   CharUnits ThisAdjustment) {
636   assert(MD->isInstance() && "Member function must not be static!");
637   MD = MD->getCanonicalDecl();
638 
639   CodeGenTypes &Types = CGM.getTypes();
640 
641   // Get the function pointer (or index if this is a virtual function).
642   llvm::Constant *MemPtr[2];
643   if (MD->isVirtual()) {
644     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
645 
646     const ASTContext &Context = getContext();
647     CharUnits PointerWidth =
648       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
649     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
650 
651     if (UseARMMethodPtrABI) {
652       // ARM C++ ABI 3.2.1:
653       //   This ABI specifies that adj contains twice the this
654       //   adjustment, plus 1 if the member function is virtual. The
655       //   least significant bit of adj then makes exactly the same
656       //   discrimination as the least significant bit of ptr does for
657       //   Itanium.
658       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
659       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
660                                          2 * ThisAdjustment.getQuantity() + 1);
661     } else {
662       // Itanium C++ ABI 2.3:
663       //   For a virtual function, [the pointer field] is 1 plus the
664       //   virtual table offset (in bytes) of the function,
665       //   represented as a ptrdiff_t.
666       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
667       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
668                                          ThisAdjustment.getQuantity());
669     }
670   } else {
671     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
672     llvm::Type *Ty;
673     // Check whether the function has a computable LLVM signature.
674     if (Types.isFuncTypeConvertible(FPT)) {
675       // The function has a computable LLVM signature; use the correct type.
676       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
677     } else {
678       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
679       // function type is incomplete.
680       Ty = CGM.PtrDiffTy;
681     }
682     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
683 
684     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
685     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
686                                        (UseARMMethodPtrABI ? 2 : 1) *
687                                        ThisAdjustment.getQuantity());
688   }
689 
690   return llvm::ConstantStruct::getAnon(MemPtr);
691 }
692 
693 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
694                                                  QualType MPType) {
695   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
696   const ValueDecl *MPD = MP.getMemberPointerDecl();
697   if (!MPD)
698     return EmitNullMemberPointer(MPT);
699 
700   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
701 
702   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
703     return BuildMemberPointer(MD, ThisAdjustment);
704 
705   CharUnits FieldOffset =
706     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
707   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
708 }
709 
710 /// The comparison algorithm is pretty easy: the member pointers are
711 /// the same if they're either bitwise identical *or* both null.
712 ///
713 /// ARM is different here only because null-ness is more complicated.
714 llvm::Value *
715 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
716                                            llvm::Value *L,
717                                            llvm::Value *R,
718                                            const MemberPointerType *MPT,
719                                            bool Inequality) {
720   CGBuilderTy &Builder = CGF.Builder;
721 
722   llvm::ICmpInst::Predicate Eq;
723   llvm::Instruction::BinaryOps And, Or;
724   if (Inequality) {
725     Eq = llvm::ICmpInst::ICMP_NE;
726     And = llvm::Instruction::Or;
727     Or = llvm::Instruction::And;
728   } else {
729     Eq = llvm::ICmpInst::ICMP_EQ;
730     And = llvm::Instruction::And;
731     Or = llvm::Instruction::Or;
732   }
733 
734   // Member data pointers are easy because there's a unique null
735   // value, so it just comes down to bitwise equality.
736   if (MPT->isMemberDataPointer())
737     return Builder.CreateICmp(Eq, L, R);
738 
739   // For member function pointers, the tautologies are more complex.
740   // The Itanium tautology is:
741   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
742   // The ARM tautology is:
743   //   (L == R) <==> (L.ptr == R.ptr &&
744   //                  (L.adj == R.adj ||
745   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
746   // The inequality tautologies have exactly the same structure, except
747   // applying De Morgan's laws.
748 
749   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
750   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
751 
752   // This condition tests whether L.ptr == R.ptr.  This must always be
753   // true for equality to hold.
754   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
755 
756   // This condition, together with the assumption that L.ptr == R.ptr,
757   // tests whether the pointers are both null.  ARM imposes an extra
758   // condition.
759   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
760   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
761 
762   // This condition tests whether L.adj == R.adj.  If this isn't
763   // true, the pointers are unequal unless they're both null.
764   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
765   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
766   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
767 
768   // Null member function pointers on ARM clear the low bit of Adj,
769   // so the zero condition has to check that neither low bit is set.
770   if (UseARMMethodPtrABI) {
771     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
772 
773     // Compute (l.adj | r.adj) & 1 and test it against zero.
774     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
775     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
776     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
777                                                       "cmp.or.adj");
778     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
779   }
780 
781   // Tie together all our conditions.
782   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
783   Result = Builder.CreateBinOp(And, PtrEq, Result,
784                                Inequality ? "memptr.ne" : "memptr.eq");
785   return Result;
786 }
787 
788 llvm::Value *
789 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
790                                           llvm::Value *MemPtr,
791                                           const MemberPointerType *MPT) {
792   CGBuilderTy &Builder = CGF.Builder;
793 
794   /// For member data pointers, this is just a check against -1.
795   if (MPT->isMemberDataPointer()) {
796     assert(MemPtr->getType() == CGM.PtrDiffTy);
797     llvm::Value *NegativeOne =
798       llvm::Constant::getAllOnesValue(MemPtr->getType());
799     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
800   }
801 
802   // In Itanium, a member function pointer is not null if 'ptr' is not null.
803   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
804 
805   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
806   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
807 
808   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
809   // (the virtual bit) is set.
810   if (UseARMMethodPtrABI) {
811     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
812     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
813     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
814     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
815                                                   "memptr.isvirtual");
816     Result = Builder.CreateOr(Result, IsVirtual);
817   }
818 
819   return Result;
820 }
821 
822 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
823   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
824   if (!RD)
825     return false;
826 
827   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
828   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
829   // special members.
830   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
831     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
832     return true;
833   }
834   return false;
835 }
836 
837 /// The Itanium ABI requires non-zero initialization only for data
838 /// member pointers, for which '0' is a valid offset.
839 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
840   return MPT->getPointeeType()->isFunctionType();
841 }
842 
843 /// The Itanium ABI always places an offset to the complete object
844 /// at entry -2 in the vtable.
845 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
846                                                    llvm::Value *ptr,
847                                                    QualType type) {
848   // Grab the vtable pointer as an intptr_t*.
849   llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
850 
851   // Track back to entry -2 and pull out the offset there.
852   llvm::Value *offsetPtr =
853     CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
854   llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
855   offset->setAlignment(CGF.PointerAlignInBytes);
856 
857   // Apply the offset.
858   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
859   return CGF.Builder.CreateInBoundsGEP(ptr, offset);
860 }
861 
862 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
863   // void *__dynamic_cast(const void *sub,
864   //                      const abi::__class_type_info *src,
865   //                      const abi::__class_type_info *dst,
866   //                      std::ptrdiff_t src2dst_offset);
867 
868   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
869   llvm::Type *PtrDiffTy =
870     CGF.ConvertType(CGF.getContext().getPointerDiffType());
871 
872   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
873 
874   llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
875 
876   // Mark the function as nounwind readonly.
877   llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
878                                             llvm::Attribute::ReadOnly };
879   llvm::AttributeSet Attrs = llvm::AttributeSet::get(
880       CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
881 
882   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
883 }
884 
885 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
886   // void __cxa_bad_cast();
887   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
888   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
889 }
890 
891 /// \brief Compute the src2dst_offset hint as described in the
892 /// Itanium C++ ABI [2.9.7]
893 static CharUnits computeOffsetHint(ASTContext &Context,
894                                    const CXXRecordDecl *Src,
895                                    const CXXRecordDecl *Dst) {
896   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
897                      /*DetectVirtual=*/false);
898 
899   // If Dst is not derived from Src we can skip the whole computation below and
900   // return that Src is not a public base of Dst.  Record all inheritance paths.
901   if (!Dst->isDerivedFrom(Src, Paths))
902     return CharUnits::fromQuantity(-2ULL);
903 
904   unsigned NumPublicPaths = 0;
905   CharUnits Offset;
906 
907   // Now walk all possible inheritance paths.
908   for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
909        ++I) {
910     if (I->Access != AS_public) // Ignore non-public inheritance.
911       continue;
912 
913     ++NumPublicPaths;
914 
915     for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
916       // If the path contains a virtual base class we can't give any hint.
917       // -1: no hint.
918       if (J->Base->isVirtual())
919         return CharUnits::fromQuantity(-1ULL);
920 
921       if (NumPublicPaths > 1) // Won't use offsets, skip computation.
922         continue;
923 
924       // Accumulate the base class offsets.
925       const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
926       Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
927     }
928   }
929 
930   // -2: Src is not a public base of Dst.
931   if (NumPublicPaths == 0)
932     return CharUnits::fromQuantity(-2ULL);
933 
934   // -3: Src is a multiple public base type but never a virtual base type.
935   if (NumPublicPaths > 1)
936     return CharUnits::fromQuantity(-3ULL);
937 
938   // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
939   // Return the offset of Src from the origin of Dst.
940   return Offset;
941 }
942 
943 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
944   // void __cxa_bad_typeid();
945   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
946 
947   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
948 }
949 
950 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
951                                               QualType SrcRecordTy) {
952   return IsDeref;
953 }
954 
955 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
956   llvm::Value *Fn = getBadTypeidFn(CGF);
957   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
958   CGF.Builder.CreateUnreachable();
959 }
960 
961 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
962                                        QualType SrcRecordTy,
963                                        llvm::Value *ThisPtr,
964                                        llvm::Type *StdTypeInfoPtrTy) {
965   llvm::Value *Value =
966       CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
967 
968   // Load the type info.
969   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
970   return CGF.Builder.CreateLoad(Value);
971 }
972 
973 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
974                                                        QualType SrcRecordTy) {
975   return SrcIsPtr;
976 }
977 
978 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
979     CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
980     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
981   llvm::Type *PtrDiffLTy =
982       CGF.ConvertType(CGF.getContext().getPointerDiffType());
983   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
984 
985   llvm::Value *SrcRTTI =
986       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
987   llvm::Value *DestRTTI =
988       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
989 
990   // Compute the offset hint.
991   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
992   const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
993   llvm::Value *OffsetHint = llvm::ConstantInt::get(
994       PtrDiffLTy,
995       computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
996 
997   // Emit the call to __dynamic_cast.
998   Value = CGF.EmitCastToVoidPtr(Value);
999 
1000   llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
1001   Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
1002   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1003 
1004   /// C++ [expr.dynamic.cast]p9:
1005   ///   A failed cast to reference type throws std::bad_cast
1006   if (DestTy->isReferenceType()) {
1007     llvm::BasicBlock *BadCastBlock =
1008         CGF.createBasicBlock("dynamic_cast.bad_cast");
1009 
1010     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1011     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1012 
1013     CGF.EmitBlock(BadCastBlock);
1014     EmitBadCastCall(CGF);
1015   }
1016 
1017   return Value;
1018 }
1019 
1020 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
1021                                                   llvm::Value *Value,
1022                                                   QualType SrcRecordTy,
1023                                                   QualType DestTy) {
1024   llvm::Type *PtrDiffLTy =
1025       CGF.ConvertType(CGF.getContext().getPointerDiffType());
1026   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1027 
1028   // Get the vtable pointer.
1029   llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1030 
1031   // Get the offset-to-top from the vtable.
1032   llvm::Value *OffsetToTop =
1033       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1034   OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1035 
1036   // Finally, add the offset to the pointer.
1037   Value = CGF.EmitCastToVoidPtr(Value);
1038   Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1039 
1040   return CGF.Builder.CreateBitCast(Value, DestLTy);
1041 }
1042 
1043 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1044   llvm::Value *Fn = getBadCastFn(CGF);
1045   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1046   CGF.Builder.CreateUnreachable();
1047   return true;
1048 }
1049 
1050 llvm::Value *
1051 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1052                                          llvm::Value *This,
1053                                          const CXXRecordDecl *ClassDecl,
1054                                          const CXXRecordDecl *BaseClassDecl) {
1055   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1056   CharUnits VBaseOffsetOffset =
1057       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1058                                                                BaseClassDecl);
1059 
1060   llvm::Value *VBaseOffsetPtr =
1061     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1062                                    "vbase.offset.ptr");
1063   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1064                                              CGM.PtrDiffTy->getPointerTo());
1065 
1066   llvm::Value *VBaseOffset =
1067     CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1068 
1069   return VBaseOffset;
1070 }
1071 
1072 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1073   // Just make sure we're in sync with TargetCXXABI.
1074   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1075 
1076   // The constructor used for constructing this as a base class;
1077   // ignores virtual bases.
1078   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1079 
1080   // The constructor used for constructing this as a complete class;
1081   // constucts the virtual bases, then calls the base constructor.
1082   if (!D->getParent()->isAbstract()) {
1083     // We don't need to emit the complete ctor if the class is abstract.
1084     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1085   }
1086 }
1087 
1088 void
1089 ItaniumCXXABI::buildStructorSignature(const CXXMethodDecl *MD, StructorType T,
1090                                       SmallVectorImpl<CanQualType> &ArgTys) {
1091   ASTContext &Context = getContext();
1092 
1093   // All parameters are already in place except VTT, which goes after 'this'.
1094   // These are Clang types, so we don't need to worry about sret yet.
1095 
1096   // Check if we need to add a VTT parameter (which has type void **).
1097   if (T == StructorType::Base && MD->getParent()->getNumVBases() != 0)
1098     ArgTys.insert(ArgTys.begin() + 1,
1099                   Context.getPointerType(Context.VoidPtrTy));
1100 }
1101 
1102 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1103   // The destructor used for destructing this as a base class; ignores
1104   // virtual bases.
1105   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1106 
1107   // The destructor used for destructing this as a most-derived class;
1108   // call the base destructor and then destructs any virtual bases.
1109   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1110 
1111   // The destructor in a virtual table is always a 'deleting'
1112   // destructor, which calls the complete destructor and then uses the
1113   // appropriate operator delete.
1114   if (D->isVirtual())
1115     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1116 }
1117 
1118 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1119                                               QualType &ResTy,
1120                                               FunctionArgList &Params) {
1121   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1122   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1123 
1124   // Check if we need a VTT parameter as well.
1125   if (NeedsVTTParameter(CGF.CurGD)) {
1126     ASTContext &Context = getContext();
1127 
1128     // FIXME: avoid the fake decl
1129     QualType T = Context.getPointerType(Context.VoidPtrTy);
1130     ImplicitParamDecl *VTTDecl
1131       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
1132                                   &Context.Idents.get("vtt"), T);
1133     Params.insert(Params.begin() + 1, VTTDecl);
1134     getStructorImplicitParamDecl(CGF) = VTTDecl;
1135   }
1136 }
1137 
1138 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1139   /// Initialize the 'this' slot.
1140   EmitThisParam(CGF);
1141 
1142   /// Initialize the 'vtt' slot if needed.
1143   if (getStructorImplicitParamDecl(CGF)) {
1144     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1145         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1146   }
1147 
1148   /// If this is a function that the ABI specifies returns 'this', initialize
1149   /// the return slot to 'this' at the start of the function.
1150   ///
1151   /// Unlike the setting of return types, this is done within the ABI
1152   /// implementation instead of by clients of CGCXXABI because:
1153   /// 1) getThisValue is currently protected
1154   /// 2) in theory, an ABI could implement 'this' returns some other way;
1155   ///    HasThisReturn only specifies a contract, not the implementation
1156   if (HasThisReturn(CGF.CurGD))
1157     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1158 }
1159 
1160 unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1161     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1162     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1163   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1164     return 0;
1165 
1166   // Insert the implicit 'vtt' argument as the second argument.
1167   llvm::Value *VTT =
1168       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1169   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1170   Args.insert(Args.begin() + 1,
1171               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1172   return 1;  // Added one arg.
1173 }
1174 
1175 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1176                                        const CXXDestructorDecl *DD,
1177                                        CXXDtorType Type, bool ForVirtualBase,
1178                                        bool Delegating, llvm::Value *This) {
1179   GlobalDecl GD(DD, Type);
1180   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1181   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1182 
1183   llvm::Value *Callee = nullptr;
1184   if (getContext().getLangOpts().AppleKext)
1185     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1186 
1187   if (!Callee)
1188     Callee = CGM.getAddrOfCXXStructor(DD, getFromDtorType(Type));
1189 
1190   CGF.EmitCXXMemberOrOperatorCall(DD, Callee, ReturnValueSlot(), This, VTT,
1191                                   VTTTy, nullptr);
1192 }
1193 
1194 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1195                                           const CXXRecordDecl *RD) {
1196   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1197   if (VTable->hasInitializer())
1198     return;
1199 
1200   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1201   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1202   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1203   llvm::Constant *RTTI =
1204       CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
1205 
1206   // Create and set the initializer.
1207   llvm::Constant *Init = CGVT.CreateVTableInitializer(
1208       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
1209       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks(), RTTI);
1210   VTable->setInitializer(Init);
1211 
1212   // Set the correct linkage.
1213   VTable->setLinkage(Linkage);
1214 
1215   // Set the right visibility.
1216   CGM.setGlobalVisibility(VTable, RD);
1217 
1218   // Use pointer alignment for the vtable. Otherwise we would align them based
1219   // on the size of the initializer which doesn't make sense as only single
1220   // values are read.
1221   unsigned PAlign = CGM.getTarget().getPointerAlign(0);
1222   VTable->setAlignment(getContext().toCharUnitsFromBits(PAlign).getQuantity());
1223 
1224   // If this is the magic class __cxxabiv1::__fundamental_type_info,
1225   // we will emit the typeinfo for the fundamental types. This is the
1226   // same behaviour as GCC.
1227   const DeclContext *DC = RD->getDeclContext();
1228   if (RD->getIdentifier() &&
1229       RD->getIdentifier()->isStr("__fundamental_type_info") &&
1230       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1231       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1232       DC->getParent()->isTranslationUnit())
1233     EmitFundamentalRTTIDescriptors();
1234 }
1235 
1236 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1237     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1238     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1239   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1240   NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1241 
1242   llvm::Value *VTableAddressPoint;
1243   if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1244     // Get the secondary vpointer index.
1245     uint64_t VirtualPointerIndex =
1246         CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1247 
1248     /// Load the VTT.
1249     llvm::Value *VTT = CGF.LoadCXXVTT();
1250     if (VirtualPointerIndex)
1251       VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1252 
1253     // And load the address point from the VTT.
1254     VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1255   } else {
1256     llvm::Constant *VTable =
1257         CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1258     uint64_t AddressPoint = CGM.getItaniumVTableContext()
1259                                 .getVTableLayout(VTableClass)
1260                                 .getAddressPoint(Base);
1261     VTableAddressPoint =
1262         CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1263   }
1264 
1265   return VTableAddressPoint;
1266 }
1267 
1268 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1269     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1270   llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1271 
1272   // Find the appropriate vtable within the vtable group.
1273   uint64_t AddressPoint = CGM.getItaniumVTableContext()
1274                               .getVTableLayout(VTableClass)
1275                               .getAddressPoint(Base);
1276   llvm::Value *Indices[] = {
1277     llvm::ConstantInt::get(CGM.Int64Ty, 0),
1278     llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1279   };
1280 
1281   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1282 }
1283 
1284 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1285                                                      CharUnits VPtrOffset) {
1286   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1287 
1288   llvm::GlobalVariable *&VTable = VTables[RD];
1289   if (VTable)
1290     return VTable;
1291 
1292   // Queue up this v-table for possible deferred emission.
1293   CGM.addDeferredVTable(RD);
1294 
1295   SmallString<256> OutName;
1296   llvm::raw_svector_ostream Out(OutName);
1297   getMangleContext().mangleCXXVTable(RD, Out);
1298   Out.flush();
1299   StringRef Name = OutName.str();
1300 
1301   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1302   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1303       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1304 
1305   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1306       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1307   VTable->setUnnamedAddr(true);
1308 
1309   if (RD->hasAttr<DLLImportAttr>())
1310     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1311   else if (RD->hasAttr<DLLExportAttr>())
1312     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1313 
1314   return VTable;
1315 }
1316 
1317 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1318                                                       GlobalDecl GD,
1319                                                       llvm::Value *This,
1320                                                       llvm::Type *Ty) {
1321   GD = GD.getCanonicalDecl();
1322   Ty = Ty->getPointerTo()->getPointerTo();
1323   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1324 
1325   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1326   llvm::Value *VFuncPtr =
1327       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1328   return CGF.Builder.CreateLoad(VFuncPtr);
1329 }
1330 
1331 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1332                                               const CXXDestructorDecl *Dtor,
1333                                               CXXDtorType DtorType,
1334                                               llvm::Value *This,
1335                                               const CXXMemberCallExpr *CE) {
1336   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1337   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1338 
1339   const CGFunctionInfo *FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
1340       Dtor, getFromDtorType(DtorType));
1341   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1342   llvm::Value *Callee =
1343       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
1344 
1345   CGF.EmitCXXMemberOrOperatorCall(Dtor, Callee, ReturnValueSlot(), This,
1346                                   /*ImplicitParam=*/nullptr, QualType(), CE);
1347 }
1348 
1349 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1350   CodeGenVTables &VTables = CGM.getVTables();
1351   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1352   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1353 }
1354 
1355 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1356                                           llvm::Value *Ptr,
1357                                           int64_t NonVirtualAdjustment,
1358                                           int64_t VirtualAdjustment,
1359                                           bool IsReturnAdjustment) {
1360   if (!NonVirtualAdjustment && !VirtualAdjustment)
1361     return Ptr;
1362 
1363   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1364   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1365 
1366   if (NonVirtualAdjustment && !IsReturnAdjustment) {
1367     // Perform the non-virtual adjustment for a base-to-derived cast.
1368     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1369   }
1370 
1371   if (VirtualAdjustment) {
1372     llvm::Type *PtrDiffTy =
1373         CGF.ConvertType(CGF.getContext().getPointerDiffType());
1374 
1375     // Perform the virtual adjustment.
1376     llvm::Value *VTablePtrPtr =
1377         CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1378 
1379     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1380 
1381     llvm::Value *OffsetPtr =
1382         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1383 
1384     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1385 
1386     // Load the adjustment offset from the vtable.
1387     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1388 
1389     // Adjust our pointer.
1390     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1391   }
1392 
1393   if (NonVirtualAdjustment && IsReturnAdjustment) {
1394     // Perform the non-virtual adjustment for a derived-to-base cast.
1395     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1396   }
1397 
1398   // Cast back to the original type.
1399   return CGF.Builder.CreateBitCast(V, Ptr->getType());
1400 }
1401 
1402 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1403                                                   llvm::Value *This,
1404                                                   const ThisAdjustment &TA) {
1405   return performTypeAdjustment(CGF, This, TA.NonVirtual,
1406                                TA.Virtual.Itanium.VCallOffsetOffset,
1407                                /*IsReturnAdjustment=*/false);
1408 }
1409 
1410 llvm::Value *
1411 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1412                                        const ReturnAdjustment &RA) {
1413   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1414                                RA.Virtual.Itanium.VBaseOffsetOffset,
1415                                /*IsReturnAdjustment=*/true);
1416 }
1417 
1418 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1419                                     RValue RV, QualType ResultType) {
1420   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1421     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1422 
1423   // Destructor thunks in the ARM ABI have indeterminate results.
1424   llvm::Type *T =
1425     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1426   RValue Undef = RValue::get(llvm::UndefValue::get(T));
1427   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1428 }
1429 
1430 /************************** Array allocation cookies **************************/
1431 
1432 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1433   // The array cookie is a size_t; pad that up to the element alignment.
1434   // The cookie is actually right-justified in that space.
1435   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1436                   CGM.getContext().getTypeAlignInChars(elementType));
1437 }
1438 
1439 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1440                                                   llvm::Value *NewPtr,
1441                                                   llvm::Value *NumElements,
1442                                                   const CXXNewExpr *expr,
1443                                                   QualType ElementType) {
1444   assert(requiresArrayCookie(expr));
1445 
1446   unsigned AS = NewPtr->getType()->getPointerAddressSpace();
1447 
1448   ASTContext &Ctx = getContext();
1449   QualType SizeTy = Ctx.getSizeType();
1450   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1451 
1452   // The size of the cookie.
1453   CharUnits CookieSize =
1454     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1455   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1456 
1457   // Compute an offset to the cookie.
1458   llvm::Value *CookiePtr = NewPtr;
1459   CharUnits CookieOffset = CookieSize - SizeSize;
1460   if (!CookieOffset.isZero())
1461     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1462                                                  CookieOffset.getQuantity());
1463 
1464   // Write the number of elements into the appropriate slot.
1465   llvm::Type *NumElementsTy = CGF.ConvertType(SizeTy)->getPointerTo(AS);
1466   llvm::Value *NumElementsPtr =
1467       CGF.Builder.CreateBitCast(CookiePtr, NumElementsTy);
1468   llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1469   if (CGM.getLangOpts().Sanitize.Address && AS == 0 &&
1470       expr->getOperatorNew()->isReplaceableGlobalAllocationFunction()) {
1471     // The store to the CookiePtr does not need to be instrumented.
1472     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
1473     llvm::FunctionType *FTy =
1474         llvm::FunctionType::get(CGM.VoidTy, NumElementsTy, false);
1475     llvm::Constant *F =
1476         CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
1477     CGF.Builder.CreateCall(F, NumElementsPtr);
1478   }
1479 
1480   // Finally, compute a pointer to the actual data buffer by skipping
1481   // over the cookie completely.
1482   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1483                                                 CookieSize.getQuantity());
1484 }
1485 
1486 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1487                                                 llvm::Value *allocPtr,
1488                                                 CharUnits cookieSize) {
1489   // The element size is right-justified in the cookie.
1490   llvm::Value *numElementsPtr = allocPtr;
1491   CharUnits numElementsOffset =
1492     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1493   if (!numElementsOffset.isZero())
1494     numElementsPtr =
1495       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1496                                              numElementsOffset.getQuantity());
1497 
1498   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1499   numElementsPtr =
1500     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1501   if (!CGM.getLangOpts().Sanitize.Address || AS != 0)
1502     return CGF.Builder.CreateLoad(numElementsPtr);
1503   // In asan mode emit a function call instead of a regular load and let the
1504   // run-time deal with it: if the shadow is properly poisoned return the
1505   // cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
1506   // We can't simply ignore this load using nosanitize metadata because
1507   // the metadata may be lost.
1508   llvm::FunctionType *FTy =
1509       llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
1510   llvm::Constant *F =
1511       CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
1512   return CGF.Builder.CreateCall(F, numElementsPtr);
1513 }
1514 
1515 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1516   // ARM says that the cookie is always:
1517   //   struct array_cookie {
1518   //     std::size_t element_size; // element_size != 0
1519   //     std::size_t element_count;
1520   //   };
1521   // But the base ABI doesn't give anything an alignment greater than
1522   // 8, so we can dismiss this as typical ABI-author blindness to
1523   // actual language complexity and round up to the element alignment.
1524   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1525                   CGM.getContext().getTypeAlignInChars(elementType));
1526 }
1527 
1528 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1529                                               llvm::Value *newPtr,
1530                                               llvm::Value *numElements,
1531                                               const CXXNewExpr *expr,
1532                                               QualType elementType) {
1533   assert(requiresArrayCookie(expr));
1534 
1535   // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1536   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1537 
1538   // The cookie is always at the start of the buffer.
1539   llvm::Value *cookie = newPtr;
1540 
1541   // The first element is the element size.
1542   cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1543   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1544                  getContext().getTypeSizeInChars(elementType).getQuantity());
1545   CGF.Builder.CreateStore(elementSize, cookie);
1546 
1547   // The second element is the element count.
1548   cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1549   CGF.Builder.CreateStore(numElements, cookie);
1550 
1551   // Finally, compute a pointer to the actual data buffer by skipping
1552   // over the cookie completely.
1553   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1554   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1555                                                 cookieSize.getQuantity());
1556 }
1557 
1558 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1559                                             llvm::Value *allocPtr,
1560                                             CharUnits cookieSize) {
1561   // The number of elements is at offset sizeof(size_t) relative to
1562   // the allocated pointer.
1563   llvm::Value *numElementsPtr
1564     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
1565 
1566   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1567   numElementsPtr =
1568     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1569   return CGF.Builder.CreateLoad(numElementsPtr);
1570 }
1571 
1572 /*********************** Static local initialization **************************/
1573 
1574 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1575                                          llvm::PointerType *GuardPtrTy) {
1576   // int __cxa_guard_acquire(__guard *guard_object);
1577   llvm::FunctionType *FTy =
1578     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1579                             GuardPtrTy, /*isVarArg=*/false);
1580   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1581                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1582                                               llvm::AttributeSet::FunctionIndex,
1583                                                  llvm::Attribute::NoUnwind));
1584 }
1585 
1586 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1587                                          llvm::PointerType *GuardPtrTy) {
1588   // void __cxa_guard_release(__guard *guard_object);
1589   llvm::FunctionType *FTy =
1590     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1591   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1592                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1593                                               llvm::AttributeSet::FunctionIndex,
1594                                                  llvm::Attribute::NoUnwind));
1595 }
1596 
1597 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1598                                        llvm::PointerType *GuardPtrTy) {
1599   // void __cxa_guard_abort(__guard *guard_object);
1600   llvm::FunctionType *FTy =
1601     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1602   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1603                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1604                                               llvm::AttributeSet::FunctionIndex,
1605                                                  llvm::Attribute::NoUnwind));
1606 }
1607 
1608 namespace {
1609   struct CallGuardAbort : EHScopeStack::Cleanup {
1610     llvm::GlobalVariable *Guard;
1611     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1612 
1613     void Emit(CodeGenFunction &CGF, Flags flags) override {
1614       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1615                                   Guard);
1616     }
1617   };
1618 }
1619 
1620 /// The ARM code here follows the Itanium code closely enough that we
1621 /// just special-case it at particular places.
1622 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1623                                     const VarDecl &D,
1624                                     llvm::GlobalVariable *var,
1625                                     bool shouldPerformInit) {
1626   CGBuilderTy &Builder = CGF.Builder;
1627 
1628   // We only need to use thread-safe statics for local non-TLS variables;
1629   // global initialization is always single-threaded.
1630   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1631                     D.isLocalVarDecl() && !D.getTLSKind();
1632 
1633   // If we have a global variable with internal linkage and thread-safe statics
1634   // are disabled, we can just let the guard variable be of type i8.
1635   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1636 
1637   llvm::IntegerType *guardTy;
1638   if (useInt8GuardVariable) {
1639     guardTy = CGF.Int8Ty;
1640   } else {
1641     // Guard variables are 64 bits in the generic ABI and size width on ARM
1642     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1643     guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
1644   }
1645   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1646 
1647   // Create the guard variable if we don't already have it (as we
1648   // might if we're double-emitting this function body).
1649   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1650   if (!guard) {
1651     // Mangle the name for the guard.
1652     SmallString<256> guardName;
1653     {
1654       llvm::raw_svector_ostream out(guardName);
1655       getMangleContext().mangleStaticGuardVariable(&D, out);
1656       out.flush();
1657     }
1658 
1659     // Create the guard variable with a zero-initializer.
1660     // Just absorb linkage and visibility from the guarded variable.
1661     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1662                                      false, var->getLinkage(),
1663                                      llvm::ConstantInt::get(guardTy, 0),
1664                                      guardName.str());
1665     guard->setVisibility(var->getVisibility());
1666     // If the variable is thread-local, so is its guard variable.
1667     guard->setThreadLocalMode(var->getThreadLocalMode());
1668 
1669     // The ABI says: It is suggested that it be emitted in the same COMDAT group
1670     // as the associated data object
1671     if (!D.isLocalVarDecl() && var->isWeakForLinker() && CGM.supportsCOMDAT()) {
1672       llvm::Comdat *C = CGM.getModule().getOrInsertComdat(var->getName());
1673       guard->setComdat(C);
1674       var->setComdat(C);
1675       CGF.CurFn->setComdat(C);
1676     }
1677 
1678     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1679   }
1680 
1681   // Test whether the variable has completed initialization.
1682   //
1683   // Itanium C++ ABI 3.3.2:
1684   //   The following is pseudo-code showing how these functions can be used:
1685   //     if (obj_guard.first_byte == 0) {
1686   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1687   //         try {
1688   //           ... initialize the object ...;
1689   //         } catch (...) {
1690   //            __cxa_guard_abort (&obj_guard);
1691   //            throw;
1692   //         }
1693   //         ... queue object destructor with __cxa_atexit() ...;
1694   //         __cxa_guard_release (&obj_guard);
1695   //       }
1696   //     }
1697 
1698   // Load the first byte of the guard variable.
1699   llvm::LoadInst *LI =
1700       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1701   LI->setAlignment(1);
1702 
1703   // Itanium ABI:
1704   //   An implementation supporting thread-safety on multiprocessor
1705   //   systems must also guarantee that references to the initialized
1706   //   object do not occur before the load of the initialization flag.
1707   //
1708   // In LLVM, we do this by marking the load Acquire.
1709   if (threadsafe)
1710     LI->setAtomic(llvm::Acquire);
1711 
1712   // For ARM, we should only check the first bit, rather than the entire byte:
1713   //
1714   // ARM C++ ABI 3.2.3.1:
1715   //   To support the potential use of initialization guard variables
1716   //   as semaphores that are the target of ARM SWP and LDREX/STREX
1717   //   synchronizing instructions we define a static initialization
1718   //   guard variable to be a 4-byte aligned, 4-byte word with the
1719   //   following inline access protocol.
1720   //     #define INITIALIZED 1
1721   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
1722   //       if (__cxa_guard_acquire(&obj_guard))
1723   //         ...
1724   //     }
1725   //
1726   // and similarly for ARM64:
1727   //
1728   // ARM64 C++ ABI 3.2.2:
1729   //   This ABI instead only specifies the value bit 0 of the static guard
1730   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
1731   //   variable is not initialized and 1 when it is.
1732   llvm::Value *V =
1733       (UseARMGuardVarABI && !useInt8GuardVariable)
1734           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1735           : LI;
1736   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1737 
1738   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1739   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1740 
1741   // Check if the first byte of the guard variable is zero.
1742   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1743 
1744   CGF.EmitBlock(InitCheckBlock);
1745 
1746   // Variables used when coping with thread-safe statics and exceptions.
1747   if (threadsafe) {
1748     // Call __cxa_guard_acquire.
1749     llvm::Value *V
1750       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1751 
1752     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1753 
1754     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1755                          InitBlock, EndBlock);
1756 
1757     // Call __cxa_guard_abort along the exceptional edge.
1758     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1759 
1760     CGF.EmitBlock(InitBlock);
1761   }
1762 
1763   // Emit the initializer and add a global destructor if appropriate.
1764   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1765 
1766   if (threadsafe) {
1767     // Pop the guard-abort cleanup if we pushed one.
1768     CGF.PopCleanupBlock();
1769 
1770     // Call __cxa_guard_release.  This cannot throw.
1771     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1772   } else {
1773     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1774   }
1775 
1776   CGF.EmitBlock(EndBlock);
1777 }
1778 
1779 /// Register a global destructor using __cxa_atexit.
1780 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1781                                         llvm::Constant *dtor,
1782                                         llvm::Constant *addr,
1783                                         bool TLS) {
1784   const char *Name = "__cxa_atexit";
1785   if (TLS) {
1786     const llvm::Triple &T = CGF.getTarget().getTriple();
1787     Name = T.isMacOSX() ?  "_tlv_atexit" : "__cxa_thread_atexit";
1788   }
1789 
1790   // We're assuming that the destructor function is something we can
1791   // reasonably call with the default CC.  Go ahead and cast it to the
1792   // right prototype.
1793   llvm::Type *dtorTy =
1794     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1795 
1796   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1797   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1798   llvm::FunctionType *atexitTy =
1799     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1800 
1801   // Fetch the actual function.
1802   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
1803   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1804     fn->setDoesNotThrow();
1805 
1806   // Create a variable that binds the atexit to this shared object.
1807   llvm::Constant *handle =
1808     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1809 
1810   llvm::Value *args[] = {
1811     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1812     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1813     handle
1814   };
1815   CGF.EmitNounwindRuntimeCall(atexit, args);
1816 }
1817 
1818 /// Register a global destructor as best as we know how.
1819 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1820                                        const VarDecl &D,
1821                                        llvm::Constant *dtor,
1822                                        llvm::Constant *addr) {
1823   // Use __cxa_atexit if available.
1824   if (CGM.getCodeGenOpts().CXAAtExit)
1825     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1826 
1827   if (D.getTLSKind())
1828     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
1829 
1830   // In Apple kexts, we want to add a global destructor entry.
1831   // FIXME: shouldn't this be guarded by some variable?
1832   if (CGM.getLangOpts().AppleKext) {
1833     // Generate a global destructor entry.
1834     return CGM.AddCXXDtorEntry(dtor, addr);
1835   }
1836 
1837   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
1838 }
1839 
1840 static bool isThreadWrapperReplaceable(const VarDecl *VD,
1841                                        CodeGen::CodeGenModule &CGM) {
1842   assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
1843   // OS X prefers to have references to thread local variables to go through
1844   // the thread wrapper instead of directly referencing the backing variable.
1845   return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1846          CGM.getTarget().getTriple().isMacOSX();
1847 }
1848 
1849 /// Get the appropriate linkage for the wrapper function. This is essentially
1850 /// the weak form of the variable's linkage; every translation unit which needs
1851 /// the wrapper emits a copy, and we want the linker to merge them.
1852 static llvm::GlobalValue::LinkageTypes
1853 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1854   llvm::GlobalValue::LinkageTypes VarLinkage =
1855       CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1856 
1857   // For internal linkage variables, we don't need an external or weak wrapper.
1858   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1859     return VarLinkage;
1860 
1861   // If the thread wrapper is replaceable, give it appropriate linkage.
1862   if (isThreadWrapperReplaceable(VD, CGM)) {
1863     if (llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) ||
1864         llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
1865       return llvm::GlobalVariable::WeakAnyLinkage;
1866     return VarLinkage;
1867   }
1868   return llvm::GlobalValue::WeakODRLinkage;
1869 }
1870 
1871 llvm::Function *
1872 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1873                                              llvm::GlobalVariable *Var) {
1874   // Mangle the name for the thread_local wrapper function.
1875   SmallString<256> WrapperName;
1876   {
1877     llvm::raw_svector_ostream Out(WrapperName);
1878     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1879     Out.flush();
1880   }
1881 
1882   if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1883     return cast<llvm::Function>(V);
1884 
1885   llvm::Type *RetTy = Var->getType();
1886   if (VD->getType()->isReferenceType())
1887     RetTy = RetTy->getPointerElementType();
1888 
1889   llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1890   llvm::Function *Wrapper =
1891       llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1892                              WrapperName.str(), &CGM.getModule());
1893   // Always resolve references to the wrapper at link time.
1894   if (!Wrapper->hasLocalLinkage() && !isThreadWrapperReplaceable(VD, CGM))
1895     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1896   return Wrapper;
1897 }
1898 
1899 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1900     ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1901     llvm::Function *InitFunc) {
1902   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1903     const VarDecl *VD = Decls[I].first;
1904     llvm::GlobalVariable *Var = Decls[I].second;
1905 
1906     // Some targets require that all access to thread local variables go through
1907     // the thread wrapper.  This means that we cannot attempt to create a thread
1908     // wrapper or a thread helper.
1909     if (isThreadWrapperReplaceable(VD, CGM) && !VD->hasDefinition())
1910       continue;
1911 
1912     // Mangle the name for the thread_local initialization function.
1913     SmallString<256> InitFnName;
1914     {
1915       llvm::raw_svector_ostream Out(InitFnName);
1916       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1917       Out.flush();
1918     }
1919 
1920     // If we have a definition for the variable, emit the initialization
1921     // function as an alias to the global Init function (if any). Otherwise,
1922     // produce a declaration of the initialization function.
1923     llvm::GlobalValue *Init = nullptr;
1924     bool InitIsInitFunc = false;
1925     if (VD->hasDefinition()) {
1926       InitIsInitFunc = true;
1927       if (InitFunc)
1928         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1929                                          InitFunc);
1930     } else {
1931       // Emit a weak global function referring to the initialization function.
1932       // This function will not exist if the TU defining the thread_local
1933       // variable in question does not need any dynamic initialization for
1934       // its thread_local variables.
1935       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1936       Init = llvm::Function::Create(
1937           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1938           &CGM.getModule());
1939     }
1940 
1941     if (Init)
1942       Init->setVisibility(Var->getVisibility());
1943 
1944     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1945     llvm::LLVMContext &Context = CGM.getModule().getContext();
1946     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1947     CGBuilderTy Builder(Entry);
1948     if (InitIsInitFunc) {
1949       if (Init)
1950         Builder.CreateCall(Init);
1951     } else {
1952       // Don't know whether we have an init function. Call it if it exists.
1953       llvm::Value *Have = Builder.CreateIsNotNull(Init);
1954       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1955       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1956       Builder.CreateCondBr(Have, InitBB, ExitBB);
1957 
1958       Builder.SetInsertPoint(InitBB);
1959       Builder.CreateCall(Init);
1960       Builder.CreateBr(ExitBB);
1961 
1962       Builder.SetInsertPoint(ExitBB);
1963     }
1964 
1965     // For a reference, the result of the wrapper function is a pointer to
1966     // the referenced object.
1967     llvm::Value *Val = Var;
1968     if (VD->getType()->isReferenceType()) {
1969       llvm::LoadInst *LI = Builder.CreateLoad(Val);
1970       LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1971       Val = LI;
1972     }
1973 
1974     Builder.CreateRet(Val);
1975   }
1976 }
1977 
1978 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1979                                                    const VarDecl *VD,
1980                                                    QualType LValType) {
1981   QualType T = VD->getType();
1982   llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1983   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1984   llvm::Function *Wrapper =
1985       getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1986 
1987   Val = CGF.Builder.CreateCall(Wrapper);
1988 
1989   LValue LV;
1990   if (VD->getType()->isReferenceType())
1991     LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
1992   else
1993     LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
1994   // FIXME: need setObjCGCLValueClass?
1995   return LV;
1996 }
1997 
1998 /// Return whether the given global decl needs a VTT parameter, which it does
1999 /// if it's a base constructor or destructor with virtual bases.
2000 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
2001   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
2002 
2003   // We don't have any virtual bases, just return early.
2004   if (!MD->getParent()->getNumVBases())
2005     return false;
2006 
2007   // Check if we have a base constructor.
2008   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
2009     return true;
2010 
2011   // Check if we have a base destructor.
2012   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
2013     return true;
2014 
2015   return false;
2016 }
2017 
2018 namespace {
2019 class ItaniumRTTIBuilder {
2020   CodeGenModule &CGM;  // Per-module state.
2021   llvm::LLVMContext &VMContext;
2022   const ItaniumCXXABI &CXXABI;  // Per-module state.
2023 
2024   /// Fields - The fields of the RTTI descriptor currently being built.
2025   SmallVector<llvm::Constant *, 16> Fields;
2026 
2027   /// GetAddrOfTypeName - Returns the mangled type name of the given type.
2028   llvm::GlobalVariable *
2029   GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
2030 
2031   /// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
2032   /// descriptor of the given type.
2033   llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
2034 
2035   /// BuildVTablePointer - Build the vtable pointer for the given type.
2036   void BuildVTablePointer(const Type *Ty);
2037 
2038   /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2039   /// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
2040   void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
2041 
2042   /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2043   /// classes with bases that do not satisfy the abi::__si_class_type_info
2044   /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2045   void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
2046 
2047   /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
2048   /// for pointer types.
2049   void BuildPointerTypeInfo(QualType PointeeTy);
2050 
2051   /// BuildObjCObjectTypeInfo - Build the appropriate kind of
2052   /// type_info for an object type.
2053   void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
2054 
2055   /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2056   /// struct, used for member pointer types.
2057   void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
2058 
2059 public:
2060   ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
2061       : CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
2062 
2063   // Pointer type info flags.
2064   enum {
2065     /// PTI_Const - Type has const qualifier.
2066     PTI_Const = 0x1,
2067 
2068     /// PTI_Volatile - Type has volatile qualifier.
2069     PTI_Volatile = 0x2,
2070 
2071     /// PTI_Restrict - Type has restrict qualifier.
2072     PTI_Restrict = 0x4,
2073 
2074     /// PTI_Incomplete - Type is incomplete.
2075     PTI_Incomplete = 0x8,
2076 
2077     /// PTI_ContainingClassIncomplete - Containing class is incomplete.
2078     /// (in pointer to member).
2079     PTI_ContainingClassIncomplete = 0x10
2080   };
2081 
2082   // VMI type info flags.
2083   enum {
2084     /// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
2085     VMI_NonDiamondRepeat = 0x1,
2086 
2087     /// VMI_DiamondShaped - Class is diamond shaped.
2088     VMI_DiamondShaped = 0x2
2089   };
2090 
2091   // Base class type info flags.
2092   enum {
2093     /// BCTI_Virtual - Base class is virtual.
2094     BCTI_Virtual = 0x1,
2095 
2096     /// BCTI_Public - Base class is public.
2097     BCTI_Public = 0x2
2098   };
2099 
2100   /// BuildTypeInfo - Build the RTTI type info struct for the given type.
2101   ///
2102   /// \param Force - true to force the creation of this RTTI value
2103   llvm::Constant *BuildTypeInfo(QualType Ty, bool Force = false);
2104 };
2105 }
2106 
2107 llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
2108     QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
2109   SmallString<256> OutName;
2110   llvm::raw_svector_ostream Out(OutName);
2111   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
2112   Out.flush();
2113   StringRef Name = OutName.str();
2114 
2115   // We know that the mangled name of the type starts at index 4 of the
2116   // mangled name of the typename, so we can just index into it in order to
2117   // get the mangled name of the type.
2118   llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
2119                                                             Name.substr(4));
2120 
2121   llvm::GlobalVariable *GV =
2122     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
2123 
2124   GV->setInitializer(Init);
2125 
2126   return GV;
2127 }
2128 
2129 llvm::Constant *
2130 ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
2131   // Mangle the RTTI name.
2132   SmallString<256> OutName;
2133   llvm::raw_svector_ostream Out(OutName);
2134   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2135   Out.flush();
2136   StringRef Name = OutName.str();
2137 
2138   // Look for an existing global.
2139   llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
2140 
2141   if (!GV) {
2142     // Create a new global variable.
2143     GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
2144                                   /*Constant=*/true,
2145                                   llvm::GlobalValue::ExternalLinkage, nullptr,
2146                                   Name);
2147   }
2148 
2149   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2150 }
2151 
2152 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
2153 /// info for that type is defined in the standard library.
2154 static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
2155   // Itanium C++ ABI 2.9.2:
2156   //   Basic type information (e.g. for "int", "bool", etc.) will be kept in
2157   //   the run-time support library. Specifically, the run-time support
2158   //   library should contain type_info objects for the types X, X* and
2159   //   X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
2160   //   unsigned char, signed char, short, unsigned short, int, unsigned int,
2161   //   long, unsigned long, long long, unsigned long long, float, double,
2162   //   long double, char16_t, char32_t, and the IEEE 754r decimal and
2163   //   half-precision floating point types.
2164   switch (Ty->getKind()) {
2165     case BuiltinType::Void:
2166     case BuiltinType::NullPtr:
2167     case BuiltinType::Bool:
2168     case BuiltinType::WChar_S:
2169     case BuiltinType::WChar_U:
2170     case BuiltinType::Char_U:
2171     case BuiltinType::Char_S:
2172     case BuiltinType::UChar:
2173     case BuiltinType::SChar:
2174     case BuiltinType::Short:
2175     case BuiltinType::UShort:
2176     case BuiltinType::Int:
2177     case BuiltinType::UInt:
2178     case BuiltinType::Long:
2179     case BuiltinType::ULong:
2180     case BuiltinType::LongLong:
2181     case BuiltinType::ULongLong:
2182     case BuiltinType::Half:
2183     case BuiltinType::Float:
2184     case BuiltinType::Double:
2185     case BuiltinType::LongDouble:
2186     case BuiltinType::Char16:
2187     case BuiltinType::Char32:
2188     case BuiltinType::Int128:
2189     case BuiltinType::UInt128:
2190     case BuiltinType::OCLImage1d:
2191     case BuiltinType::OCLImage1dArray:
2192     case BuiltinType::OCLImage1dBuffer:
2193     case BuiltinType::OCLImage2d:
2194     case BuiltinType::OCLImage2dArray:
2195     case BuiltinType::OCLImage3d:
2196     case BuiltinType::OCLSampler:
2197     case BuiltinType::OCLEvent:
2198       return true;
2199 
2200     case BuiltinType::Dependent:
2201 #define BUILTIN_TYPE(Id, SingletonId)
2202 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2203     case BuiltinType::Id:
2204 #include "clang/AST/BuiltinTypes.def"
2205       llvm_unreachable("asking for RRTI for a placeholder type!");
2206 
2207     case BuiltinType::ObjCId:
2208     case BuiltinType::ObjCClass:
2209     case BuiltinType::ObjCSel:
2210       llvm_unreachable("FIXME: Objective-C types are unsupported!");
2211   }
2212 
2213   llvm_unreachable("Invalid BuiltinType Kind!");
2214 }
2215 
2216 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
2217   QualType PointeeTy = PointerTy->getPointeeType();
2218   const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
2219   if (!BuiltinTy)
2220     return false;
2221 
2222   // Check the qualifiers.
2223   Qualifiers Quals = PointeeTy.getQualifiers();
2224   Quals.removeConst();
2225 
2226   if (!Quals.empty())
2227     return false;
2228 
2229   return TypeInfoIsInStandardLibrary(BuiltinTy);
2230 }
2231 
2232 /// IsStandardLibraryRTTIDescriptor - Returns whether the type
2233 /// information for the given type exists in the standard library.
2234 static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
2235   // Type info for builtin types is defined in the standard library.
2236   if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
2237     return TypeInfoIsInStandardLibrary(BuiltinTy);
2238 
2239   // Type info for some pointer types to builtin types is defined in the
2240   // standard library.
2241   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2242     return TypeInfoIsInStandardLibrary(PointerTy);
2243 
2244   return false;
2245 }
2246 
2247 /// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
2248 /// the given type exists somewhere else, and that we should not emit the type
2249 /// information in this translation unit.  Assumes that it is not a
2250 /// standard-library type.
2251 static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
2252                                             QualType Ty) {
2253   ASTContext &Context = CGM.getContext();
2254 
2255   // If RTTI is disabled, assume it might be disabled in the
2256   // translation unit that defines any potential key function, too.
2257   if (!Context.getLangOpts().RTTI) return false;
2258 
2259   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2260     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
2261     if (!RD->hasDefinition())
2262       return false;
2263 
2264     if (!RD->isDynamicClass())
2265       return false;
2266 
2267     // FIXME: this may need to be reconsidered if the key function
2268     // changes.
2269     return CGM.getVTables().isVTableExternal(RD);
2270   }
2271 
2272   return false;
2273 }
2274 
2275 /// IsIncompleteClassType - Returns whether the given record type is incomplete.
2276 static bool IsIncompleteClassType(const RecordType *RecordTy) {
2277   return !RecordTy->getDecl()->isCompleteDefinition();
2278 }
2279 
2280 /// ContainsIncompleteClassType - Returns whether the given type contains an
2281 /// incomplete class type. This is true if
2282 ///
2283 ///   * The given type is an incomplete class type.
2284 ///   * The given type is a pointer type whose pointee type contains an
2285 ///     incomplete class type.
2286 ///   * The given type is a member pointer type whose class is an incomplete
2287 ///     class type.
2288 ///   * The given type is a member pointer type whoise pointee type contains an
2289 ///     incomplete class type.
2290 /// is an indirect or direct pointer to an incomplete class type.
2291 static bool ContainsIncompleteClassType(QualType Ty) {
2292   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
2293     if (IsIncompleteClassType(RecordTy))
2294       return true;
2295   }
2296 
2297   if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
2298     return ContainsIncompleteClassType(PointerTy->getPointeeType());
2299 
2300   if (const MemberPointerType *MemberPointerTy =
2301       dyn_cast<MemberPointerType>(Ty)) {
2302     // Check if the class type is incomplete.
2303     const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
2304     if (IsIncompleteClassType(ClassType))
2305       return true;
2306 
2307     return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
2308   }
2309 
2310   return false;
2311 }
2312 
2313 // CanUseSingleInheritance - Return whether the given record decl has a "single,
2314 // public, non-virtual base at offset zero (i.e. the derived class is dynamic
2315 // iff the base is)", according to Itanium C++ ABI, 2.95p6b.
2316 static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
2317   // Check the number of bases.
2318   if (RD->getNumBases() != 1)
2319     return false;
2320 
2321   // Get the base.
2322   CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
2323 
2324   // Check that the base is not virtual.
2325   if (Base->isVirtual())
2326     return false;
2327 
2328   // Check that the base is public.
2329   if (Base->getAccessSpecifier() != AS_public)
2330     return false;
2331 
2332   // Check that the class is dynamic iff the base is.
2333   const CXXRecordDecl *BaseDecl =
2334     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2335   if (!BaseDecl->isEmpty() &&
2336       BaseDecl->isDynamicClass() != RD->isDynamicClass())
2337     return false;
2338 
2339   return true;
2340 }
2341 
2342 void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
2343   // abi::__class_type_info.
2344   static const char * const ClassTypeInfo =
2345     "_ZTVN10__cxxabiv117__class_type_infoE";
2346   // abi::__si_class_type_info.
2347   static const char * const SIClassTypeInfo =
2348     "_ZTVN10__cxxabiv120__si_class_type_infoE";
2349   // abi::__vmi_class_type_info.
2350   static const char * const VMIClassTypeInfo =
2351     "_ZTVN10__cxxabiv121__vmi_class_type_infoE";
2352 
2353   const char *VTableName = nullptr;
2354 
2355   switch (Ty->getTypeClass()) {
2356 #define TYPE(Class, Base)
2357 #define ABSTRACT_TYPE(Class, Base)
2358 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2359 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2360 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2361 #include "clang/AST/TypeNodes.def"
2362     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2363 
2364   case Type::LValueReference:
2365   case Type::RValueReference:
2366     llvm_unreachable("References shouldn't get here");
2367 
2368   case Type::Auto:
2369     llvm_unreachable("Undeduced auto type shouldn't get here");
2370 
2371   case Type::Builtin:
2372   // GCC treats vector and complex types as fundamental types.
2373   case Type::Vector:
2374   case Type::ExtVector:
2375   case Type::Complex:
2376   case Type::Atomic:
2377   // FIXME: GCC treats block pointers as fundamental types?!
2378   case Type::BlockPointer:
2379     // abi::__fundamental_type_info.
2380     VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
2381     break;
2382 
2383   case Type::ConstantArray:
2384   case Type::IncompleteArray:
2385   case Type::VariableArray:
2386     // abi::__array_type_info.
2387     VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
2388     break;
2389 
2390   case Type::FunctionNoProto:
2391   case Type::FunctionProto:
2392     // abi::__function_type_info.
2393     VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
2394     break;
2395 
2396   case Type::Enum:
2397     // abi::__enum_type_info.
2398     VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
2399     break;
2400 
2401   case Type::Record: {
2402     const CXXRecordDecl *RD =
2403       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2404 
2405     if (!RD->hasDefinition() || !RD->getNumBases()) {
2406       VTableName = ClassTypeInfo;
2407     } else if (CanUseSingleInheritance(RD)) {
2408       VTableName = SIClassTypeInfo;
2409     } else {
2410       VTableName = VMIClassTypeInfo;
2411     }
2412 
2413     break;
2414   }
2415 
2416   case Type::ObjCObject:
2417     // Ignore protocol qualifiers.
2418     Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
2419 
2420     // Handle id and Class.
2421     if (isa<BuiltinType>(Ty)) {
2422       VTableName = ClassTypeInfo;
2423       break;
2424     }
2425 
2426     assert(isa<ObjCInterfaceType>(Ty));
2427     // Fall through.
2428 
2429   case Type::ObjCInterface:
2430     if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
2431       VTableName = SIClassTypeInfo;
2432     } else {
2433       VTableName = ClassTypeInfo;
2434     }
2435     break;
2436 
2437   case Type::ObjCObjectPointer:
2438   case Type::Pointer:
2439     // abi::__pointer_type_info.
2440     VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
2441     break;
2442 
2443   case Type::MemberPointer:
2444     // abi::__pointer_to_member_type_info.
2445     VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
2446     break;
2447   }
2448 
2449   llvm::Constant *VTable =
2450     CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
2451 
2452   llvm::Type *PtrDiffTy =
2453     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
2454 
2455   // The vtable address point is 2.
2456   llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
2457   VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
2458   VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
2459 
2460   Fields.push_back(VTable);
2461 }
2462 
2463 /// \brief Return the linkage that the type info and type info name constants
2464 /// should have for the given type.
2465 static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
2466                                                              QualType Ty) {
2467   // Itanium C++ ABI 2.9.5p7:
2468   //   In addition, it and all of the intermediate abi::__pointer_type_info
2469   //   structs in the chain down to the abi::__class_type_info for the
2470   //   incomplete class type must be prevented from resolving to the
2471   //   corresponding type_info structs for the complete class type, possibly
2472   //   by making them local static objects. Finally, a dummy class RTTI is
2473   //   generated for the incomplete type that will not resolve to the final
2474   //   complete class RTTI (because the latter need not exist), possibly by
2475   //   making it a local static object.
2476   if (ContainsIncompleteClassType(Ty))
2477     return llvm::GlobalValue::InternalLinkage;
2478 
2479   switch (Ty->getLinkage()) {
2480   case NoLinkage:
2481   case InternalLinkage:
2482   case UniqueExternalLinkage:
2483     return llvm::GlobalValue::InternalLinkage;
2484 
2485   case VisibleNoLinkage:
2486   case ExternalLinkage:
2487     if (!CGM.getLangOpts().RTTI) {
2488       // RTTI is not enabled, which means that this type info struct is going
2489       // to be used for exception handling. Give it linkonce_odr linkage.
2490       return llvm::GlobalValue::LinkOnceODRLinkage;
2491     }
2492 
2493     if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
2494       const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2495       if (RD->hasAttr<WeakAttr>())
2496         return llvm::GlobalValue::WeakODRLinkage;
2497       if (RD->isDynamicClass())
2498         return CGM.getVTableLinkage(RD);
2499     }
2500 
2501     return llvm::GlobalValue::LinkOnceODRLinkage;
2502   }
2503 
2504   llvm_unreachable("Invalid linkage!");
2505 }
2506 
2507 llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
2508   // We want to operate on the canonical type.
2509   Ty = CGM.getContext().getCanonicalType(Ty);
2510 
2511   // Check if we've already emitted an RTTI descriptor for this type.
2512   SmallString<256> OutName;
2513   llvm::raw_svector_ostream Out(OutName);
2514   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
2515   Out.flush();
2516   StringRef Name = OutName.str();
2517 
2518   llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
2519   if (OldGV && !OldGV->isDeclaration()) {
2520     assert(!OldGV->hasAvailableExternallyLinkage() &&
2521            "available_externally typeinfos not yet implemented");
2522 
2523     return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
2524   }
2525 
2526   // Check if there is already an external RTTI descriptor for this type.
2527   bool IsStdLib = IsStandardLibraryRTTIDescriptor(Ty);
2528   if (!Force && (IsStdLib || ShouldUseExternalRTTIDescriptor(CGM, Ty)))
2529     return GetAddrOfExternalRTTIDescriptor(Ty);
2530 
2531   // Emit the standard library with external linkage.
2532   llvm::GlobalVariable::LinkageTypes Linkage;
2533   if (IsStdLib)
2534     Linkage = llvm::GlobalValue::ExternalLinkage;
2535   else
2536     Linkage = getTypeInfoLinkage(CGM, Ty);
2537 
2538   // Add the vtable pointer.
2539   BuildVTablePointer(cast<Type>(Ty));
2540 
2541   // And the name.
2542   llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
2543   llvm::Constant *TypeNameField;
2544 
2545   // If we're supposed to demote the visibility, be sure to set a flag
2546   // to use a string comparison for type_info comparisons.
2547   ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
2548       CXXABI.classifyRTTIUniqueness(Ty, Linkage);
2549   if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
2550     // The flag is the sign bit, which on ARM64 is defined to be clear
2551     // for global pointers.  This is very ARM64-specific.
2552     TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
2553     llvm::Constant *flag =
2554         llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
2555     TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
2556     TypeNameField =
2557         llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
2558   } else {
2559     TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
2560   }
2561   Fields.push_back(TypeNameField);
2562 
2563   switch (Ty->getTypeClass()) {
2564 #define TYPE(Class, Base)
2565 #define ABSTRACT_TYPE(Class, Base)
2566 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2567 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2568 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2569 #include "clang/AST/TypeNodes.def"
2570     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
2571 
2572   // GCC treats vector types as fundamental types.
2573   case Type::Builtin:
2574   case Type::Vector:
2575   case Type::ExtVector:
2576   case Type::Complex:
2577   case Type::BlockPointer:
2578     // Itanium C++ ABI 2.9.5p4:
2579     // abi::__fundamental_type_info adds no data members to std::type_info.
2580     break;
2581 
2582   case Type::LValueReference:
2583   case Type::RValueReference:
2584     llvm_unreachable("References shouldn't get here");
2585 
2586   case Type::Auto:
2587     llvm_unreachable("Undeduced auto type shouldn't get here");
2588 
2589   case Type::ConstantArray:
2590   case Type::IncompleteArray:
2591   case Type::VariableArray:
2592     // Itanium C++ ABI 2.9.5p5:
2593     // abi::__array_type_info adds no data members to std::type_info.
2594     break;
2595 
2596   case Type::FunctionNoProto:
2597   case Type::FunctionProto:
2598     // Itanium C++ ABI 2.9.5p5:
2599     // abi::__function_type_info adds no data members to std::type_info.
2600     break;
2601 
2602   case Type::Enum:
2603     // Itanium C++ ABI 2.9.5p5:
2604     // abi::__enum_type_info adds no data members to std::type_info.
2605     break;
2606 
2607   case Type::Record: {
2608     const CXXRecordDecl *RD =
2609       cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
2610     if (!RD->hasDefinition() || !RD->getNumBases()) {
2611       // We don't need to emit any fields.
2612       break;
2613     }
2614 
2615     if (CanUseSingleInheritance(RD))
2616       BuildSIClassTypeInfo(RD);
2617     else
2618       BuildVMIClassTypeInfo(RD);
2619 
2620     break;
2621   }
2622 
2623   case Type::ObjCObject:
2624   case Type::ObjCInterface:
2625     BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
2626     break;
2627 
2628   case Type::ObjCObjectPointer:
2629     BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2630     break;
2631 
2632   case Type::Pointer:
2633     BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
2634     break;
2635 
2636   case Type::MemberPointer:
2637     BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
2638     break;
2639 
2640   case Type::Atomic:
2641     // No fields, at least for the moment.
2642     break;
2643   }
2644 
2645   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
2646 
2647   llvm::GlobalVariable *GV =
2648     new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2649                              /*Constant=*/true, Linkage, Init, Name);
2650 
2651   // If there's already an old global variable, replace it with the new one.
2652   if (OldGV) {
2653     GV->takeName(OldGV);
2654     llvm::Constant *NewPtr =
2655       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2656     OldGV->replaceAllUsesWith(NewPtr);
2657     OldGV->eraseFromParent();
2658   }
2659 
2660   // The Itanium ABI specifies that type_info objects must be globally
2661   // unique, with one exception: if the type is an incomplete class
2662   // type or a (possibly indirect) pointer to one.  That exception
2663   // affects the general case of comparing type_info objects produced
2664   // by the typeid operator, which is why the comparison operators on
2665   // std::type_info generally use the type_info name pointers instead
2666   // of the object addresses.  However, the language's built-in uses
2667   // of RTTI generally require class types to be complete, even when
2668   // manipulating pointers to those class types.  This allows the
2669   // implementation of dynamic_cast to rely on address equality tests,
2670   // which is much faster.
2671 
2672   // All of this is to say that it's important that both the type_info
2673   // object and the type_info name be uniqued when weakly emitted.
2674 
2675   // Give the type_info object and name the formal visibility of the
2676   // type itself.
2677   llvm::GlobalValue::VisibilityTypes llvmVisibility;
2678   if (llvm::GlobalValue::isLocalLinkage(Linkage))
2679     // If the linkage is local, only default visibility makes sense.
2680     llvmVisibility = llvm::GlobalValue::DefaultVisibility;
2681   else if (RTTIUniqueness == ItaniumCXXABI::RUK_NonUniqueHidden)
2682     llvmVisibility = llvm::GlobalValue::HiddenVisibility;
2683   else
2684     llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
2685   TypeName->setVisibility(llvmVisibility);
2686   GV->setVisibility(llvmVisibility);
2687 
2688   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
2689 }
2690 
2691 /// ComputeQualifierFlags - Compute the pointer type info flags from the
2692 /// given qualifier.
2693 static unsigned ComputeQualifierFlags(Qualifiers Quals) {
2694   unsigned Flags = 0;
2695 
2696   if (Quals.hasConst())
2697     Flags |= ItaniumRTTIBuilder::PTI_Const;
2698   if (Quals.hasVolatile())
2699     Flags |= ItaniumRTTIBuilder::PTI_Volatile;
2700   if (Quals.hasRestrict())
2701     Flags |= ItaniumRTTIBuilder::PTI_Restrict;
2702 
2703   return Flags;
2704 }
2705 
2706 /// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
2707 /// for the given Objective-C object type.
2708 void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
2709   // Drop qualifiers.
2710   const Type *T = OT->getBaseType().getTypePtr();
2711   assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
2712 
2713   // The builtin types are abi::__class_type_infos and don't require
2714   // extra fields.
2715   if (isa<BuiltinType>(T)) return;
2716 
2717   ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
2718   ObjCInterfaceDecl *Super = Class->getSuperClass();
2719 
2720   // Root classes are also __class_type_info.
2721   if (!Super) return;
2722 
2723   QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
2724 
2725   // Everything else is single inheritance.
2726   llvm::Constant *BaseTypeInfo =
2727       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
2728   Fields.push_back(BaseTypeInfo);
2729 }
2730 
2731 /// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
2732 /// inheritance, according to the Itanium C++ ABI, 2.95p6b.
2733 void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
2734   // Itanium C++ ABI 2.9.5p6b:
2735   // It adds to abi::__class_type_info a single member pointing to the
2736   // type_info structure for the base type,
2737   llvm::Constant *BaseTypeInfo =
2738     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
2739   Fields.push_back(BaseTypeInfo);
2740 }
2741 
2742 namespace {
2743   /// SeenBases - Contains virtual and non-virtual bases seen when traversing
2744   /// a class hierarchy.
2745   struct SeenBases {
2746     llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
2747     llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
2748   };
2749 }
2750 
2751 /// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
2752 /// abi::__vmi_class_type_info.
2753 ///
2754 static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
2755                                              SeenBases &Bases) {
2756 
2757   unsigned Flags = 0;
2758 
2759   const CXXRecordDecl *BaseDecl =
2760     cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2761 
2762   if (Base->isVirtual()) {
2763     // Mark the virtual base as seen.
2764     if (!Bases.VirtualBases.insert(BaseDecl)) {
2765       // If this virtual base has been seen before, then the class is diamond
2766       // shaped.
2767       Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
2768     } else {
2769       if (Bases.NonVirtualBases.count(BaseDecl))
2770         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2771     }
2772   } else {
2773     // Mark the non-virtual base as seen.
2774     if (!Bases.NonVirtualBases.insert(BaseDecl)) {
2775       // If this non-virtual base has been seen before, then the class has non-
2776       // diamond shaped repeated inheritance.
2777       Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2778     } else {
2779       if (Bases.VirtualBases.count(BaseDecl))
2780         Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
2781     }
2782   }
2783 
2784   // Walk all bases.
2785   for (const auto &I : BaseDecl->bases())
2786     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2787 
2788   return Flags;
2789 }
2790 
2791 static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
2792   unsigned Flags = 0;
2793   SeenBases Bases;
2794 
2795   // Walk all bases.
2796   for (const auto &I : RD->bases())
2797     Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
2798 
2799   return Flags;
2800 }
2801 
2802 /// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
2803 /// classes with bases that do not satisfy the abi::__si_class_type_info
2804 /// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
2805 void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
2806   llvm::Type *UnsignedIntLTy =
2807     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2808 
2809   // Itanium C++ ABI 2.9.5p6c:
2810   //   __flags is a word with flags describing details about the class
2811   //   structure, which may be referenced by using the __flags_masks
2812   //   enumeration. These flags refer to both direct and indirect bases.
2813   unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
2814   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2815 
2816   // Itanium C++ ABI 2.9.5p6c:
2817   //   __base_count is a word with the number of direct proper base class
2818   //   descriptions that follow.
2819   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
2820 
2821   if (!RD->getNumBases())
2822     return;
2823 
2824   llvm::Type *LongLTy =
2825     CGM.getTypes().ConvertType(CGM.getContext().LongTy);
2826 
2827   // Now add the base class descriptions.
2828 
2829   // Itanium C++ ABI 2.9.5p6c:
2830   //   __base_info[] is an array of base class descriptions -- one for every
2831   //   direct proper base. Each description is of the type:
2832   //
2833   //   struct abi::__base_class_type_info {
2834   //   public:
2835   //     const __class_type_info *__base_type;
2836   //     long __offset_flags;
2837   //
2838   //     enum __offset_flags_masks {
2839   //       __virtual_mask = 0x1,
2840   //       __public_mask = 0x2,
2841   //       __offset_shift = 8
2842   //     };
2843   //   };
2844   for (const auto &Base : RD->bases()) {
2845     // The __base_type member points to the RTTI for the base type.
2846     Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
2847 
2848     const CXXRecordDecl *BaseDecl =
2849       cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
2850 
2851     int64_t OffsetFlags = 0;
2852 
2853     // All but the lower 8 bits of __offset_flags are a signed offset.
2854     // For a non-virtual base, this is the offset in the object of the base
2855     // subobject. For a virtual base, this is the offset in the virtual table of
2856     // the virtual base offset for the virtual base referenced (negative).
2857     CharUnits Offset;
2858     if (Base.isVirtual())
2859       Offset =
2860         CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
2861     else {
2862       const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
2863       Offset = Layout.getBaseClassOffset(BaseDecl);
2864     };
2865 
2866     OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
2867 
2868     // The low-order byte of __offset_flags contains flags, as given by the
2869     // masks from the enumeration __offset_flags_masks.
2870     if (Base.isVirtual())
2871       OffsetFlags |= BCTI_Virtual;
2872     if (Base.getAccessSpecifier() == AS_public)
2873       OffsetFlags |= BCTI_Public;
2874 
2875     Fields.push_back(llvm::ConstantInt::get(LongLTy, OffsetFlags));
2876   }
2877 }
2878 
2879 /// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
2880 /// used for pointer types.
2881 void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
2882   Qualifiers Quals;
2883   QualType UnqualifiedPointeeTy =
2884     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2885 
2886   // Itanium C++ ABI 2.9.5p7:
2887   //   __flags is a flag word describing the cv-qualification and other
2888   //   attributes of the type pointed to
2889   unsigned Flags = ComputeQualifierFlags(Quals);
2890 
2891   // Itanium C++ ABI 2.9.5p7:
2892   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
2893   //   incomplete class type, the incomplete target type flag is set.
2894   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2895     Flags |= PTI_Incomplete;
2896 
2897   llvm::Type *UnsignedIntLTy =
2898     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2899   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2900 
2901   // Itanium C++ ABI 2.9.5p7:
2902   //  __pointee is a pointer to the std::type_info derivation for the
2903   //  unqualified type being pointed to.
2904   llvm::Constant *PointeeTypeInfo =
2905     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2906   Fields.push_back(PointeeTypeInfo);
2907 }
2908 
2909 /// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
2910 /// struct, used for member pointer types.
2911 void
2912 ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
2913   QualType PointeeTy = Ty->getPointeeType();
2914 
2915   Qualifiers Quals;
2916   QualType UnqualifiedPointeeTy =
2917     CGM.getContext().getUnqualifiedArrayType(PointeeTy, Quals);
2918 
2919   // Itanium C++ ABI 2.9.5p7:
2920   //   __flags is a flag word describing the cv-qualification and other
2921   //   attributes of the type pointed to.
2922   unsigned Flags = ComputeQualifierFlags(Quals);
2923 
2924   const RecordType *ClassType = cast<RecordType>(Ty->getClass());
2925 
2926   // Itanium C++ ABI 2.9.5p7:
2927   //   When the abi::__pbase_type_info is for a direct or indirect pointer to an
2928   //   incomplete class type, the incomplete target type flag is set.
2929   if (ContainsIncompleteClassType(UnqualifiedPointeeTy))
2930     Flags |= PTI_Incomplete;
2931 
2932   if (IsIncompleteClassType(ClassType))
2933     Flags |= PTI_ContainingClassIncomplete;
2934 
2935   llvm::Type *UnsignedIntLTy =
2936     CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
2937   Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
2938 
2939   // Itanium C++ ABI 2.9.5p7:
2940   //   __pointee is a pointer to the std::type_info derivation for the
2941   //   unqualified type being pointed to.
2942   llvm::Constant *PointeeTypeInfo =
2943     ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(UnqualifiedPointeeTy);
2944   Fields.push_back(PointeeTypeInfo);
2945 
2946   // Itanium C++ ABI 2.9.5p9:
2947   //   __context is a pointer to an abi::__class_type_info corresponding to the
2948   //   class type containing the member pointed to
2949   //   (e.g., the "A" in "int A::*").
2950   Fields.push_back(
2951       ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
2952 }
2953 
2954 llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
2955   return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
2956 }
2957 
2958 void ItaniumCXXABI::EmitFundamentalRTTIDescriptor(QualType Type) {
2959   QualType PointerType = getContext().getPointerType(Type);
2960   QualType PointerTypeConst = getContext().getPointerType(Type.withConst());
2961   ItaniumRTTIBuilder(*this).BuildTypeInfo(Type, true);
2962   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerType, true);
2963   ItaniumRTTIBuilder(*this).BuildTypeInfo(PointerTypeConst, true);
2964 }
2965 
2966 void ItaniumCXXABI::EmitFundamentalRTTIDescriptors() {
2967   QualType FundamentalTypes[] = {
2968       getContext().VoidTy,             getContext().NullPtrTy,
2969       getContext().BoolTy,             getContext().WCharTy,
2970       getContext().CharTy,             getContext().UnsignedCharTy,
2971       getContext().SignedCharTy,       getContext().ShortTy,
2972       getContext().UnsignedShortTy,    getContext().IntTy,
2973       getContext().UnsignedIntTy,      getContext().LongTy,
2974       getContext().UnsignedLongTy,     getContext().LongLongTy,
2975       getContext().UnsignedLongLongTy, getContext().HalfTy,
2976       getContext().FloatTy,            getContext().DoubleTy,
2977       getContext().LongDoubleTy,       getContext().Char16Ty,
2978       getContext().Char32Ty,
2979   };
2980   for (const QualType &FundamentalType : FundamentalTypes)
2981     EmitFundamentalRTTIDescriptor(FundamentalType);
2982 }
2983 
2984 /// What sort of uniqueness rules should we use for the RTTI for the
2985 /// given type?
2986 ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
2987     QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
2988   if (shouldRTTIBeUnique())
2989     return RUK_Unique;
2990 
2991   // It's only necessary for linkonce_odr or weak_odr linkage.
2992   if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
2993       Linkage != llvm::GlobalValue::WeakODRLinkage)
2994     return RUK_Unique;
2995 
2996   // It's only necessary with default visibility.
2997   if (CanTy->getVisibility() != DefaultVisibility)
2998     return RUK_Unique;
2999 
3000   // If we're not required to publish this symbol, hide it.
3001   if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
3002     return RUK_NonUniqueHidden;
3003 
3004   // If we're required to publish this symbol, as we might be under an
3005   // explicit instantiation, leave it with default visibility but
3006   // enable string-comparisons.
3007   assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
3008   return RUK_NonUniqueVisible;
3009 }
3010 
3011 // Find out how to codegen the complete destructor and constructor
3012 namespace {
3013 enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
3014 }
3015 static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
3016                                        const CXXMethodDecl *MD) {
3017   if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
3018     return StructorCodegen::Emit;
3019 
3020   // The complete and base structors are not equivalent if there are any virtual
3021   // bases, so emit separate functions.
3022   if (MD->getParent()->getNumVBases())
3023     return StructorCodegen::Emit;
3024 
3025   GlobalDecl AliasDecl;
3026   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
3027     AliasDecl = GlobalDecl(DD, Dtor_Complete);
3028   } else {
3029     const auto *CD = cast<CXXConstructorDecl>(MD);
3030     AliasDecl = GlobalDecl(CD, Ctor_Complete);
3031   }
3032   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3033 
3034   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
3035     return StructorCodegen::RAUW;
3036 
3037   // FIXME: Should we allow available_externally aliases?
3038   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
3039     return StructorCodegen::RAUW;
3040 
3041   if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
3042     // Only ELF supports COMDATs with arbitrary names (C5/D5).
3043     if (CGM.getTarget().getTriple().isOSBinFormatELF())
3044       return StructorCodegen::COMDAT;
3045     return StructorCodegen::Emit;
3046   }
3047 
3048   return StructorCodegen::Alias;
3049 }
3050 
3051 static void emitConstructorDestructorAlias(CodeGenModule &CGM,
3052                                            GlobalDecl AliasDecl,
3053                                            GlobalDecl TargetDecl) {
3054   llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
3055 
3056   StringRef MangledName = CGM.getMangledName(AliasDecl);
3057   llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
3058   if (Entry && !Entry->isDeclaration())
3059     return;
3060 
3061   auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
3062   llvm::PointerType *AliasType = Aliasee->getType();
3063 
3064   // Create the alias with no name.
3065   auto *Alias = llvm::GlobalAlias::create(
3066       AliasType->getElementType(), 0, Linkage, "", Aliasee, &CGM.getModule());
3067 
3068   // Switch any previous uses to the alias.
3069   if (Entry) {
3070     assert(Entry->getType() == AliasType &&
3071            "declaration exists with different type");
3072     Alias->takeName(Entry);
3073     Entry->replaceAllUsesWith(Alias);
3074     Entry->eraseFromParent();
3075   } else {
3076     Alias->setName(MangledName);
3077   }
3078 
3079   // Finally, set up the alias with its proper name and attributes.
3080   CGM.setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
3081 }
3082 
3083 void ItaniumCXXABI::emitCXXStructor(const CXXMethodDecl *MD,
3084                                     StructorType Type) {
3085   auto *CD = dyn_cast<CXXConstructorDecl>(MD);
3086   const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
3087 
3088   StructorCodegen CGType = getCodegenToUse(CGM, MD);
3089 
3090   if (Type == StructorType::Complete) {
3091     GlobalDecl CompleteDecl;
3092     GlobalDecl BaseDecl;
3093     if (CD) {
3094       CompleteDecl = GlobalDecl(CD, Ctor_Complete);
3095       BaseDecl = GlobalDecl(CD, Ctor_Base);
3096     } else {
3097       CompleteDecl = GlobalDecl(DD, Dtor_Complete);
3098       BaseDecl = GlobalDecl(DD, Dtor_Base);
3099     }
3100 
3101     if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
3102       emitConstructorDestructorAlias(CGM, CompleteDecl, BaseDecl);
3103       return;
3104     }
3105 
3106     if (CGType == StructorCodegen::RAUW) {
3107       StringRef MangledName = CGM.getMangledName(CompleteDecl);
3108       auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(BaseDecl));
3109       CGM.addReplacement(MangledName, Aliasee);
3110       return;
3111     }
3112   }
3113 
3114   // The base destructor is equivalent to the base destructor of its
3115   // base class if there is exactly one non-virtual base class with a
3116   // non-trivial destructor, there are no fields with a non-trivial
3117   // destructor, and the body of the destructor is trivial.
3118   if (DD && Type == StructorType::Base && CGType != StructorCodegen::COMDAT &&
3119       !CGM.TryEmitBaseDestructorAsAlias(DD))
3120     return;
3121 
3122   llvm::Function *Fn = CGM.codegenCXXStructor(MD, Type);
3123 
3124   if (CGType == StructorCodegen::COMDAT) {
3125     SmallString<256> Buffer;
3126     llvm::raw_svector_ostream Out(Buffer);
3127     if (DD)
3128       getMangleContext().mangleCXXDtorComdat(DD, Out);
3129     else
3130       getMangleContext().mangleCXXCtorComdat(CD, Out);
3131     llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
3132     Fn->setComdat(C);
3133   }
3134 }
3135