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   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
113   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
114   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
115                           llvm::Value *ThisPtr,
116                           llvm::Type *StdTypeInfoPtrTy) override;
117 
118   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
119                                           QualType SrcRecordTy) override;
120 
121   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
122                                    QualType SrcRecordTy, QualType DestTy,
123                                    QualType DestRecordTy,
124                                    llvm::BasicBlock *CastEnd) override;
125 
126   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, llvm::Value *Value,
127                                      QualType SrcRecordTy,
128                                      QualType DestTy) override;
129 
130   bool EmitBadCastCall(CodeGenFunction &CGF) override;
131 
132   llvm::Value *
133     GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
134                               const CXXRecordDecl *ClassDecl,
135                               const CXXRecordDecl *BaseClassDecl) override;
136 
137   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
138                                  CXXCtorType T, CanQualType &ResTy,
139                                  SmallVectorImpl<CanQualType> &ArgTys) override;
140 
141   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
142 
143   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
144                                 CXXDtorType T, CanQualType &ResTy,
145                                 SmallVectorImpl<CanQualType> &ArgTys) override;
146 
147   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
148                               CXXDtorType DT) const override {
149     // Itanium does not emit any destructor variant as an inline thunk.
150     // Delegating may occur as an optimization, but all variants are either
151     // emitted with external linkage or as linkonce if they are inline and used.
152     return false;
153   }
154 
155   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
156 
157   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
158                                  FunctionArgList &Params) override;
159 
160   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
161 
162   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
163                                       const CXXConstructorDecl *D,
164                                       CXXCtorType Type, bool ForVirtualBase,
165                                       bool Delegating,
166                                       CallArgList &Args) override;
167 
168   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
169                           CXXDtorType Type, bool ForVirtualBase,
170                           bool Delegating, llvm::Value *This) override;
171 
172   void emitVTableDefinitions(CodeGenVTables &CGVT,
173                              const CXXRecordDecl *RD) override;
174 
175   llvm::Value *getVTableAddressPointInStructor(
176       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
177       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
178       bool &NeedsVirtualOffset) override;
179 
180   llvm::Constant *
181   getVTableAddressPointForConstExpr(BaseSubobject Base,
182                                     const CXXRecordDecl *VTableClass) override;
183 
184   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
185                                         CharUnits VPtrOffset) override;
186 
187   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
188                                          llvm::Value *This,
189                                          llvm::Type *Ty) override;
190 
191   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
192                                  const CXXDestructorDecl *Dtor,
193                                  CXXDtorType DtorType, SourceLocation CallLoc,
194                                  llvm::Value *This) override;
195 
196   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
197 
198   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
199                        bool ReturnAdjustment) override {
200     // Allow inlining of thunks by emitting them with available_externally
201     // linkage together with vtables when needed.
202     if (ForVTable)
203       Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
204   }
205 
206   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
207                                      const ThisAdjustment &TA) override;
208 
209   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
210                                        const ReturnAdjustment &RA) override;
211 
212   StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
213   StringRef GetDeletedVirtualCallName() override
214     { return "__cxa_deleted_virtual"; }
215 
216   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
217   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
218                                      llvm::Value *NewPtr,
219                                      llvm::Value *NumElements,
220                                      const CXXNewExpr *expr,
221                                      QualType ElementType) override;
222   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
223                                    llvm::Value *allocPtr,
224                                    CharUnits cookieSize) override;
225 
226   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
227                        llvm::GlobalVariable *DeclPtr,
228                        bool PerformInit) override;
229   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
230                           llvm::Constant *dtor, llvm::Constant *addr) override;
231 
232   llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
233                                                 llvm::GlobalVariable *Var);
234   void EmitThreadLocalInitFuncs(
235       llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
236       llvm::Function *InitFunc) override;
237   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
238                                       QualType LValType) override;
239 
240   bool NeedsVTTParameter(GlobalDecl GD) override;
241 };
242 
243 class ARMCXXABI : public ItaniumCXXABI {
244 public:
245   ARMCXXABI(CodeGen::CodeGenModule &CGM) :
246     ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
247                   /* UseARMGuardVarABI = */ true) {}
248 
249   bool HasThisReturn(GlobalDecl GD) const override {
250     return (isa<CXXConstructorDecl>(GD.getDecl()) || (
251               isa<CXXDestructorDecl>(GD.getDecl()) &&
252               GD.getDtorType() != Dtor_Deleting));
253   }
254 
255   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
256                            QualType ResTy) override;
257 
258   CharUnits getArrayCookieSizeImpl(QualType elementType) override;
259   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
260                                      llvm::Value *NewPtr,
261                                      llvm::Value *NumElements,
262                                      const CXXNewExpr *expr,
263                                      QualType ElementType) override;
264   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
265                                    CharUnits cookieSize) override;
266 };
267 
268 class iOS64CXXABI : public ARMCXXABI {
269 public:
270   iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {}
271 
272   // ARM64 libraries are prepared for non-unique RTTI.
273   bool shouldRTTIBeUnique() override { return false; }
274 };
275 }
276 
277 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
278   switch (CGM.getTarget().getCXXABI().getKind()) {
279   // For IR-generation purposes, there's no significant difference
280   // between the ARM and iOS ABIs.
281   case TargetCXXABI::GenericARM:
282   case TargetCXXABI::iOS:
283     return new ARMCXXABI(CGM);
284 
285   case TargetCXXABI::iOS64:
286     return new iOS64CXXABI(CGM);
287 
288   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
289   // include the other 32-bit ARM oddities: constructor/destructor return values
290   // and array cookies.
291   case TargetCXXABI::GenericAArch64:
292     return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
293                              /* UseARMGuardVarABI = */ true);
294 
295   case TargetCXXABI::GenericItanium:
296     if (CGM.getContext().getTargetInfo().getTriple().getArch()
297         == llvm::Triple::le32) {
298       // For PNaCl, use ARM-style method pointers so that PNaCl code
299       // does not assume anything about the alignment of function
300       // pointers.
301       return new ItaniumCXXABI(CGM, /* UseARMMethodPtrABI = */ true,
302                                /* UseARMGuardVarABI = */ false);
303     }
304     return new ItaniumCXXABI(CGM);
305 
306   case TargetCXXABI::Microsoft:
307     llvm_unreachable("Microsoft ABI is not Itanium-based");
308   }
309   llvm_unreachable("bad ABI kind");
310 }
311 
312 llvm::Type *
313 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
314   if (MPT->isMemberDataPointer())
315     return CGM.PtrDiffTy;
316   return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy, NULL);
317 }
318 
319 /// In the Itanium and ARM ABIs, method pointers have the form:
320 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
321 ///
322 /// In the Itanium ABI:
323 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
324 ///  - the this-adjustment is (memptr.adj)
325 ///  - the virtual offset is (memptr.ptr - 1)
326 ///
327 /// In the ARM ABI:
328 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
329 ///  - the this-adjustment is (memptr.adj >> 1)
330 ///  - the virtual offset is (memptr.ptr)
331 /// ARM uses 'adj' for the virtual flag because Thumb functions
332 /// may be only single-byte aligned.
333 ///
334 /// If the member is virtual, the adjusted 'this' pointer points
335 /// to a vtable pointer from which the virtual offset is applied.
336 ///
337 /// If the member is non-virtual, memptr.ptr is the address of
338 /// the function to call.
339 llvm::Value *ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
340     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
341     llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
342   CGBuilderTy &Builder = CGF.Builder;
343 
344   const FunctionProtoType *FPT =
345     MPT->getPointeeType()->getAs<FunctionProtoType>();
346   const CXXRecordDecl *RD =
347     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
348 
349   llvm::FunctionType *FTy =
350     CGM.getTypes().GetFunctionType(
351       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
352 
353   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
354 
355   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
356   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
357   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
358 
359   // Extract memptr.adj, which is in the second field.
360   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
361 
362   // Compute the true adjustment.
363   llvm::Value *Adj = RawAdj;
364   if (UseARMMethodPtrABI)
365     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
366 
367   // Apply the adjustment and cast back to the original struct type
368   // for consistency.
369   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
370   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
371   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
372 
373   // Load the function pointer.
374   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
375 
376   // If the LSB in the function pointer is 1, the function pointer points to
377   // a virtual function.
378   llvm::Value *IsVirtual;
379   if (UseARMMethodPtrABI)
380     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
381   else
382     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
383   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
384   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
385 
386   // In the virtual path, the adjustment left 'This' pointing to the
387   // vtable of the correct base subobject.  The "function pointer" is an
388   // offset within the vtable (+1 for the virtual flag on non-ARM).
389   CGF.EmitBlock(FnVirtual);
390 
391   // Cast the adjusted this to a pointer to vtable pointer and load.
392   llvm::Type *VTableTy = Builder.getInt8PtrTy();
393   llvm::Value *VTable = CGF.GetVTablePtr(This, VTableTy);
394 
395   // Apply the offset.
396   llvm::Value *VTableOffset = FnAsInt;
397   if (!UseARMMethodPtrABI)
398     VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
399   VTable = Builder.CreateGEP(VTable, VTableOffset);
400 
401   // Load the virtual function to call.
402   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
403   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
404   CGF.EmitBranch(FnEnd);
405 
406   // In the non-virtual path, the function pointer is actually a
407   // function pointer.
408   CGF.EmitBlock(FnNonVirtual);
409   llvm::Value *NonVirtualFn =
410     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
411 
412   // We're done.
413   CGF.EmitBlock(FnEnd);
414   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
415   Callee->addIncoming(VirtualFn, FnVirtual);
416   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
417   return Callee;
418 }
419 
420 /// Compute an l-value by applying the given pointer-to-member to a
421 /// base object.
422 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
423     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
424     const MemberPointerType *MPT) {
425   assert(MemPtr->getType() == CGM.PtrDiffTy);
426 
427   CGBuilderTy &Builder = CGF.Builder;
428 
429   unsigned AS = Base->getType()->getPointerAddressSpace();
430 
431   // Cast to char*.
432   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
433 
434   // Apply the offset, which we assume is non-null.
435   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
436 
437   // Cast the address to the appropriate pointer type, adopting the
438   // address space of the base pointer.
439   llvm::Type *PType
440     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
441   return Builder.CreateBitCast(Addr, PType);
442 }
443 
444 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
445 /// conversion.
446 ///
447 /// Bitcast conversions are always a no-op under Itanium.
448 ///
449 /// Obligatory offset/adjustment diagram:
450 ///         <-- offset -->          <-- adjustment -->
451 ///   |--------------------------|----------------------|--------------------|
452 ///   ^Derived address point     ^Base address point    ^Member address point
453 ///
454 /// So when converting a base member pointer to a derived member pointer,
455 /// we add the offset to the adjustment because the address point has
456 /// decreased;  and conversely, when converting a derived MP to a base MP
457 /// we subtract the offset from the adjustment because the address point
458 /// has increased.
459 ///
460 /// The standard forbids (at compile time) conversion to and from
461 /// virtual bases, which is why we don't have to consider them here.
462 ///
463 /// The standard forbids (at run time) casting a derived MP to a base
464 /// MP when the derived MP does not point to a member of the base.
465 /// This is why -1 is a reasonable choice for null data member
466 /// pointers.
467 llvm::Value *
468 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
469                                            const CastExpr *E,
470                                            llvm::Value *src) {
471   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
472          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
473          E->getCastKind() == CK_ReinterpretMemberPointer);
474 
475   // Under Itanium, reinterprets don't require any additional processing.
476   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
477 
478   // Use constant emission if we can.
479   if (isa<llvm::Constant>(src))
480     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
481 
482   llvm::Constant *adj = getMemberPointerAdjustment(E);
483   if (!adj) return src;
484 
485   CGBuilderTy &Builder = CGF.Builder;
486   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
487 
488   const MemberPointerType *destTy =
489     E->getType()->castAs<MemberPointerType>();
490 
491   // For member data pointers, this is just a matter of adding the
492   // offset if the source is non-null.
493   if (destTy->isMemberDataPointer()) {
494     llvm::Value *dst;
495     if (isDerivedToBase)
496       dst = Builder.CreateNSWSub(src, adj, "adj");
497     else
498       dst = Builder.CreateNSWAdd(src, adj, "adj");
499 
500     // Null check.
501     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
502     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
503     return Builder.CreateSelect(isNull, src, dst);
504   }
505 
506   // The this-adjustment is left-shifted by 1 on ARM.
507   if (UseARMMethodPtrABI) {
508     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
509     offset <<= 1;
510     adj = llvm::ConstantInt::get(adj->getType(), offset);
511   }
512 
513   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
514   llvm::Value *dstAdj;
515   if (isDerivedToBase)
516     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
517   else
518     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
519 
520   return Builder.CreateInsertValue(src, dstAdj, 1);
521 }
522 
523 llvm::Constant *
524 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
525                                            llvm::Constant *src) {
526   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
527          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
528          E->getCastKind() == CK_ReinterpretMemberPointer);
529 
530   // Under Itanium, reinterprets don't require any additional processing.
531   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
532 
533   // If the adjustment is trivial, we don't need to do anything.
534   llvm::Constant *adj = getMemberPointerAdjustment(E);
535   if (!adj) return src;
536 
537   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
538 
539   const MemberPointerType *destTy =
540     E->getType()->castAs<MemberPointerType>();
541 
542   // For member data pointers, this is just a matter of adding the
543   // offset if the source is non-null.
544   if (destTy->isMemberDataPointer()) {
545     // null maps to null.
546     if (src->isAllOnesValue()) return src;
547 
548     if (isDerivedToBase)
549       return llvm::ConstantExpr::getNSWSub(src, adj);
550     else
551       return llvm::ConstantExpr::getNSWAdd(src, adj);
552   }
553 
554   // The this-adjustment is left-shifted by 1 on ARM.
555   if (UseARMMethodPtrABI) {
556     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
557     offset <<= 1;
558     adj = llvm::ConstantInt::get(adj->getType(), offset);
559   }
560 
561   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
562   llvm::Constant *dstAdj;
563   if (isDerivedToBase)
564     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
565   else
566     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
567 
568   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
569 }
570 
571 llvm::Constant *
572 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
573   // Itanium C++ ABI 2.3:
574   //   A NULL pointer is represented as -1.
575   if (MPT->isMemberDataPointer())
576     return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
577 
578   llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
579   llvm::Constant *Values[2] = { Zero, Zero };
580   return llvm::ConstantStruct::getAnon(Values);
581 }
582 
583 llvm::Constant *
584 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
585                                      CharUnits offset) {
586   // Itanium C++ ABI 2.3:
587   //   A pointer to data member is an offset from the base address of
588   //   the class object containing it, represented as a ptrdiff_t
589   return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
590 }
591 
592 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
593   return BuildMemberPointer(MD, CharUnits::Zero());
594 }
595 
596 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
597                                                   CharUnits ThisAdjustment) {
598   assert(MD->isInstance() && "Member function must not be static!");
599   MD = MD->getCanonicalDecl();
600 
601   CodeGenTypes &Types = CGM.getTypes();
602 
603   // Get the function pointer (or index if this is a virtual function).
604   llvm::Constant *MemPtr[2];
605   if (MD->isVirtual()) {
606     uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
607 
608     const ASTContext &Context = getContext();
609     CharUnits PointerWidth =
610       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
611     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
612 
613     if (UseARMMethodPtrABI) {
614       // ARM C++ ABI 3.2.1:
615       //   This ABI specifies that adj contains twice the this
616       //   adjustment, plus 1 if the member function is virtual. The
617       //   least significant bit of adj then makes exactly the same
618       //   discrimination as the least significant bit of ptr does for
619       //   Itanium.
620       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
621       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
622                                          2 * ThisAdjustment.getQuantity() + 1);
623     } else {
624       // Itanium C++ ABI 2.3:
625       //   For a virtual function, [the pointer field] is 1 plus the
626       //   virtual table offset (in bytes) of the function,
627       //   represented as a ptrdiff_t.
628       MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
629       MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
630                                          ThisAdjustment.getQuantity());
631     }
632   } else {
633     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
634     llvm::Type *Ty;
635     // Check whether the function has a computable LLVM signature.
636     if (Types.isFuncTypeConvertible(FPT)) {
637       // The function has a computable LLVM signature; use the correct type.
638       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
639     } else {
640       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
641       // function type is incomplete.
642       Ty = CGM.PtrDiffTy;
643     }
644     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
645 
646     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
647     MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
648                                        (UseARMMethodPtrABI ? 2 : 1) *
649                                        ThisAdjustment.getQuantity());
650   }
651 
652   return llvm::ConstantStruct::getAnon(MemPtr);
653 }
654 
655 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
656                                                  QualType MPType) {
657   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
658   const ValueDecl *MPD = MP.getMemberPointerDecl();
659   if (!MPD)
660     return EmitNullMemberPointer(MPT);
661 
662   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
663 
664   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
665     return BuildMemberPointer(MD, ThisAdjustment);
666 
667   CharUnits FieldOffset =
668     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
669   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
670 }
671 
672 /// The comparison algorithm is pretty easy: the member pointers are
673 /// the same if they're either bitwise identical *or* both null.
674 ///
675 /// ARM is different here only because null-ness is more complicated.
676 llvm::Value *
677 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
678                                            llvm::Value *L,
679                                            llvm::Value *R,
680                                            const MemberPointerType *MPT,
681                                            bool Inequality) {
682   CGBuilderTy &Builder = CGF.Builder;
683 
684   llvm::ICmpInst::Predicate Eq;
685   llvm::Instruction::BinaryOps And, Or;
686   if (Inequality) {
687     Eq = llvm::ICmpInst::ICMP_NE;
688     And = llvm::Instruction::Or;
689     Or = llvm::Instruction::And;
690   } else {
691     Eq = llvm::ICmpInst::ICMP_EQ;
692     And = llvm::Instruction::And;
693     Or = llvm::Instruction::Or;
694   }
695 
696   // Member data pointers are easy because there's a unique null
697   // value, so it just comes down to bitwise equality.
698   if (MPT->isMemberDataPointer())
699     return Builder.CreateICmp(Eq, L, R);
700 
701   // For member function pointers, the tautologies are more complex.
702   // The Itanium tautology is:
703   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
704   // The ARM tautology is:
705   //   (L == R) <==> (L.ptr == R.ptr &&
706   //                  (L.adj == R.adj ||
707   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
708   // The inequality tautologies have exactly the same structure, except
709   // applying De Morgan's laws.
710 
711   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
712   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
713 
714   // This condition tests whether L.ptr == R.ptr.  This must always be
715   // true for equality to hold.
716   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
717 
718   // This condition, together with the assumption that L.ptr == R.ptr,
719   // tests whether the pointers are both null.  ARM imposes an extra
720   // condition.
721   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
722   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
723 
724   // This condition tests whether L.adj == R.adj.  If this isn't
725   // true, the pointers are unequal unless they're both null.
726   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
727   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
728   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
729 
730   // Null member function pointers on ARM clear the low bit of Adj,
731   // so the zero condition has to check that neither low bit is set.
732   if (UseARMMethodPtrABI) {
733     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
734 
735     // Compute (l.adj | r.adj) & 1 and test it against zero.
736     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
737     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
738     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
739                                                       "cmp.or.adj");
740     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
741   }
742 
743   // Tie together all our conditions.
744   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
745   Result = Builder.CreateBinOp(And, PtrEq, Result,
746                                Inequality ? "memptr.ne" : "memptr.eq");
747   return Result;
748 }
749 
750 llvm::Value *
751 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
752                                           llvm::Value *MemPtr,
753                                           const MemberPointerType *MPT) {
754   CGBuilderTy &Builder = CGF.Builder;
755 
756   /// For member data pointers, this is just a check against -1.
757   if (MPT->isMemberDataPointer()) {
758     assert(MemPtr->getType() == CGM.PtrDiffTy);
759     llvm::Value *NegativeOne =
760       llvm::Constant::getAllOnesValue(MemPtr->getType());
761     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
762   }
763 
764   // In Itanium, a member function pointer is not null if 'ptr' is not null.
765   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
766 
767   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
768   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
769 
770   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
771   // (the virtual bit) is set.
772   if (UseARMMethodPtrABI) {
773     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
774     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
775     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
776     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
777                                                   "memptr.isvirtual");
778     Result = Builder.CreateOr(Result, IsVirtual);
779   }
780 
781   return Result;
782 }
783 
784 bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
785   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
786   if (!RD)
787     return false;
788 
789   // Return indirectly if we have a non-trivial copy ctor or non-trivial dtor.
790   // FIXME: Use canCopyArgument() when it is fixed to handle lazily declared
791   // special members.
792   if (RD->hasNonTrivialDestructor() || RD->hasNonTrivialCopyConstructor()) {
793     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
794     return true;
795   }
796   return false;
797 }
798 
799 /// The Itanium ABI requires non-zero initialization only for data
800 /// member pointers, for which '0' is a valid offset.
801 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
802   return MPT->getPointeeType()->isFunctionType();
803 }
804 
805 /// The Itanium ABI always places an offset to the complete object
806 /// at entry -2 in the vtable.
807 llvm::Value *ItaniumCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
808                                                    llvm::Value *ptr,
809                                                    QualType type) {
810   // Grab the vtable pointer as an intptr_t*.
811   llvm::Value *vtable = CGF.GetVTablePtr(ptr, CGF.IntPtrTy->getPointerTo());
812 
813   // Track back to entry -2 and pull out the offset there.
814   llvm::Value *offsetPtr =
815     CGF.Builder.CreateConstInBoundsGEP1_64(vtable, -2, "complete-offset.ptr");
816   llvm::LoadInst *offset = CGF.Builder.CreateLoad(offsetPtr);
817   offset->setAlignment(CGF.PointerAlignInBytes);
818 
819   // Apply the offset.
820   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
821   return CGF.Builder.CreateInBoundsGEP(ptr, offset);
822 }
823 
824 static llvm::Constant *getItaniumDynamicCastFn(CodeGenFunction &CGF) {
825   // void *__dynamic_cast(const void *sub,
826   //                      const abi::__class_type_info *src,
827   //                      const abi::__class_type_info *dst,
828   //                      std::ptrdiff_t src2dst_offset);
829 
830   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
831   llvm::Type *PtrDiffTy =
832     CGF.ConvertType(CGF.getContext().getPointerDiffType());
833 
834   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
835 
836   llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
837 
838   // Mark the function as nounwind readonly.
839   llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
840                                             llvm::Attribute::ReadOnly };
841   llvm::AttributeSet Attrs = llvm::AttributeSet::get(
842       CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
843 
844   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
845 }
846 
847 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
848   // void __cxa_bad_cast();
849   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
850   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
851 }
852 
853 /// \brief Compute the src2dst_offset hint as described in the
854 /// Itanium C++ ABI [2.9.7]
855 static CharUnits computeOffsetHint(ASTContext &Context,
856                                    const CXXRecordDecl *Src,
857                                    const CXXRecordDecl *Dst) {
858   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
859                      /*DetectVirtual=*/false);
860 
861   // If Dst is not derived from Src we can skip the whole computation below and
862   // return that Src is not a public base of Dst.  Record all inheritance paths.
863   if (!Dst->isDerivedFrom(Src, Paths))
864     return CharUnits::fromQuantity(-2ULL);
865 
866   unsigned NumPublicPaths = 0;
867   CharUnits Offset;
868 
869   // Now walk all possible inheritance paths.
870   for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end(); I != E;
871        ++I) {
872     if (I->Access != AS_public) // Ignore non-public inheritance.
873       continue;
874 
875     ++NumPublicPaths;
876 
877     for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
878       // If the path contains a virtual base class we can't give any hint.
879       // -1: no hint.
880       if (J->Base->isVirtual())
881         return CharUnits::fromQuantity(-1ULL);
882 
883       if (NumPublicPaths > 1) // Won't use offsets, skip computation.
884         continue;
885 
886       // Accumulate the base class offsets.
887       const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
888       Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
889     }
890   }
891 
892   // -2: Src is not a public base of Dst.
893   if (NumPublicPaths == 0)
894     return CharUnits::fromQuantity(-2ULL);
895 
896   // -3: Src is a multiple public base type but never a virtual base type.
897   if (NumPublicPaths > 1)
898     return CharUnits::fromQuantity(-3ULL);
899 
900   // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
901   // Return the offset of Src from the origin of Dst.
902   return Offset;
903 }
904 
905 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
906   // void __cxa_bad_typeid();
907   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
908 
909   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
910 }
911 
912 bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
913                                               QualType SrcRecordTy) {
914   return IsDeref;
915 }
916 
917 void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
918   llvm::Value *Fn = getBadTypeidFn(CGF);
919   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
920   CGF.Builder.CreateUnreachable();
921 }
922 
923 llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
924                                        QualType SrcRecordTy,
925                                        llvm::Value *ThisPtr,
926                                        llvm::Type *StdTypeInfoPtrTy) {
927   llvm::Value *Value =
928       CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo());
929 
930   // Load the type info.
931   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
932   return CGF.Builder.CreateLoad(Value);
933 }
934 
935 bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
936                                                        QualType SrcRecordTy) {
937   return SrcIsPtr;
938 }
939 
940 llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
941     CodeGenFunction &CGF, llvm::Value *Value, QualType SrcRecordTy,
942     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
943   llvm::Type *PtrDiffLTy =
944       CGF.ConvertType(CGF.getContext().getPointerDiffType());
945   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
946 
947   llvm::Value *SrcRTTI =
948       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
949   llvm::Value *DestRTTI =
950       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
951 
952   // Compute the offset hint.
953   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
954   const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
955   llvm::Value *OffsetHint = llvm::ConstantInt::get(
956       PtrDiffLTy,
957       computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
958 
959   // Emit the call to __dynamic_cast.
960   Value = CGF.EmitCastToVoidPtr(Value);
961 
962   llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
963   Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
964   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
965 
966   /// C++ [expr.dynamic.cast]p9:
967   ///   A failed cast to reference type throws std::bad_cast
968   if (DestTy->isReferenceType()) {
969     llvm::BasicBlock *BadCastBlock =
970         CGF.createBasicBlock("dynamic_cast.bad_cast");
971 
972     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
973     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
974 
975     CGF.EmitBlock(BadCastBlock);
976     EmitBadCastCall(CGF);
977   }
978 
979   return Value;
980 }
981 
982 llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
983                                                   llvm::Value *Value,
984                                                   QualType SrcRecordTy,
985                                                   QualType DestTy) {
986   llvm::Type *PtrDiffLTy =
987       CGF.ConvertType(CGF.getContext().getPointerDiffType());
988   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
989 
990   // Get the vtable pointer.
991   llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
992 
993   // Get the offset-to-top from the vtable.
994   llvm::Value *OffsetToTop =
995       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
996   OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
997 
998   // Finally, add the offset to the pointer.
999   Value = CGF.EmitCastToVoidPtr(Value);
1000   Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1001 
1002   return CGF.Builder.CreateBitCast(Value, DestLTy);
1003 }
1004 
1005 bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1006   llvm::Value *Fn = getBadCastFn(CGF);
1007   CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
1008   CGF.Builder.CreateUnreachable();
1009   return true;
1010 }
1011 
1012 llvm::Value *
1013 ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
1014                                          llvm::Value *This,
1015                                          const CXXRecordDecl *ClassDecl,
1016                                          const CXXRecordDecl *BaseClassDecl) {
1017   llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy);
1018   CharUnits VBaseOffsetOffset =
1019       CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
1020                                                                BaseClassDecl);
1021 
1022   llvm::Value *VBaseOffsetPtr =
1023     CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1024                                    "vbase.offset.ptr");
1025   VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
1026                                              CGM.PtrDiffTy->getPointerTo());
1027 
1028   llvm::Value *VBaseOffset =
1029     CGF.Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1030 
1031   return VBaseOffset;
1032 }
1033 
1034 /// The generic ABI passes 'this', plus a VTT if it's initializing a
1035 /// base subobject.
1036 void
1037 ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
1038                                          CXXCtorType Type, CanQualType &ResTy,
1039                                          SmallVectorImpl<CanQualType> &ArgTys) {
1040   ASTContext &Context = getContext();
1041 
1042   // All parameters are already in place except VTT, which goes after 'this'.
1043   // These are Clang types, so we don't need to worry about sret yet.
1044 
1045   // Check if we need to add a VTT parameter (which has type void **).
1046   if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
1047     ArgTys.insert(ArgTys.begin() + 1,
1048                   Context.getPointerType(Context.VoidPtrTy));
1049 }
1050 
1051 void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1052   // Just make sure we're in sync with TargetCXXABI.
1053   assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
1054 
1055   // The constructor used for constructing this as a base class;
1056   // ignores virtual bases.
1057   CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
1058 
1059   // The constructor used for constructing this as a complete class;
1060   // constucts the virtual bases, then calls the base constructor.
1061   if (!D->getParent()->isAbstract()) {
1062     // We don't need to emit the complete ctor if the class is abstract.
1063     CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1064   }
1065 }
1066 
1067 /// The generic ABI passes 'this', plus a VTT if it's destroying a
1068 /// base subobject.
1069 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
1070                                              CXXDtorType Type,
1071                                              CanQualType &ResTy,
1072                                 SmallVectorImpl<CanQualType> &ArgTys) {
1073   ASTContext &Context = getContext();
1074 
1075   // 'this' parameter is already there, as well as 'this' return if
1076   // HasThisReturn(GlobalDecl(Dtor, Type)) is true
1077 
1078   // Check if we need to add a VTT parameter (which has type void **).
1079   if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
1080     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
1081 }
1082 
1083 void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1084   // The destructor used for destructing this as a base class; ignores
1085   // virtual bases.
1086   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1087 
1088   // The destructor used for destructing this as a most-derived class;
1089   // call the base destructor and then destructs any virtual bases.
1090   CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1091 
1092   // The destructor in a virtual table is always a 'deleting'
1093   // destructor, which calls the complete destructor and then uses the
1094   // appropriate operator delete.
1095   if (D->isVirtual())
1096     CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
1097 }
1098 
1099 void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1100                                               QualType &ResTy,
1101                                               FunctionArgList &Params) {
1102   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1103   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1104 
1105   // Check if we need a VTT parameter as well.
1106   if (NeedsVTTParameter(CGF.CurGD)) {
1107     ASTContext &Context = getContext();
1108 
1109     // FIXME: avoid the fake decl
1110     QualType T = Context.getPointerType(Context.VoidPtrTy);
1111     ImplicitParamDecl *VTTDecl
1112       = ImplicitParamDecl::Create(Context, nullptr, MD->getLocation(),
1113                                   &Context.Idents.get("vtt"), T);
1114     Params.insert(Params.begin() + 1, VTTDecl);
1115     getStructorImplicitParamDecl(CGF) = VTTDecl;
1116   }
1117 }
1118 
1119 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1120   /// Initialize the 'this' slot.
1121   EmitThisParam(CGF);
1122 
1123   /// Initialize the 'vtt' slot if needed.
1124   if (getStructorImplicitParamDecl(CGF)) {
1125     getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
1126         CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
1127   }
1128 
1129   /// If this is a function that the ABI specifies returns 'this', initialize
1130   /// the return slot to 'this' at the start of the function.
1131   ///
1132   /// Unlike the setting of return types, this is done within the ABI
1133   /// implementation instead of by clients of CGCXXABI because:
1134   /// 1) getThisValue is currently protected
1135   /// 2) in theory, an ABI could implement 'this' returns some other way;
1136   ///    HasThisReturn only specifies a contract, not the implementation
1137   if (HasThisReturn(CGF.CurGD))
1138     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1139 }
1140 
1141 unsigned ItaniumCXXABI::addImplicitConstructorArgs(
1142     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1143     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
1144   if (!NeedsVTTParameter(GlobalDecl(D, Type)))
1145     return 0;
1146 
1147   // Insert the implicit 'vtt' argument as the second argument.
1148   llvm::Value *VTT =
1149       CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
1150   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1151   Args.insert(Args.begin() + 1,
1152               CallArg(RValue::get(VTT), VTTTy, /*needscopy=*/false));
1153   return 1;  // Added one arg.
1154 }
1155 
1156 void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1157                                        const CXXDestructorDecl *DD,
1158                                        CXXDtorType Type, bool ForVirtualBase,
1159                                        bool Delegating, llvm::Value *This) {
1160   GlobalDecl GD(DD, Type);
1161   llvm::Value *VTT = CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
1162   QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
1163 
1164   llvm::Value *Callee = nullptr;
1165   if (getContext().getLangOpts().AppleKext)
1166     Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
1167 
1168   if (!Callee)
1169     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1170 
1171   // FIXME: Provide a source location here.
1172   CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1173                         VTT, VTTTy, nullptr, nullptr);
1174 }
1175 
1176 void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1177                                           const CXXRecordDecl *RD) {
1178   llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
1179   if (VTable->hasInitializer())
1180     return;
1181 
1182   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1183   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
1184   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1185 
1186   // Create and set the initializer.
1187   llvm::Constant *Init = CGVT.CreateVTableInitializer(
1188       RD, VTLayout.vtable_component_begin(), VTLayout.getNumVTableComponents(),
1189       VTLayout.vtable_thunk_begin(), VTLayout.getNumVTableThunks());
1190   VTable->setInitializer(Init);
1191 
1192   // Set the correct linkage.
1193   VTable->setLinkage(Linkage);
1194 
1195   // Set the right visibility.
1196   CGM.setGlobalVisibility(VTable, RD);
1197 
1198   // If this is the magic class __cxxabiv1::__fundamental_type_info,
1199   // we will emit the typeinfo for the fundamental types. This is the
1200   // same behaviour as GCC.
1201   const DeclContext *DC = RD->getDeclContext();
1202   if (RD->getIdentifier() &&
1203       RD->getIdentifier()->isStr("__fundamental_type_info") &&
1204       isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
1205       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
1206       DC->getParent()->isTranslationUnit())
1207     CGM.EmitFundamentalRTTIDescriptors();
1208 }
1209 
1210 llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
1211     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1212     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
1213   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CGF.CurGD);
1214   NeedsVirtualOffset = (NeedsVTTParam && NearestVBase);
1215 
1216   llvm::Value *VTableAddressPoint;
1217   if (NeedsVTTParam && (Base.getBase()->getNumVBases() || NearestVBase)) {
1218     // Get the secondary vpointer index.
1219     uint64_t VirtualPointerIndex =
1220         CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1221 
1222     /// Load the VTT.
1223     llvm::Value *VTT = CGF.LoadCXXVTT();
1224     if (VirtualPointerIndex)
1225       VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1226 
1227     // And load the address point from the VTT.
1228     VTableAddressPoint = CGF.Builder.CreateLoad(VTT);
1229   } else {
1230     llvm::Constant *VTable =
1231         CGM.getCXXABI().getAddrOfVTable(VTableClass, CharUnits());
1232     uint64_t AddressPoint = CGM.getItaniumVTableContext()
1233                                 .getVTableLayout(VTableClass)
1234                                 .getAddressPoint(Base);
1235     VTableAddressPoint =
1236         CGF.Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1237   }
1238 
1239   return VTableAddressPoint;
1240 }
1241 
1242 llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
1243     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1244   llvm::Constant *VTable = getAddrOfVTable(VTableClass, CharUnits());
1245 
1246   // Find the appropriate vtable within the vtable group.
1247   uint64_t AddressPoint = CGM.getItaniumVTableContext()
1248                               .getVTableLayout(VTableClass)
1249                               .getAddressPoint(Base);
1250   llvm::Value *Indices[] = {
1251     llvm::ConstantInt::get(CGM.Int64Ty, 0),
1252     llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
1253   };
1254 
1255   return llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
1256 }
1257 
1258 llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1259                                                      CharUnits VPtrOffset) {
1260   assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
1261 
1262   llvm::GlobalVariable *&VTable = VTables[RD];
1263   if (VTable)
1264     return VTable;
1265 
1266   // Queue up this v-table for possible deferred emission.
1267   CGM.addDeferredVTable(RD);
1268 
1269   SmallString<256> OutName;
1270   llvm::raw_svector_ostream Out(OutName);
1271   getMangleContext().mangleCXXVTable(RD, Out);
1272   Out.flush();
1273   StringRef Name = OutName.str();
1274 
1275   ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
1276   llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1277       CGM.Int8PtrTy, VTContext.getVTableLayout(RD).getNumVTableComponents());
1278 
1279   VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1280       Name, ArrayType, llvm::GlobalValue::ExternalLinkage);
1281   VTable->setUnnamedAddr(true);
1282 
1283   if (RD->hasAttr<DLLImportAttr>())
1284     VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1285   else if (RD->hasAttr<DLLExportAttr>())
1286     VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1287 
1288   return VTable;
1289 }
1290 
1291 llvm::Value *ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1292                                                       GlobalDecl GD,
1293                                                       llvm::Value *This,
1294                                                       llvm::Type *Ty) {
1295   GD = GD.getCanonicalDecl();
1296   Ty = Ty->getPointerTo()->getPointerTo();
1297   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
1298 
1299   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
1300   llvm::Value *VFuncPtr =
1301       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
1302   return CGF.Builder.CreateLoad(VFuncPtr);
1303 }
1304 
1305 void ItaniumCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1306                                               const CXXDestructorDecl *Dtor,
1307                                               CXXDtorType DtorType,
1308                                               SourceLocation CallLoc,
1309                                               llvm::Value *This) {
1310   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1311 
1312   const CGFunctionInfo *FInfo
1313     = &CGM.getTypes().arrangeCXXDestructor(Dtor, DtorType);
1314   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1315   llvm::Value *Callee =
1316       getVirtualFunctionPointer(CGF, GlobalDecl(Dtor, DtorType), This, Ty);
1317 
1318   CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1319                         /*ImplicitParam=*/nullptr, QualType(), nullptr,
1320                         nullptr);
1321 }
1322 
1323 void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1324   CodeGenVTables &VTables = CGM.getVTables();
1325   llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
1326   VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
1327 }
1328 
1329 static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
1330                                           llvm::Value *Ptr,
1331                                           int64_t NonVirtualAdjustment,
1332                                           int64_t VirtualAdjustment,
1333                                           bool IsReturnAdjustment) {
1334   if (!NonVirtualAdjustment && !VirtualAdjustment)
1335     return Ptr;
1336 
1337   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1338   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
1339 
1340   if (NonVirtualAdjustment && !IsReturnAdjustment) {
1341     // Perform the non-virtual adjustment for a base-to-derived cast.
1342     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1343   }
1344 
1345   if (VirtualAdjustment) {
1346     llvm::Type *PtrDiffTy =
1347         CGF.ConvertType(CGF.getContext().getPointerDiffType());
1348 
1349     // Perform the virtual adjustment.
1350     llvm::Value *VTablePtrPtr =
1351         CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
1352 
1353     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
1354 
1355     llvm::Value *OffsetPtr =
1356         CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
1357 
1358     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
1359 
1360     // Load the adjustment offset from the vtable.
1361     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
1362 
1363     // Adjust our pointer.
1364     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
1365   }
1366 
1367   if (NonVirtualAdjustment && IsReturnAdjustment) {
1368     // Perform the non-virtual adjustment for a derived-to-base cast.
1369     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
1370   }
1371 
1372   // Cast back to the original type.
1373   return CGF.Builder.CreateBitCast(V, Ptr->getType());
1374 }
1375 
1376 llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1377                                                   llvm::Value *This,
1378                                                   const ThisAdjustment &TA) {
1379   return performTypeAdjustment(CGF, This, TA.NonVirtual,
1380                                TA.Virtual.Itanium.VCallOffsetOffset,
1381                                /*IsReturnAdjustment=*/false);
1382 }
1383 
1384 llvm::Value *
1385 ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1386                                        const ReturnAdjustment &RA) {
1387   return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
1388                                RA.Virtual.Itanium.VBaseOffsetOffset,
1389                                /*IsReturnAdjustment=*/true);
1390 }
1391 
1392 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
1393                                     RValue RV, QualType ResultType) {
1394   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
1395     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
1396 
1397   // Destructor thunks in the ARM ABI have indeterminate results.
1398   llvm::Type *T =
1399     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
1400   RValue Undef = RValue::get(llvm::UndefValue::get(T));
1401   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
1402 }
1403 
1404 /************************** Array allocation cookies **************************/
1405 
1406 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1407   // The array cookie is a size_t; pad that up to the element alignment.
1408   // The cookie is actually right-justified in that space.
1409   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
1410                   CGM.getContext().getTypeAlignInChars(elementType));
1411 }
1412 
1413 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1414                                                   llvm::Value *NewPtr,
1415                                                   llvm::Value *NumElements,
1416                                                   const CXXNewExpr *expr,
1417                                                   QualType ElementType) {
1418   assert(requiresArrayCookie(expr));
1419 
1420   unsigned AS = NewPtr->getType()->getPointerAddressSpace();
1421 
1422   ASTContext &Ctx = getContext();
1423   QualType SizeTy = Ctx.getSizeType();
1424   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
1425 
1426   // The size of the cookie.
1427   CharUnits CookieSize =
1428     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
1429   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
1430 
1431   // Compute an offset to the cookie.
1432   llvm::Value *CookiePtr = NewPtr;
1433   CharUnits CookieOffset = CookieSize - SizeSize;
1434   if (!CookieOffset.isZero())
1435     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
1436                                                  CookieOffset.getQuantity());
1437 
1438   // Write the number of elements into the appropriate slot.
1439   llvm::Value *NumElementsPtr
1440     = CGF.Builder.CreateBitCast(CookiePtr,
1441                                 CGF.ConvertType(SizeTy)->getPointerTo(AS));
1442   CGF.Builder.CreateStore(NumElements, NumElementsPtr);
1443 
1444   // Finally, compute a pointer to the actual data buffer by skipping
1445   // over the cookie completely.
1446   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
1447                                                 CookieSize.getQuantity());
1448 }
1449 
1450 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1451                                                 llvm::Value *allocPtr,
1452                                                 CharUnits cookieSize) {
1453   // The element size is right-justified in the cookie.
1454   llvm::Value *numElementsPtr = allocPtr;
1455   CharUnits numElementsOffset =
1456     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
1457   if (!numElementsOffset.isZero())
1458     numElementsPtr =
1459       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
1460                                              numElementsOffset.getQuantity());
1461 
1462   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1463   numElementsPtr =
1464     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1465   return CGF.Builder.CreateLoad(numElementsPtr);
1466 }
1467 
1468 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
1469   // ARM says that the cookie is always:
1470   //   struct array_cookie {
1471   //     std::size_t element_size; // element_size != 0
1472   //     std::size_t element_count;
1473   //   };
1474   // But the base ABI doesn't give anything an alignment greater than
1475   // 8, so we can dismiss this as typical ABI-author blindness to
1476   // actual language complexity and round up to the element alignment.
1477   return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
1478                   CGM.getContext().getTypeAlignInChars(elementType));
1479 }
1480 
1481 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1482                                               llvm::Value *newPtr,
1483                                               llvm::Value *numElements,
1484                                               const CXXNewExpr *expr,
1485                                               QualType elementType) {
1486   assert(requiresArrayCookie(expr));
1487 
1488   // NewPtr is a char*, but we generalize to arbitrary addrspaces.
1489   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1490 
1491   // The cookie is always at the start of the buffer.
1492   llvm::Value *cookie = newPtr;
1493 
1494   // The first element is the element size.
1495   cookie = CGF.Builder.CreateBitCast(cookie, CGF.SizeTy->getPointerTo(AS));
1496   llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
1497                  getContext().getTypeSizeInChars(elementType).getQuantity());
1498   CGF.Builder.CreateStore(elementSize, cookie);
1499 
1500   // The second element is the element count.
1501   cookie = CGF.Builder.CreateConstInBoundsGEP1_32(cookie, 1);
1502   CGF.Builder.CreateStore(numElements, cookie);
1503 
1504   // Finally, compute a pointer to the actual data buffer by skipping
1505   // over the cookie completely.
1506   CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
1507   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1508                                                 cookieSize.getQuantity());
1509 }
1510 
1511 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1512                                             llvm::Value *allocPtr,
1513                                             CharUnits cookieSize) {
1514   // The number of elements is at offset sizeof(size_t) relative to
1515   // the allocated pointer.
1516   llvm::Value *numElementsPtr
1517     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
1518 
1519   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1520   numElementsPtr =
1521     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
1522   return CGF.Builder.CreateLoad(numElementsPtr);
1523 }
1524 
1525 /*********************** Static local initialization **************************/
1526 
1527 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
1528                                          llvm::PointerType *GuardPtrTy) {
1529   // int __cxa_guard_acquire(__guard *guard_object);
1530   llvm::FunctionType *FTy =
1531     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
1532                             GuardPtrTy, /*isVarArg=*/false);
1533   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
1534                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1535                                               llvm::AttributeSet::FunctionIndex,
1536                                                  llvm::Attribute::NoUnwind));
1537 }
1538 
1539 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
1540                                          llvm::PointerType *GuardPtrTy) {
1541   // void __cxa_guard_release(__guard *guard_object);
1542   llvm::FunctionType *FTy =
1543     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1544   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
1545                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1546                                               llvm::AttributeSet::FunctionIndex,
1547                                                  llvm::Attribute::NoUnwind));
1548 }
1549 
1550 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
1551                                        llvm::PointerType *GuardPtrTy) {
1552   // void __cxa_guard_abort(__guard *guard_object);
1553   llvm::FunctionType *FTy =
1554     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
1555   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
1556                                    llvm::AttributeSet::get(CGM.getLLVMContext(),
1557                                               llvm::AttributeSet::FunctionIndex,
1558                                                  llvm::Attribute::NoUnwind));
1559 }
1560 
1561 namespace {
1562   struct CallGuardAbort : EHScopeStack::Cleanup {
1563     llvm::GlobalVariable *Guard;
1564     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
1565 
1566     void Emit(CodeGenFunction &CGF, Flags flags) override {
1567       CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
1568                                   Guard);
1569     }
1570   };
1571 }
1572 
1573 /// The ARM code here follows the Itanium code closely enough that we
1574 /// just special-case it at particular places.
1575 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
1576                                     const VarDecl &D,
1577                                     llvm::GlobalVariable *var,
1578                                     bool shouldPerformInit) {
1579   CGBuilderTy &Builder = CGF.Builder;
1580 
1581   // We only need to use thread-safe statics for local non-TLS variables;
1582   // global initialization is always single-threaded.
1583   bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
1584                     D.isLocalVarDecl() && !D.getTLSKind();
1585 
1586   // If we have a global variable with internal linkage and thread-safe statics
1587   // are disabled, we can just let the guard variable be of type i8.
1588   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
1589 
1590   llvm::IntegerType *guardTy;
1591   if (useInt8GuardVariable) {
1592     guardTy = CGF.Int8Ty;
1593   } else {
1594     // Guard variables are 64 bits in the generic ABI and size width on ARM
1595     // (i.e. 32-bit on AArch32, 64-bit on AArch64).
1596     guardTy = (UseARMGuardVarABI ? CGF.SizeTy : CGF.Int64Ty);
1597   }
1598   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
1599 
1600   // Create the guard variable if we don't already have it (as we
1601   // might if we're double-emitting this function body).
1602   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
1603   if (!guard) {
1604     // Mangle the name for the guard.
1605     SmallString<256> guardName;
1606     {
1607       llvm::raw_svector_ostream out(guardName);
1608       getMangleContext().mangleStaticGuardVariable(&D, out);
1609       out.flush();
1610     }
1611 
1612     // Create the guard variable with a zero-initializer.
1613     // Just absorb linkage and visibility from the guarded variable.
1614     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1615                                      false, var->getLinkage(),
1616                                      llvm::ConstantInt::get(guardTy, 0),
1617                                      guardName.str());
1618     guard->setVisibility(var->getVisibility());
1619     // If the variable is thread-local, so is its guard variable.
1620     guard->setThreadLocalMode(var->getThreadLocalMode());
1621 
1622     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1623   }
1624 
1625   // Test whether the variable has completed initialization.
1626   //
1627   // Itanium C++ ABI 3.3.2:
1628   //   The following is pseudo-code showing how these functions can be used:
1629   //     if (obj_guard.first_byte == 0) {
1630   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1631   //         try {
1632   //           ... initialize the object ...;
1633   //         } catch (...) {
1634   //            __cxa_guard_abort (&obj_guard);
1635   //            throw;
1636   //         }
1637   //         ... queue object destructor with __cxa_atexit() ...;
1638   //         __cxa_guard_release (&obj_guard);
1639   //       }
1640   //     }
1641 
1642   // Load the first byte of the guard variable.
1643   llvm::LoadInst *LI =
1644       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1645   LI->setAlignment(1);
1646 
1647   // Itanium ABI:
1648   //   An implementation supporting thread-safety on multiprocessor
1649   //   systems must also guarantee that references to the initialized
1650   //   object do not occur before the load of the initialization flag.
1651   //
1652   // In LLVM, we do this by marking the load Acquire.
1653   if (threadsafe)
1654     LI->setAtomic(llvm::Acquire);
1655 
1656   // For ARM, we should only check the first bit, rather than the entire byte:
1657   //
1658   // ARM C++ ABI 3.2.3.1:
1659   //   To support the potential use of initialization guard variables
1660   //   as semaphores that are the target of ARM SWP and LDREX/STREX
1661   //   synchronizing instructions we define a static initialization
1662   //   guard variable to be a 4-byte aligned, 4-byte word with the
1663   //   following inline access protocol.
1664   //     #define INITIALIZED 1
1665   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
1666   //       if (__cxa_guard_acquire(&obj_guard))
1667   //         ...
1668   //     }
1669   //
1670   // and similarly for ARM64:
1671   //
1672   // ARM64 C++ ABI 3.2.2:
1673   //   This ABI instead only specifies the value bit 0 of the static guard
1674   //   variable; all other bits are platform defined. Bit 0 shall be 0 when the
1675   //   variable is not initialized and 1 when it is.
1676   llvm::Value *V =
1677       (UseARMGuardVarABI && !useInt8GuardVariable)
1678           ? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
1679           : LI;
1680   llvm::Value *isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1681 
1682   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1683   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1684 
1685   // Check if the first byte of the guard variable is zero.
1686   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1687 
1688   CGF.EmitBlock(InitCheckBlock);
1689 
1690   // Variables used when coping with thread-safe statics and exceptions.
1691   if (threadsafe) {
1692     // Call __cxa_guard_acquire.
1693     llvm::Value *V
1694       = CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1695 
1696     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1697 
1698     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1699                          InitBlock, EndBlock);
1700 
1701     // Call __cxa_guard_abort along the exceptional edge.
1702     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1703 
1704     CGF.EmitBlock(InitBlock);
1705   }
1706 
1707   // Emit the initializer and add a global destructor if appropriate.
1708   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1709 
1710   if (threadsafe) {
1711     // Pop the guard-abort cleanup if we pushed one.
1712     CGF.PopCleanupBlock();
1713 
1714     // Call __cxa_guard_release.  This cannot throw.
1715     CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1716   } else {
1717     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1718   }
1719 
1720   CGF.EmitBlock(EndBlock);
1721 }
1722 
1723 /// Register a global destructor using __cxa_atexit.
1724 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1725                                         llvm::Constant *dtor,
1726                                         llvm::Constant *addr,
1727                                         bool TLS) {
1728   const char *Name = "__cxa_atexit";
1729   if (TLS) {
1730     const llvm::Triple &T = CGF.getTarget().getTriple();
1731     Name = T.isMacOSX() ?  "_tlv_atexit" : "__cxa_thread_atexit";
1732   }
1733 
1734   // We're assuming that the destructor function is something we can
1735   // reasonably call with the default CC.  Go ahead and cast it to the
1736   // right prototype.
1737   llvm::Type *dtorTy =
1738     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1739 
1740   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1741   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1742   llvm::FunctionType *atexitTy =
1743     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1744 
1745   // Fetch the actual function.
1746   llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
1747   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1748     fn->setDoesNotThrow();
1749 
1750   // Create a variable that binds the atexit to this shared object.
1751   llvm::Constant *handle =
1752     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1753 
1754   llvm::Value *args[] = {
1755     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1756     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1757     handle
1758   };
1759   CGF.EmitNounwindRuntimeCall(atexit, args);
1760 }
1761 
1762 /// Register a global destructor as best as we know how.
1763 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1764                                        const VarDecl &D,
1765                                        llvm::Constant *dtor,
1766                                        llvm::Constant *addr) {
1767   // Use __cxa_atexit if available.
1768   if (CGM.getCodeGenOpts().CXAAtExit)
1769     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
1770 
1771   if (D.getTLSKind())
1772     CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
1773 
1774   // In Apple kexts, we want to add a global destructor entry.
1775   // FIXME: shouldn't this be guarded by some variable?
1776   if (CGM.getLangOpts().AppleKext) {
1777     // Generate a global destructor entry.
1778     return CGM.AddCXXDtorEntry(dtor, addr);
1779   }
1780 
1781   CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
1782 }
1783 
1784 /// Get the appropriate linkage for the wrapper function. This is essentially
1785 /// the weak form of the variable's linkage; every translation unit which wneeds
1786 /// the wrapper emits a copy, and we want the linker to merge them.
1787 static llvm::GlobalValue::LinkageTypes
1788 getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
1789   llvm::GlobalValue::LinkageTypes VarLinkage =
1790       CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false);
1791 
1792   // For internal linkage variables, we don't need an external or weak wrapper.
1793   if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
1794     return VarLinkage;
1795 
1796   // All accesses to the thread_local variable go through the thread wrapper.
1797   // However, this means that we cannot allow the thread wrapper to get inlined
1798   // into any functions.
1799   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1800       CGM.getTarget().getTriple().isMacOSX())
1801     return llvm::GlobalValue::WeakAnyLinkage;
1802   return llvm::GlobalValue::WeakODRLinkage;
1803 }
1804 
1805 llvm::Function *
1806 ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
1807                                              llvm::GlobalVariable *Var) {
1808   // Mangle the name for the thread_local wrapper function.
1809   SmallString<256> WrapperName;
1810   {
1811     llvm::raw_svector_ostream Out(WrapperName);
1812     getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
1813     Out.flush();
1814   }
1815 
1816   if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
1817     return cast<llvm::Function>(V);
1818 
1819   llvm::Type *RetTy = Var->getType();
1820   if (VD->getType()->isReferenceType())
1821     RetTy = RetTy->getPointerElementType();
1822 
1823   llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
1824   llvm::Function *Wrapper =
1825       llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
1826                              WrapperName.str(), &CGM.getModule());
1827   // Always resolve references to the wrapper at link time.
1828   if (!Wrapper->hasLocalLinkage())
1829     Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
1830   return Wrapper;
1831 }
1832 
1833 void ItaniumCXXABI::EmitThreadLocalInitFuncs(
1834     llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
1835     llvm::Function *InitFunc) {
1836   for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
1837     const VarDecl *VD = Decls[I].first;
1838     llvm::GlobalVariable *Var = Decls[I].second;
1839 
1840     // Mangle the name for the thread_local initialization function.
1841     SmallString<256> InitFnName;
1842     {
1843       llvm::raw_svector_ostream Out(InitFnName);
1844       getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
1845       Out.flush();
1846     }
1847 
1848     // If we have a definition for the variable, emit the initialization
1849     // function as an alias to the global Init function (if any). Otherwise,
1850     // produce a declaration of the initialization function.
1851     llvm::GlobalValue *Init = nullptr;
1852     bool InitIsInitFunc = false;
1853     if (VD->hasDefinition()) {
1854       InitIsInitFunc = true;
1855       if (InitFunc)
1856         Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
1857                                          InitFunc);
1858     } else {
1859       // Emit a weak global function referring to the initialization function.
1860       // This function will not exist if the TU defining the thread_local
1861       // variable in question does not need any dynamic initialization for
1862       // its thread_local variables.
1863       llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
1864       Init = llvm::Function::Create(
1865           FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
1866           &CGM.getModule());
1867     }
1868 
1869     if (Init)
1870       Init->setVisibility(Var->getVisibility());
1871 
1872     llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
1873     llvm::LLVMContext &Context = CGM.getModule().getContext();
1874     llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
1875     CGBuilderTy Builder(Entry);
1876     if (InitIsInitFunc) {
1877       if (Init)
1878         Builder.CreateCall(Init);
1879     } else {
1880       // Don't know whether we have an init function. Call it if it exists.
1881       llvm::Value *Have = Builder.CreateIsNotNull(Init);
1882       llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1883       llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
1884       Builder.CreateCondBr(Have, InitBB, ExitBB);
1885 
1886       Builder.SetInsertPoint(InitBB);
1887       Builder.CreateCall(Init);
1888       Builder.CreateBr(ExitBB);
1889 
1890       Builder.SetInsertPoint(ExitBB);
1891     }
1892 
1893     // For a reference, the result of the wrapper function is a pointer to
1894     // the referenced object.
1895     llvm::Value *Val = Var;
1896     if (VD->getType()->isReferenceType()) {
1897       llvm::LoadInst *LI = Builder.CreateLoad(Val);
1898       LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
1899       Val = LI;
1900     }
1901 
1902     Builder.CreateRet(Val);
1903   }
1904 }
1905 
1906 LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
1907                                                    const VarDecl *VD,
1908                                                    QualType LValType) {
1909   QualType T = VD->getType();
1910   llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
1911   llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
1912   llvm::Function *Wrapper =
1913       getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
1914 
1915   Val = CGF.Builder.CreateCall(Wrapper);
1916 
1917   LValue LV;
1918   if (VD->getType()->isReferenceType())
1919     LV = CGF.MakeNaturalAlignAddrLValue(Val, LValType);
1920   else
1921     LV = CGF.MakeAddrLValue(Val, LValType, CGF.getContext().getDeclAlign(VD));
1922   // FIXME: need setObjCGCLValueClass?
1923   return LV;
1924 }
1925 
1926 /// Return whether the given global decl needs a VTT parameter, which it does
1927 /// if it's a base constructor or destructor with virtual bases.
1928 bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
1929   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1930 
1931   // We don't have any virtual bases, just return early.
1932   if (!MD->getParent()->getNumVBases())
1933     return false;
1934 
1935   // Check if we have a base constructor.
1936   if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
1937     return true;
1938 
1939   // Check if we have a base destructor.
1940   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1941     return true;
1942 
1943   return false;
1944 }
1945