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