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