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/Intrinsics.h>
29 #include <llvm/Target/TargetData.h>
30 #include <llvm/Value.h>
31 
32 using namespace clang;
33 using namespace CodeGen;
34 
35 namespace {
36 class ItaniumCXXABI : public CodeGen::CGCXXABI {
37 private:
38   llvm::IntegerType *PtrDiffTy;
39 protected:
40   bool IsARM;
41 
42   // It's a little silly for us to cache this.
43   llvm::IntegerType *getPtrDiffTy() {
44     if (!PtrDiffTy) {
45       QualType T = getContext().getPointerDiffType();
46       llvm::Type *Ty = CGM.getTypes().ConvertType(T);
47       PtrDiffTy = cast<llvm::IntegerType>(Ty);
48     }
49     return PtrDiffTy;
50   }
51 
52 public:
53   ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
54     CGCXXABI(CGM), PtrDiffTy(0), IsARM(IsARM) { }
55 
56   bool isZeroInitializable(const MemberPointerType *MPT);
57 
58   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
59 
60   llvm::Value *EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
61                                                llvm::Value *&This,
62                                                llvm::Value *MemFnPtr,
63                                                const MemberPointerType *MPT);
64 
65   llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
66                                             llvm::Value *Base,
67                                             llvm::Value *MemPtr,
68                                             const MemberPointerType *MPT);
69 
70   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
71                                            const CastExpr *E,
72                                            llvm::Value *Src);
73   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
74                                               llvm::Constant *Src);
75 
76   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
77 
78   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
79   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
80                                         CharUnits offset);
81   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
82   llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
83                                      CharUnits ThisAdjustment);
84 
85   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
86                                            llvm::Value *L,
87                                            llvm::Value *R,
88                                            const MemberPointerType *MPT,
89                                            bool Inequality);
90 
91   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
92                                           llvm::Value *Addr,
93                                           const MemberPointerType *MPT);
94 
95   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
96                                  CXXCtorType T,
97                                  CanQualType &ResTy,
98                                  SmallVectorImpl<CanQualType> &ArgTys);
99 
100   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
101                                 CXXDtorType T,
102                                 CanQualType &ResTy,
103                                 SmallVectorImpl<CanQualType> &ArgTys);
104 
105   void BuildInstanceFunctionParams(CodeGenFunction &CGF,
106                                    QualType &ResTy,
107                                    FunctionArgList &Params);
108 
109   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
110 
111   CharUnits getArrayCookieSizeImpl(QualType elementType);
112   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
113                                      llvm::Value *NewPtr,
114                                      llvm::Value *NumElements,
115                                      const CXXNewExpr *expr,
116                                      QualType ElementType);
117   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
118                                    llvm::Value *allocPtr,
119                                    CharUnits cookieSize);
120 
121   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
122                        llvm::GlobalVariable *DeclPtr, bool PerformInit);
123   void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
124                           llvm::Constant *addr);
125 
126   void EmitVTables(const CXXRecordDecl *Class);
127 };
128 
129 class ARMCXXABI : public ItaniumCXXABI {
130 public:
131   ARMCXXABI(CodeGen::CodeGenModule &CGM) : ItaniumCXXABI(CGM, /*ARM*/ true) {}
132 
133   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
134                                  CXXCtorType T,
135                                  CanQualType &ResTy,
136                                  SmallVectorImpl<CanQualType> &ArgTys);
137 
138   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
139                                 CXXDtorType T,
140                                 CanQualType &ResTy,
141                                 SmallVectorImpl<CanQualType> &ArgTys);
142 
143   void BuildInstanceFunctionParams(CodeGenFunction &CGF,
144                                    QualType &ResTy,
145                                    FunctionArgList &Params);
146 
147   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
148 
149   void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV, QualType ResTy);
150 
151   CharUnits getArrayCookieSizeImpl(QualType elementType);
152   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
153                                      llvm::Value *NewPtr,
154                                      llvm::Value *NumElements,
155                                      const CXXNewExpr *expr,
156                                      QualType ElementType);
157   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, llvm::Value *allocPtr,
158                                    CharUnits cookieSize);
159 
160 private:
161   /// \brief Returns true if the given instance method is one of the
162   /// kinds that the ARM ABI says returns 'this'.
163   static bool HasThisReturn(GlobalDecl GD) {
164     const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
165     return ((isa<CXXDestructorDecl>(MD) && GD.getDtorType() != Dtor_Deleting) ||
166             (isa<CXXConstructorDecl>(MD)));
167   }
168 };
169 }
170 
171 CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
172   return new ItaniumCXXABI(CGM);
173 }
174 
175 CodeGen::CGCXXABI *CodeGen::CreateARMCXXABI(CodeGenModule &CGM) {
176   return new ARMCXXABI(CGM);
177 }
178 
179 llvm::Type *
180 ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
181   if (MPT->isMemberDataPointer())
182     return getPtrDiffTy();
183   return llvm::StructType::get(getPtrDiffTy(), getPtrDiffTy(), NULL);
184 }
185 
186 /// In the Itanium and ARM ABIs, method pointers have the form:
187 ///   struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
188 ///
189 /// In the Itanium ABI:
190 ///  - method pointers are virtual if (memptr.ptr & 1) is nonzero
191 ///  - the this-adjustment is (memptr.adj)
192 ///  - the virtual offset is (memptr.ptr - 1)
193 ///
194 /// In the ARM ABI:
195 ///  - method pointers are virtual if (memptr.adj & 1) is nonzero
196 ///  - the this-adjustment is (memptr.adj >> 1)
197 ///  - the virtual offset is (memptr.ptr)
198 /// ARM uses 'adj' for the virtual flag because Thumb functions
199 /// may be only single-byte aligned.
200 ///
201 /// If the member is virtual, the adjusted 'this' pointer points
202 /// to a vtable pointer from which the virtual offset is applied.
203 ///
204 /// If the member is non-virtual, memptr.ptr is the address of
205 /// the function to call.
206 llvm::Value *
207 ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
208                                                llvm::Value *&This,
209                                                llvm::Value *MemFnPtr,
210                                                const MemberPointerType *MPT) {
211   CGBuilderTy &Builder = CGF.Builder;
212 
213   const FunctionProtoType *FPT =
214     MPT->getPointeeType()->getAs<FunctionProtoType>();
215   const CXXRecordDecl *RD =
216     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
217 
218   llvm::FunctionType *FTy =
219     CGM.getTypes().GetFunctionType(
220       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
221 
222   llvm::IntegerType *ptrdiff = getPtrDiffTy();
223   llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(ptrdiff, 1);
224 
225   llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
226   llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
227   llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
228 
229   // Extract memptr.adj, which is in the second field.
230   llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
231 
232   // Compute the true adjustment.
233   llvm::Value *Adj = RawAdj;
234   if (IsARM)
235     Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
236 
237   // Apply the adjustment and cast back to the original struct type
238   // for consistency.
239   llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
240   Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
241   This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
242 
243   // Load the function pointer.
244   llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
245 
246   // If the LSB in the function pointer is 1, the function pointer points to
247   // a virtual function.
248   llvm::Value *IsVirtual;
249   if (IsARM)
250     IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
251   else
252     IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
253   IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
254   Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
255 
256   // In the virtual path, the adjustment left 'This' pointing to the
257   // vtable of the correct base subobject.  The "function pointer" is an
258   // offset within the vtable (+1 for the virtual flag on non-ARM).
259   CGF.EmitBlock(FnVirtual);
260 
261   // Cast the adjusted this to a pointer to vtable pointer and load.
262   llvm::Type *VTableTy = Builder.getInt8PtrTy();
263   llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy->getPointerTo());
264   VTable = Builder.CreateLoad(VTable, "memptr.vtable");
265 
266   // Apply the offset.
267   llvm::Value *VTableOffset = FnAsInt;
268   if (!IsARM) VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
269   VTable = Builder.CreateGEP(VTable, VTableOffset);
270 
271   // Load the virtual function to call.
272   VTable = Builder.CreateBitCast(VTable, FTy->getPointerTo()->getPointerTo());
273   llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "memptr.virtualfn");
274   CGF.EmitBranch(FnEnd);
275 
276   // In the non-virtual path, the function pointer is actually a
277   // function pointer.
278   CGF.EmitBlock(FnNonVirtual);
279   llvm::Value *NonVirtualFn =
280     Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
281 
282   // We're done.
283   CGF.EmitBlock(FnEnd);
284   llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo(), 2);
285   Callee->addIncoming(VirtualFn, FnVirtual);
286   Callee->addIncoming(NonVirtualFn, FnNonVirtual);
287   return Callee;
288 }
289 
290 /// Compute an l-value by applying the given pointer-to-member to a
291 /// base object.
292 llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
293                                                          llvm::Value *Base,
294                                                          llvm::Value *MemPtr,
295                                            const MemberPointerType *MPT) {
296   assert(MemPtr->getType() == getPtrDiffTy());
297 
298   CGBuilderTy &Builder = CGF.Builder;
299 
300   unsigned AS = cast<llvm::PointerType>(Base->getType())->getAddressSpace();
301 
302   // Cast to char*.
303   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
304 
305   // Apply the offset, which we assume is non-null.
306   llvm::Value *Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
307 
308   // Cast the address to the appropriate pointer type, adopting the
309   // address space of the base pointer.
310   llvm::Type *PType
311     = CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
312   return Builder.CreateBitCast(Addr, PType);
313 }
314 
315 /// Perform a bitcast, derived-to-base, or base-to-derived member pointer
316 /// conversion.
317 ///
318 /// Bitcast conversions are always a no-op under Itanium.
319 ///
320 /// Obligatory offset/adjustment diagram:
321 ///         <-- offset -->          <-- adjustment -->
322 ///   |--------------------------|----------------------|--------------------|
323 ///   ^Derived address point     ^Base address point    ^Member address point
324 ///
325 /// So when converting a base member pointer to a derived member pointer,
326 /// we add the offset to the adjustment because the address point has
327 /// decreased;  and conversely, when converting a derived MP to a base MP
328 /// we subtract the offset from the adjustment because the address point
329 /// has increased.
330 ///
331 /// The standard forbids (at compile time) conversion to and from
332 /// virtual bases, which is why we don't have to consider them here.
333 ///
334 /// The standard forbids (at run time) casting a derived MP to a base
335 /// MP when the derived MP does not point to a member of the base.
336 /// This is why -1 is a reasonable choice for null data member
337 /// pointers.
338 llvm::Value *
339 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
340                                            const CastExpr *E,
341                                            llvm::Value *src) {
342   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
343          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
344          E->getCastKind() == CK_ReinterpretMemberPointer);
345 
346   // Under Itanium, reinterprets don't require any additional processing.
347   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
348 
349   // Use constant emission if we can.
350   if (isa<llvm::Constant>(src))
351     return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
352 
353   llvm::Constant *adj = getMemberPointerAdjustment(E);
354   if (!adj) return src;
355 
356   CGBuilderTy &Builder = CGF.Builder;
357   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
358 
359   const MemberPointerType *destTy =
360     E->getType()->castAs<MemberPointerType>();
361 
362   // For member data pointers, this is just a matter of adding the
363   // offset if the source is non-null.
364   if (destTy->isMemberDataPointer()) {
365     llvm::Value *dst;
366     if (isDerivedToBase)
367       dst = Builder.CreateNSWSub(src, adj, "adj");
368     else
369       dst = Builder.CreateNSWAdd(src, adj, "adj");
370 
371     // Null check.
372     llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
373     llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
374     return Builder.CreateSelect(isNull, src, dst);
375   }
376 
377   // The this-adjustment is left-shifted by 1 on ARM.
378   if (IsARM) {
379     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
380     offset <<= 1;
381     adj = llvm::ConstantInt::get(adj->getType(), offset);
382   }
383 
384   llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
385   llvm::Value *dstAdj;
386   if (isDerivedToBase)
387     dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
388   else
389     dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
390 
391   return Builder.CreateInsertValue(src, dstAdj, 1);
392 }
393 
394 llvm::Constant *
395 ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
396                                            llvm::Constant *src) {
397   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
398          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
399          E->getCastKind() == CK_ReinterpretMemberPointer);
400 
401   // Under Itanium, reinterprets don't require any additional processing.
402   if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
403 
404   // If the adjustment is trivial, we don't need to do anything.
405   llvm::Constant *adj = getMemberPointerAdjustment(E);
406   if (!adj) return src;
407 
408   bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
409 
410   const MemberPointerType *destTy =
411     E->getType()->castAs<MemberPointerType>();
412 
413   // For member data pointers, this is just a matter of adding the
414   // offset if the source is non-null.
415   if (destTy->isMemberDataPointer()) {
416     // null maps to null.
417     if (src->isAllOnesValue()) return src;
418 
419     if (isDerivedToBase)
420       return llvm::ConstantExpr::getNSWSub(src, adj);
421     else
422       return llvm::ConstantExpr::getNSWAdd(src, adj);
423   }
424 
425   // The this-adjustment is left-shifted by 1 on ARM.
426   if (IsARM) {
427     uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
428     offset <<= 1;
429     adj = llvm::ConstantInt::get(adj->getType(), offset);
430   }
431 
432   llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
433   llvm::Constant *dstAdj;
434   if (isDerivedToBase)
435     dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
436   else
437     dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
438 
439   return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
440 }
441 
442 llvm::Constant *
443 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
444   llvm::Type *ptrdiff_t = getPtrDiffTy();
445 
446   // Itanium C++ ABI 2.3:
447   //   A NULL pointer is represented as -1.
448   if (MPT->isMemberDataPointer())
449     return llvm::ConstantInt::get(ptrdiff_t, -1ULL, /*isSigned=*/true);
450 
451   llvm::Constant *Zero = llvm::ConstantInt::get(ptrdiff_t, 0);
452   llvm::Constant *Values[2] = { Zero, Zero };
453   return llvm::ConstantStruct::getAnon(Values);
454 }
455 
456 llvm::Constant *
457 ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
458                                      CharUnits offset) {
459   // Itanium C++ ABI 2.3:
460   //   A pointer to data member is an offset from the base address of
461   //   the class object containing it, represented as a ptrdiff_t
462   return llvm::ConstantInt::get(getPtrDiffTy(), offset.getQuantity());
463 }
464 
465 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
466   return BuildMemberPointer(MD, CharUnits::Zero());
467 }
468 
469 llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
470                                                   CharUnits ThisAdjustment) {
471   assert(MD->isInstance() && "Member function must not be static!");
472   MD = MD->getCanonicalDecl();
473 
474   CodeGenTypes &Types = CGM.getTypes();
475   llvm::Type *ptrdiff_t = getPtrDiffTy();
476 
477   // Get the function pointer (or index if this is a virtual function).
478   llvm::Constant *MemPtr[2];
479   if (MD->isVirtual()) {
480     uint64_t Index = CGM.getVTableContext().getMethodVTableIndex(MD);
481 
482     const ASTContext &Context = getContext();
483     CharUnits PointerWidth =
484       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
485     uint64_t VTableOffset = (Index * PointerWidth.getQuantity());
486 
487     if (IsARM) {
488       // ARM C++ ABI 3.2.1:
489       //   This ABI specifies that adj contains twice the this
490       //   adjustment, plus 1 if the member function is virtual. The
491       //   least significant bit of adj then makes exactly the same
492       //   discrimination as the least significant bit of ptr does for
493       //   Itanium.
494       MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
495       MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
496                                          2 * ThisAdjustment.getQuantity() + 1);
497     } else {
498       // Itanium C++ ABI 2.3:
499       //   For a virtual function, [the pointer field] is 1 plus the
500       //   virtual table offset (in bytes) of the function,
501       //   represented as a ptrdiff_t.
502       MemPtr[0] = llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
503       MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t,
504                                          ThisAdjustment.getQuantity());
505     }
506   } else {
507     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
508     llvm::Type *Ty;
509     // Check whether the function has a computable LLVM signature.
510     if (Types.isFuncTypeConvertible(FPT)) {
511       // The function has a computable LLVM signature; use the correct type.
512       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
513     } else {
514       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
515       // function type is incomplete.
516       Ty = ptrdiff_t;
517     }
518     llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
519 
520     MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
521     MemPtr[1] = llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
522                                        ThisAdjustment.getQuantity());
523   }
524 
525   return llvm::ConstantStruct::getAnon(MemPtr);
526 }
527 
528 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
529                                                  QualType MPType) {
530   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
531   const ValueDecl *MPD = MP.getMemberPointerDecl();
532   if (!MPD)
533     return EmitNullMemberPointer(MPT);
534 
535   // Compute the this-adjustment.
536   CharUnits ThisAdjustment = CharUnits::Zero();
537   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
538   bool DerivedMember = MP.isMemberPointerToDerivedMember();
539   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
540   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
541     const CXXRecordDecl *Base = RD;
542     const CXXRecordDecl *Derived = Path[I];
543     if (DerivedMember)
544       std::swap(Base, Derived);
545     ThisAdjustment +=
546       getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
547     RD = Path[I];
548   }
549   if (DerivedMember)
550     ThisAdjustment = -ThisAdjustment;
551 
552   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
553     return BuildMemberPointer(MD, ThisAdjustment);
554 
555   CharUnits FieldOffset =
556     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
557   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
558 }
559 
560 /// The comparison algorithm is pretty easy: the member pointers are
561 /// the same if they're either bitwise identical *or* both null.
562 ///
563 /// ARM is different here only because null-ness is more complicated.
564 llvm::Value *
565 ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
566                                            llvm::Value *L,
567                                            llvm::Value *R,
568                                            const MemberPointerType *MPT,
569                                            bool Inequality) {
570   CGBuilderTy &Builder = CGF.Builder;
571 
572   llvm::ICmpInst::Predicate Eq;
573   llvm::Instruction::BinaryOps And, Or;
574   if (Inequality) {
575     Eq = llvm::ICmpInst::ICMP_NE;
576     And = llvm::Instruction::Or;
577     Or = llvm::Instruction::And;
578   } else {
579     Eq = llvm::ICmpInst::ICMP_EQ;
580     And = llvm::Instruction::And;
581     Or = llvm::Instruction::Or;
582   }
583 
584   // Member data pointers are easy because there's a unique null
585   // value, so it just comes down to bitwise equality.
586   if (MPT->isMemberDataPointer())
587     return Builder.CreateICmp(Eq, L, R);
588 
589   // For member function pointers, the tautologies are more complex.
590   // The Itanium tautology is:
591   //   (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
592   // The ARM tautology is:
593   //   (L == R) <==> (L.ptr == R.ptr &&
594   //                  (L.adj == R.adj ||
595   //                   (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
596   // The inequality tautologies have exactly the same structure, except
597   // applying De Morgan's laws.
598 
599   llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
600   llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
601 
602   // This condition tests whether L.ptr == R.ptr.  This must always be
603   // true for equality to hold.
604   llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
605 
606   // This condition, together with the assumption that L.ptr == R.ptr,
607   // tests whether the pointers are both null.  ARM imposes an extra
608   // condition.
609   llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
610   llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
611 
612   // This condition tests whether L.adj == R.adj.  If this isn't
613   // true, the pointers are unequal unless they're both null.
614   llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
615   llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
616   llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
617 
618   // Null member function pointers on ARM clear the low bit of Adj,
619   // so the zero condition has to check that neither low bit is set.
620   if (IsARM) {
621     llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
622 
623     // Compute (l.adj | r.adj) & 1 and test it against zero.
624     llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
625     llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
626     llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
627                                                       "cmp.or.adj");
628     EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
629   }
630 
631   // Tie together all our conditions.
632   llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
633   Result = Builder.CreateBinOp(And, PtrEq, Result,
634                                Inequality ? "memptr.ne" : "memptr.eq");
635   return Result;
636 }
637 
638 llvm::Value *
639 ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
640                                           llvm::Value *MemPtr,
641                                           const MemberPointerType *MPT) {
642   CGBuilderTy &Builder = CGF.Builder;
643 
644   /// For member data pointers, this is just a check against -1.
645   if (MPT->isMemberDataPointer()) {
646     assert(MemPtr->getType() == getPtrDiffTy());
647     llvm::Value *NegativeOne =
648       llvm::Constant::getAllOnesValue(MemPtr->getType());
649     return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
650   }
651 
652   // In Itanium, a member function pointer is not null if 'ptr' is not null.
653   llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
654 
655   llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
656   llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
657 
658   // On ARM, a member function pointer is also non-null if the low bit of 'adj'
659   // (the virtual bit) is set.
660   if (IsARM) {
661     llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
662     llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
663     llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
664     llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
665                                                   "memptr.isvirtual");
666     Result = Builder.CreateOr(Result, IsVirtual);
667   }
668 
669   return Result;
670 }
671 
672 /// The Itanium ABI requires non-zero initialization only for data
673 /// member pointers, for which '0' is a valid offset.
674 bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
675   return MPT->getPointeeType()->isFunctionType();
676 }
677 
678 /// The generic ABI passes 'this', plus a VTT if it's initializing a
679 /// base subobject.
680 void ItaniumCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
681                                               CXXCtorType Type,
682                                               CanQualType &ResTy,
683                                 SmallVectorImpl<CanQualType> &ArgTys) {
684   ASTContext &Context = getContext();
685 
686   // 'this' is already there.
687 
688   // Check if we need to add a VTT parameter (which has type void **).
689   if (Type == Ctor_Base && Ctor->getParent()->getNumVBases() != 0)
690     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
691 }
692 
693 /// The ARM ABI does the same as the Itanium ABI, but returns 'this'.
694 void ARMCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
695                                           CXXCtorType Type,
696                                           CanQualType &ResTy,
697                                 SmallVectorImpl<CanQualType> &ArgTys) {
698   ItaniumCXXABI::BuildConstructorSignature(Ctor, Type, ResTy, ArgTys);
699   ResTy = ArgTys[0];
700 }
701 
702 /// The generic ABI passes 'this', plus a VTT if it's destroying a
703 /// base subobject.
704 void ItaniumCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
705                                              CXXDtorType Type,
706                                              CanQualType &ResTy,
707                                 SmallVectorImpl<CanQualType> &ArgTys) {
708   ASTContext &Context = getContext();
709 
710   // 'this' is already there.
711 
712   // Check if we need to add a VTT parameter (which has type void **).
713   if (Type == Dtor_Base && Dtor->getParent()->getNumVBases() != 0)
714     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
715 }
716 
717 /// The ARM ABI does the same as the Itanium ABI, but returns 'this'
718 /// for non-deleting destructors.
719 void ARMCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
720                                          CXXDtorType Type,
721                                          CanQualType &ResTy,
722                                 SmallVectorImpl<CanQualType> &ArgTys) {
723   ItaniumCXXABI::BuildDestructorSignature(Dtor, Type, ResTy, ArgTys);
724 
725   if (Type != Dtor_Deleting)
726     ResTy = ArgTys[0];
727 }
728 
729 void ItaniumCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
730                                                 QualType &ResTy,
731                                                 FunctionArgList &Params) {
732   /// Create the 'this' variable.
733   BuildThisParam(CGF, Params);
734 
735   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
736   assert(MD->isInstance());
737 
738   // Check if we need a VTT parameter as well.
739   if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
740     ASTContext &Context = getContext();
741 
742     // FIXME: avoid the fake decl
743     QualType T = Context.getPointerType(Context.VoidPtrTy);
744     ImplicitParamDecl *VTTDecl
745       = ImplicitParamDecl::Create(Context, 0, MD->getLocation(),
746                                   &Context.Idents.get("vtt"), T);
747     Params.push_back(VTTDecl);
748     getVTTDecl(CGF) = VTTDecl;
749   }
750 }
751 
752 void ARMCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
753                                             QualType &ResTy,
754                                             FunctionArgList &Params) {
755   ItaniumCXXABI::BuildInstanceFunctionParams(CGF, ResTy, Params);
756 
757   // Return 'this' from certain constructors and destructors.
758   if (HasThisReturn(CGF.CurGD))
759     ResTy = Params[0]->getType();
760 }
761 
762 void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
763   /// Initialize the 'this' slot.
764   EmitThisParam(CGF);
765 
766   /// Initialize the 'vtt' slot if needed.
767   if (getVTTDecl(CGF)) {
768     getVTTValue(CGF)
769       = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getVTTDecl(CGF)),
770                                "vtt");
771   }
772 }
773 
774 void ARMCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
775   ItaniumCXXABI::EmitInstanceFunctionProlog(CGF);
776 
777   /// Initialize the return slot to 'this' at the start of the
778   /// function.
779   if (HasThisReturn(CGF.CurGD))
780     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
781 }
782 
783 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
784                                     RValue RV, QualType ResultType) {
785   if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
786     return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
787 
788   // Destructor thunks in the ARM ABI have indeterminate results.
789   llvm::Type *T =
790     cast<llvm::PointerType>(CGF.ReturnValue->getType())->getElementType();
791   RValue Undef = RValue::get(llvm::UndefValue::get(T));
792   return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
793 }
794 
795 /************************** Array allocation cookies **************************/
796 
797 CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
798   // The array cookie is a size_t; pad that up to the element alignment.
799   // The cookie is actually right-justified in that space.
800   return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
801                   CGM.getContext().getTypeAlignInChars(elementType));
802 }
803 
804 llvm::Value *ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
805                                                   llvm::Value *NewPtr,
806                                                   llvm::Value *NumElements,
807                                                   const CXXNewExpr *expr,
808                                                   QualType ElementType) {
809   assert(requiresArrayCookie(expr));
810 
811   unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
812 
813   ASTContext &Ctx = getContext();
814   QualType SizeTy = Ctx.getSizeType();
815   CharUnits SizeSize = Ctx.getTypeSizeInChars(SizeTy);
816 
817   // The size of the cookie.
818   CharUnits CookieSize =
819     std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
820   assert(CookieSize == getArrayCookieSizeImpl(ElementType));
821 
822   // Compute an offset to the cookie.
823   llvm::Value *CookiePtr = NewPtr;
824   CharUnits CookieOffset = CookieSize - SizeSize;
825   if (!CookieOffset.isZero())
826     CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_64(CookiePtr,
827                                                  CookieOffset.getQuantity());
828 
829   // Write the number of elements into the appropriate slot.
830   llvm::Value *NumElementsPtr
831     = CGF.Builder.CreateBitCast(CookiePtr,
832                                 CGF.ConvertType(SizeTy)->getPointerTo(AS));
833   CGF.Builder.CreateStore(NumElements, NumElementsPtr);
834 
835   // Finally, compute a pointer to the actual data buffer by skipping
836   // over the cookie completely.
837   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
838                                                 CookieSize.getQuantity());
839 }
840 
841 llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
842                                                 llvm::Value *allocPtr,
843                                                 CharUnits cookieSize) {
844   // The element size is right-justified in the cookie.
845   llvm::Value *numElementsPtr = allocPtr;
846   CharUnits numElementsOffset =
847     cookieSize - CharUnits::fromQuantity(CGF.SizeSizeInBytes);
848   if (!numElementsOffset.isZero())
849     numElementsPtr =
850       CGF.Builder.CreateConstInBoundsGEP1_64(numElementsPtr,
851                                              numElementsOffset.getQuantity());
852 
853   unsigned AS = cast<llvm::PointerType>(allocPtr->getType())->getAddressSpace();
854   numElementsPtr =
855     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
856   return CGF.Builder.CreateLoad(numElementsPtr);
857 }
858 
859 CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
860   // On ARM, the cookie is always:
861   //   struct array_cookie {
862   //     std::size_t element_size; // element_size != 0
863   //     std::size_t element_count;
864   //   };
865   // TODO: what should we do if the allocated type actually wants
866   // greater alignment?
867   return CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes);
868 }
869 
870 llvm::Value *ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
871                                               llvm::Value *NewPtr,
872                                               llvm::Value *NumElements,
873                                               const CXXNewExpr *expr,
874                                               QualType ElementType) {
875   assert(requiresArrayCookie(expr));
876 
877   // NewPtr is a char*.
878 
879   unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
880 
881   ASTContext &Ctx = getContext();
882   CharUnits SizeSize = Ctx.getTypeSizeInChars(Ctx.getSizeType());
883   llvm::IntegerType *SizeTy =
884     cast<llvm::IntegerType>(CGF.ConvertType(Ctx.getSizeType()));
885 
886   // The cookie is always at the start of the buffer.
887   llvm::Value *CookiePtr = NewPtr;
888 
889   // The first element is the element size.
890   CookiePtr = CGF.Builder.CreateBitCast(CookiePtr, SizeTy->getPointerTo(AS));
891   llvm::Value *ElementSize = llvm::ConstantInt::get(SizeTy,
892                           Ctx.getTypeSizeInChars(ElementType).getQuantity());
893   CGF.Builder.CreateStore(ElementSize, CookiePtr);
894 
895   // The second element is the element count.
896   CookiePtr = CGF.Builder.CreateConstInBoundsGEP1_32(CookiePtr, 1);
897   CGF.Builder.CreateStore(NumElements, CookiePtr);
898 
899   // Finally, compute a pointer to the actual data buffer by skipping
900   // over the cookie completely.
901   CharUnits CookieSize = 2 * SizeSize;
902   return CGF.Builder.CreateConstInBoundsGEP1_64(NewPtr,
903                                                 CookieSize.getQuantity());
904 }
905 
906 llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
907                                             llvm::Value *allocPtr,
908                                             CharUnits cookieSize) {
909   // The number of elements is at offset sizeof(size_t) relative to
910   // the allocated pointer.
911   llvm::Value *numElementsPtr
912     = CGF.Builder.CreateConstInBoundsGEP1_64(allocPtr, CGF.SizeSizeInBytes);
913 
914   unsigned AS = cast<llvm::PointerType>(allocPtr->getType())->getAddressSpace();
915   numElementsPtr =
916     CGF.Builder.CreateBitCast(numElementsPtr, CGF.SizeTy->getPointerTo(AS));
917   return CGF.Builder.CreateLoad(numElementsPtr);
918 }
919 
920 /*********************** Static local initialization **************************/
921 
922 static llvm::Constant *getGuardAcquireFn(CodeGenModule &CGM,
923                                          llvm::PointerType *GuardPtrTy) {
924   // int __cxa_guard_acquire(__guard *guard_object);
925   llvm::FunctionType *FTy =
926     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
927                             GuardPtrTy, /*isVarArg=*/false);
928 
929   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
930                                    llvm::Attribute::NoUnwind);
931 }
932 
933 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
934                                          llvm::PointerType *GuardPtrTy) {
935   // void __cxa_guard_release(__guard *guard_object);
936   llvm::FunctionType *FTy =
937     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
938 
939   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
940                                    llvm::Attribute::NoUnwind);
941 }
942 
943 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
944                                        llvm::PointerType *GuardPtrTy) {
945   // void __cxa_guard_abort(__guard *guard_object);
946   llvm::FunctionType *FTy =
947     llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
948 
949   return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
950                                    llvm::Attribute::NoUnwind);
951 }
952 
953 namespace {
954   struct CallGuardAbort : EHScopeStack::Cleanup {
955     llvm::GlobalVariable *Guard;
956     CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
957 
958     void Emit(CodeGenFunction &CGF, Flags flags) {
959       CGF.Builder.CreateCall(getGuardAbortFn(CGF.CGM, Guard->getType()), Guard)
960         ->setDoesNotThrow();
961     }
962   };
963 }
964 
965 /// The ARM code here follows the Itanium code closely enough that we
966 /// just special-case it at particular places.
967 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
968                                     const VarDecl &D,
969                                     llvm::GlobalVariable *var,
970                                     bool shouldPerformInit) {
971   CGBuilderTy &Builder = CGF.Builder;
972 
973   // We only need to use thread-safe statics for local variables;
974   // global initialization is always single-threaded.
975   bool threadsafe =
976     (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
977 
978   // If we have a global variable with internal linkage and thread-safe statics
979   // are disabled, we can just let the guard variable be of type i8.
980   bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
981 
982   llvm::IntegerType *guardTy;
983   if (useInt8GuardVariable) {
984     guardTy = CGF.Int8Ty;
985   } else {
986     // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
987     guardTy = (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
988   }
989   llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
990 
991   // Create the guard variable if we don't already have it (as we
992   // might if we're double-emitting this function body).
993   llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
994   if (!guard) {
995     // Mangle the name for the guard.
996     SmallString<256> guardName;
997     {
998       llvm::raw_svector_ostream out(guardName);
999       getMangleContext().mangleItaniumGuardVariable(&D, out);
1000       out.flush();
1001     }
1002 
1003     // Create the guard variable with a zero-initializer.
1004     // Just absorb linkage and visibility from the guarded variable.
1005     guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
1006                                      false, var->getLinkage(),
1007                                      llvm::ConstantInt::get(guardTy, 0),
1008                                      guardName.str());
1009     guard->setVisibility(var->getVisibility());
1010 
1011     CGM.setStaticLocalDeclGuardAddress(&D, guard);
1012   }
1013 
1014   // Test whether the variable has completed initialization.
1015   llvm::Value *isInitialized;
1016 
1017   // ARM C++ ABI 3.2.3.1:
1018   //   To support the potential use of initialization guard variables
1019   //   as semaphores that are the target of ARM SWP and LDREX/STREX
1020   //   synchronizing instructions we define a static initialization
1021   //   guard variable to be a 4-byte aligned, 4- byte word with the
1022   //   following inline access protocol.
1023   //     #define INITIALIZED 1
1024   //     if ((obj_guard & INITIALIZED) != INITIALIZED) {
1025   //       if (__cxa_guard_acquire(&obj_guard))
1026   //         ...
1027   //     }
1028   if (IsARM && !useInt8GuardVariable) {
1029     llvm::Value *V = Builder.CreateLoad(guard);
1030     V = Builder.CreateAnd(V, Builder.getInt32(1));
1031     isInitialized = Builder.CreateIsNull(V, "guard.uninitialized");
1032 
1033   // Itanium C++ ABI 3.3.2:
1034   //   The following is pseudo-code showing how these functions can be used:
1035   //     if (obj_guard.first_byte == 0) {
1036   //       if ( __cxa_guard_acquire (&obj_guard) ) {
1037   //         try {
1038   //           ... initialize the object ...;
1039   //         } catch (...) {
1040   //            __cxa_guard_abort (&obj_guard);
1041   //            throw;
1042   //         }
1043   //         ... queue object destructor with __cxa_atexit() ...;
1044   //         __cxa_guard_release (&obj_guard);
1045   //       }
1046   //     }
1047   } else {
1048     // Load the first byte of the guard variable.
1049     llvm::LoadInst *LI =
1050       Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
1051     LI->setAlignment(1);
1052 
1053     // Itanium ABI:
1054     //   An implementation supporting thread-safety on multiprocessor
1055     //   systems must also guarantee that references to the initialized
1056     //   object do not occur before the load of the initialization flag.
1057     //
1058     // In LLVM, we do this by marking the load Acquire.
1059     if (threadsafe)
1060       LI->setAtomic(llvm::Acquire);
1061 
1062     isInitialized = Builder.CreateIsNull(LI, "guard.uninitialized");
1063   }
1064 
1065   llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
1066   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1067 
1068   // Check if the first byte of the guard variable is zero.
1069   Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
1070 
1071   CGF.EmitBlock(InitCheckBlock);
1072 
1073   // Variables used when coping with thread-safe statics and exceptions.
1074   if (threadsafe) {
1075     // Call __cxa_guard_acquire.
1076     llvm::Value *V
1077       = Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
1078 
1079     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1080 
1081     Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
1082                          InitBlock, EndBlock);
1083 
1084     // Call __cxa_guard_abort along the exceptional edge.
1085     CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
1086 
1087     CGF.EmitBlock(InitBlock);
1088   }
1089 
1090   // Emit the initializer and add a global destructor if appropriate.
1091   CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
1092 
1093   if (threadsafe) {
1094     // Pop the guard-abort cleanup if we pushed one.
1095     CGF.PopCleanupBlock();
1096 
1097     // Call __cxa_guard_release.  This cannot throw.
1098     Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
1099   } else {
1100     Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
1101   }
1102 
1103   CGF.EmitBlock(EndBlock);
1104 }
1105 
1106 /// Register a global destructor using __cxa_atexit.
1107 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
1108                                         llvm::Constant *dtor,
1109                                         llvm::Constant *addr) {
1110   // We're assuming that the destructor function is something we can
1111   // reasonably call with the default CC.  Go ahead and cast it to the
1112   // right prototype.
1113   llvm::Type *dtorTy =
1114     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
1115 
1116   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
1117   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
1118   llvm::FunctionType *atexitTy =
1119     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
1120 
1121   // Fetch the actual function.
1122   llvm::Constant *atexit =
1123     CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
1124   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
1125     fn->setDoesNotThrow();
1126 
1127   // Create a variable that binds the atexit to this shared object.
1128   llvm::Constant *handle =
1129     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
1130 
1131   llvm::Value *args[] = {
1132     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
1133     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
1134     handle
1135   };
1136   CGF.Builder.CreateCall(atexit, args)->setDoesNotThrow();
1137 }
1138 
1139 /// Register a global destructor as best as we know how.
1140 void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
1141                                        llvm::Constant *dtor,
1142                                        llvm::Constant *addr) {
1143   // Use __cxa_atexit if available.
1144   if (CGM.getCodeGenOpts().CXAAtExit) {
1145     return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
1146   }
1147 
1148   // In Apple kexts, we want to add a global destructor entry.
1149   // FIXME: shouldn't this be guarded by some variable?
1150   if (CGM.getContext().getLangOpts().AppleKext) {
1151     // Generate a global destructor entry.
1152     return CGM.AddCXXDtorEntry(dtor, addr);
1153   }
1154 
1155   CGF.registerGlobalDtorWithAtExit(dtor, addr);
1156 }
1157 
1158 /// Generate and emit virtual tables for the given class.
1159 void ItaniumCXXABI::EmitVTables(const CXXRecordDecl *Class) {
1160   CGM.getVTables().GenerateClassData(CGM.getVTableLinkage(Class), Class);
1161 }
1162