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