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