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