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