1 //===--- MicrosoftCXXABI.cpp - Emit LLVM Code from ASTs for a Module ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides C++ code generation targeting the Microsoft Visual C++ ABI.
10 // The class in this file generates structures that follow the Microsoft
11 // Visual C++ ABI, which is actually not very well documented at all outside
12 // of Microsoft.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGVTables.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenTypes.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/VTableBuilder.h"
28 #include "clang/CodeGen/ConstantInitBuilder.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSet.h"
31 #include "llvm/IR/Intrinsics.h"
32 
33 using namespace clang;
34 using namespace CodeGen;
35 
36 namespace {
37 
38 /// Holds all the vbtable globals for a given class.
39 struct VBTableGlobals {
40   const VPtrInfoVector *VBTables;
41   SmallVector<llvm::GlobalVariable *, 2> Globals;
42 };
43 
44 class MicrosoftCXXABI : public CGCXXABI {
45 public:
46   MicrosoftCXXABI(CodeGenModule &CGM)
47       : CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
48         ClassHierarchyDescriptorType(nullptr),
49         CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
50         ThrowInfoType(nullptr) {}
51 
52   bool HasThisReturn(GlobalDecl GD) const override;
53   bool hasMostDerivedReturn(GlobalDecl GD) const override;
54 
55   bool classifyReturnType(CGFunctionInfo &FI) const override;
56 
57   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
58 
59   bool isSRetParameterAfterThis() const override { return true; }
60 
61   bool isThisCompleteObject(GlobalDecl GD) const override {
62     // The Microsoft ABI doesn't use separate complete-object vs.
63     // base-object variants of constructors, but it does of destructors.
64     if (isa<CXXDestructorDecl>(GD.getDecl())) {
65       switch (GD.getDtorType()) {
66       case Dtor_Complete:
67       case Dtor_Deleting:
68         return true;
69 
70       case Dtor_Base:
71         return false;
72 
73       case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
74       }
75       llvm_unreachable("bad dtor kind");
76     }
77 
78     // No other kinds.
79     return false;
80   }
81 
82   size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
83                               FunctionArgList &Args) const override {
84     assert(Args.size() >= 2 &&
85            "expected the arglist to have at least two args!");
86     // The 'most_derived' parameter goes second if the ctor is variadic and
87     // has v-bases.
88     if (CD->getParent()->getNumVBases() > 0 &&
89         CD->getType()->castAs<FunctionProtoType>()->isVariadic())
90       return 2;
91     return 1;
92   }
93 
94   std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
95     std::vector<CharUnits> VBPtrOffsets;
96     const ASTContext &Context = getContext();
97     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
98 
99     const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
100     for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
101       const ASTRecordLayout &SubobjectLayout =
102           Context.getASTRecordLayout(VBT->IntroducingObject);
103       CharUnits Offs = VBT->NonVirtualOffset;
104       Offs += SubobjectLayout.getVBPtrOffset();
105       if (VBT->getVBaseWithVPtr())
106         Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
107       VBPtrOffsets.push_back(Offs);
108     }
109     llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
110     return VBPtrOffsets;
111   }
112 
113   StringRef GetPureVirtualCallName() override { return "_purecall"; }
114   StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
115 
116   void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
117                                Address Ptr, QualType ElementType,
118                                const CXXDestructorDecl *Dtor) override;
119 
120   void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
121   void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
122 
123   void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
124 
125   llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
126                                                    const VPtrInfo &Info);
127 
128   llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
129   CatchTypeInfo
130   getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
131 
132   /// MSVC needs an extra flag to indicate a catchall.
133   CatchTypeInfo getCatchAllTypeInfo() override {
134     // For -EHa catch(...) must handle HW exception
135     // Adjective = HT_IsStdDotDot (0x40), only catch C++ exceptions
136     if (getContext().getLangOpts().EHAsynch)
137       return CatchTypeInfo{nullptr, 0};
138     else
139       return CatchTypeInfo{nullptr, 0x40};
140   }
141 
142   bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
143   void EmitBadTypeidCall(CodeGenFunction &CGF) override;
144   llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
145                           Address ThisPtr,
146                           llvm::Type *StdTypeInfoPtrTy) override;
147 
148   bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
149                                           QualType SrcRecordTy) override;
150 
151   llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
152                                    QualType SrcRecordTy, QualType DestTy,
153                                    QualType DestRecordTy,
154                                    llvm::BasicBlock *CastEnd) override;
155 
156   llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
157                                      QualType SrcRecordTy,
158                                      QualType DestTy) override;
159 
160   bool EmitBadCastCall(CodeGenFunction &CGF) override;
161   bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
162     return false;
163   }
164 
165   llvm::Value *
166   GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
167                             const CXXRecordDecl *ClassDecl,
168                             const CXXRecordDecl *BaseClassDecl) override;
169 
170   llvm::BasicBlock *
171   EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
172                                 const CXXRecordDecl *RD) override;
173 
174   llvm::BasicBlock *
175   EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
176 
177   void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
178                                               const CXXRecordDecl *RD) override;
179 
180   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
181 
182   // Background on MSVC destructors
183   // ==============================
184   //
185   // Both Itanium and MSVC ABIs have destructor variants.  The variant names
186   // roughly correspond in the following way:
187   //   Itanium       Microsoft
188   //   Base       -> no name, just ~Class
189   //   Complete   -> vbase destructor
190   //   Deleting   -> scalar deleting destructor
191   //                 vector deleting destructor
192   //
193   // The base and complete destructors are the same as in Itanium, although the
194   // complete destructor does not accept a VTT parameter when there are virtual
195   // bases.  A separate mechanism involving vtordisps is used to ensure that
196   // virtual methods of destroyed subobjects are not called.
197   //
198   // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
199   // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
200   // pointer points to an array.  The scalar deleting destructor assumes that
201   // bit 2 is zero, and therefore does not contain a loop.
202   //
203   // For virtual destructors, only one entry is reserved in the vftable, and it
204   // always points to the vector deleting destructor.  The vector deleting
205   // destructor is the most general, so it can be used to destroy objects in
206   // place, delete single heap objects, or delete arrays.
207   //
208   // A TU defining a non-inline destructor is only guaranteed to emit a base
209   // destructor, and all of the other variants are emitted on an as-needed basis
210   // in COMDATs.  Because a non-base destructor can be emitted in a TU that
211   // lacks a definition for the destructor, non-base destructors must always
212   // delegate to or alias the base destructor.
213 
214   AddedStructorArgCounts
215   buildStructorSignature(GlobalDecl GD,
216                          SmallVectorImpl<CanQualType> &ArgTys) override;
217 
218   /// Non-base dtors should be emitted as delegating thunks in this ABI.
219   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
220                               CXXDtorType DT) const override {
221     return DT != Dtor_Base;
222   }
223 
224   void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
225                                   const CXXDestructorDecl *Dtor,
226                                   CXXDtorType DT) const override;
227 
228   llvm::GlobalValue::LinkageTypes
229   getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
230                           CXXDtorType DT) const override;
231 
232   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
233 
234   const CXXRecordDecl *
235   getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
236     if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
237       MethodVFTableLocation ML =
238           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
239       // The vbases might be ordered differently in the final overrider object
240       // and the complete object, so the "this" argument may sometimes point to
241       // memory that has no particular type (e.g. past the complete object).
242       // In this case, we just use a generic pointer type.
243       // FIXME: might want to have a more precise type in the non-virtual
244       // multiple inheritance case.
245       if (ML.VBase || !ML.VFPtrOffset.isZero())
246         return nullptr;
247     }
248     return MD->getParent();
249   }
250 
251   Address
252   adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
253                                            Address This,
254                                            bool VirtualCall) override;
255 
256   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
257                                  FunctionArgList &Params) override;
258 
259   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
260 
261   AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
262                                                const CXXConstructorDecl *D,
263                                                CXXCtorType Type,
264                                                bool ForVirtualBase,
265                                                bool Delegating) override;
266 
267   llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
268                                              const CXXDestructorDecl *DD,
269                                              CXXDtorType Type,
270                                              bool ForVirtualBase,
271                                              bool Delegating) override;
272 
273   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
274                           CXXDtorType Type, bool ForVirtualBase,
275                           bool Delegating, Address This,
276                           QualType ThisTy) override;
277 
278   void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
279                               llvm::GlobalVariable *VTable);
280 
281   void emitVTableDefinitions(CodeGenVTables &CGVT,
282                              const CXXRecordDecl *RD) override;
283 
284   bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
285                                            CodeGenFunction::VPtr Vptr) override;
286 
287   /// Don't initialize vptrs if dynamic class
288   /// is marked with with the 'novtable' attribute.
289   bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
290     return !VTableClass->hasAttr<MSNoVTableAttr>();
291   }
292 
293   llvm::Constant *
294   getVTableAddressPoint(BaseSubobject Base,
295                         const CXXRecordDecl *VTableClass) override;
296 
297   llvm::Value *getVTableAddressPointInStructor(
298       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
299       BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
300 
301   llvm::Constant *
302   getVTableAddressPointForConstExpr(BaseSubobject Base,
303                                     const CXXRecordDecl *VTableClass) override;
304 
305   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
306                                         CharUnits VPtrOffset) override;
307 
308   CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
309                                      Address This, llvm::Type *Ty,
310                                      SourceLocation Loc) override;
311 
312   llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
313                                          const CXXDestructorDecl *Dtor,
314                                          CXXDtorType DtorType, Address This,
315                                          DeleteOrMemberCallExpr E) override;
316 
317   void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
318                                         CallArgList &CallArgs) override {
319     assert(GD.getDtorType() == Dtor_Deleting &&
320            "Only deleting destructor thunks are available in this ABI");
321     CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
322                  getContext().IntTy);
323   }
324 
325   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
326 
327   llvm::GlobalVariable *
328   getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
329                    llvm::GlobalVariable::LinkageTypes Linkage);
330 
331   llvm::GlobalVariable *
332   getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
333                                   const CXXRecordDecl *DstRD) {
334     SmallString<256> OutName;
335     llvm::raw_svector_ostream Out(OutName);
336     getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
337     StringRef MangledName = OutName.str();
338 
339     if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
340       return VDispMap;
341 
342     MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
343     unsigned NumEntries = 1 + SrcRD->getNumVBases();
344     SmallVector<llvm::Constant *, 4> Map(NumEntries,
345                                          llvm::UndefValue::get(CGM.IntTy));
346     Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
347     bool AnyDifferent = false;
348     for (const auto &I : SrcRD->vbases()) {
349       const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
350       if (!DstRD->isVirtuallyDerivedFrom(VBase))
351         continue;
352 
353       unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
354       unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
355       Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
356       AnyDifferent |= SrcVBIndex != DstVBIndex;
357     }
358     // This map would be useless, don't use it.
359     if (!AnyDifferent)
360       return nullptr;
361 
362     llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
363     llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
364     llvm::GlobalValue::LinkageTypes Linkage =
365         SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
366             ? llvm::GlobalValue::LinkOnceODRLinkage
367             : llvm::GlobalValue::InternalLinkage;
368     auto *VDispMap = new llvm::GlobalVariable(
369         CGM.getModule(), VDispMapTy, /*isConstant=*/true, Linkage,
370         /*Initializer=*/Init, MangledName);
371     return VDispMap;
372   }
373 
374   void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
375                              llvm::GlobalVariable *GV) const;
376 
377   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
378                        GlobalDecl GD, bool ReturnAdjustment) override {
379     GVALinkage Linkage =
380         getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
381 
382     if (Linkage == GVA_Internal)
383       Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
384     else if (ReturnAdjustment)
385       Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
386     else
387       Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
388   }
389 
390   bool exportThunk() override { return false; }
391 
392   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
393                                      const ThisAdjustment &TA) override;
394 
395   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
396                                        const ReturnAdjustment &RA) override;
397 
398   void EmitThreadLocalInitFuncs(
399       CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
400       ArrayRef<llvm::Function *> CXXThreadLocalInits,
401       ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
402 
403   bool usesThreadWrapperFunction(const VarDecl *VD) const override {
404     return getContext().getLangOpts().isCompatibleWithMSVC(
405                LangOptions::MSVC2019_5) &&
406            (!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
407   }
408   LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
409                                       QualType LValType) override;
410 
411   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
412                        llvm::GlobalVariable *DeclPtr,
413                        bool PerformInit) override;
414   void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
415                           llvm::FunctionCallee Dtor,
416                           llvm::Constant *Addr) override;
417 
418   // ==== Notes on array cookies =========
419   //
420   // MSVC seems to only use cookies when the class has a destructor; a
421   // two-argument usual array deallocation function isn't sufficient.
422   //
423   // For example, this code prints "100" and "1":
424   //   struct A {
425   //     char x;
426   //     void *operator new[](size_t sz) {
427   //       printf("%u\n", sz);
428   //       return malloc(sz);
429   //     }
430   //     void operator delete[](void *p, size_t sz) {
431   //       printf("%u\n", sz);
432   //       free(p);
433   //     }
434   //   };
435   //   int main() {
436   //     A *p = new A[100];
437   //     delete[] p;
438   //   }
439   // Whereas it prints "104" and "104" if you give A a destructor.
440 
441   bool requiresArrayCookie(const CXXDeleteExpr *expr,
442                            QualType elementType) override;
443   bool requiresArrayCookie(const CXXNewExpr *expr) override;
444   CharUnits getArrayCookieSizeImpl(QualType type) override;
445   Address InitializeArrayCookie(CodeGenFunction &CGF,
446                                 Address NewPtr,
447                                 llvm::Value *NumElements,
448                                 const CXXNewExpr *expr,
449                                 QualType ElementType) override;
450   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
451                                    Address allocPtr,
452                                    CharUnits cookieSize) override;
453 
454   friend struct MSRTTIBuilder;
455 
456   bool isImageRelative() const {
457     return CGM.getTarget().getPointerWidth(/*AddrSpace=*/0) == 64;
458   }
459 
460   // 5 routines for constructing the llvm types for MS RTTI structs.
461   llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
462     llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
463     TDTypeName += llvm::utostr(TypeInfoString.size());
464     llvm::StructType *&TypeDescriptorType =
465         TypeDescriptorTypeMap[TypeInfoString.size()];
466     if (TypeDescriptorType)
467       return TypeDescriptorType;
468     llvm::Type *FieldTypes[] = {
469         CGM.Int8PtrPtrTy,
470         CGM.Int8PtrTy,
471         llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
472     TypeDescriptorType =
473         llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
474     return TypeDescriptorType;
475   }
476 
477   llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
478     if (!isImageRelative())
479       return PtrType;
480     return CGM.IntTy;
481   }
482 
483   llvm::StructType *getBaseClassDescriptorType() {
484     if (BaseClassDescriptorType)
485       return BaseClassDescriptorType;
486     llvm::Type *FieldTypes[] = {
487         getImageRelativeType(CGM.Int8PtrTy),
488         CGM.IntTy,
489         CGM.IntTy,
490         CGM.IntTy,
491         CGM.IntTy,
492         CGM.IntTy,
493         getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
494     };
495     BaseClassDescriptorType = llvm::StructType::create(
496         CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
497     return BaseClassDescriptorType;
498   }
499 
500   llvm::StructType *getClassHierarchyDescriptorType() {
501     if (ClassHierarchyDescriptorType)
502       return ClassHierarchyDescriptorType;
503     // Forward-declare RTTIClassHierarchyDescriptor to break a cycle.
504     ClassHierarchyDescriptorType = llvm::StructType::create(
505         CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
506     llvm::Type *FieldTypes[] = {
507         CGM.IntTy,
508         CGM.IntTy,
509         CGM.IntTy,
510         getImageRelativeType(
511             getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
512     };
513     ClassHierarchyDescriptorType->setBody(FieldTypes);
514     return ClassHierarchyDescriptorType;
515   }
516 
517   llvm::StructType *getCompleteObjectLocatorType() {
518     if (CompleteObjectLocatorType)
519       return CompleteObjectLocatorType;
520     CompleteObjectLocatorType = llvm::StructType::create(
521         CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
522     llvm::Type *FieldTypes[] = {
523         CGM.IntTy,
524         CGM.IntTy,
525         CGM.IntTy,
526         getImageRelativeType(CGM.Int8PtrTy),
527         getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
528         getImageRelativeType(CompleteObjectLocatorType),
529     };
530     llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
531     if (!isImageRelative())
532       FieldTypesRef = FieldTypesRef.drop_back();
533     CompleteObjectLocatorType->setBody(FieldTypesRef);
534     return CompleteObjectLocatorType;
535   }
536 
537   llvm::GlobalVariable *getImageBase() {
538     StringRef Name = "__ImageBase";
539     if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
540       return GV;
541 
542     auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
543                                         /*isConstant=*/true,
544                                         llvm::GlobalValue::ExternalLinkage,
545                                         /*Initializer=*/nullptr, Name);
546     CGM.setDSOLocal(GV);
547     return GV;
548   }
549 
550   llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
551     if (!isImageRelative())
552       return PtrVal;
553 
554     if (PtrVal->isNullValue())
555       return llvm::Constant::getNullValue(CGM.IntTy);
556 
557     llvm::Constant *ImageBaseAsInt =
558         llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
559     llvm::Constant *PtrValAsInt =
560         llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
561     llvm::Constant *Diff =
562         llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
563                                    /*HasNUW=*/true, /*HasNSW=*/true);
564     return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
565   }
566 
567 private:
568   MicrosoftMangleContext &getMangleContext() {
569     return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
570   }
571 
572   llvm::Constant *getZeroInt() {
573     return llvm::ConstantInt::get(CGM.IntTy, 0);
574   }
575 
576   llvm::Constant *getAllOnesInt() {
577     return  llvm::Constant::getAllOnesValue(CGM.IntTy);
578   }
579 
580   CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
581 
582   void
583   GetNullMemberPointerFields(const MemberPointerType *MPT,
584                              llvm::SmallVectorImpl<llvm::Constant *> &fields);
585 
586   /// Shared code for virtual base adjustment.  Returns the offset from
587   /// the vbptr to the virtual base.  Optionally returns the address of the
588   /// vbptr itself.
589   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
590                                        Address Base,
591                                        llvm::Value *VBPtrOffset,
592                                        llvm::Value *VBTableOffset,
593                                        llvm::Value **VBPtr = nullptr);
594 
595   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
596                                        Address Base,
597                                        int32_t VBPtrOffset,
598                                        int32_t VBTableOffset,
599                                        llvm::Value **VBPtr = nullptr) {
600     assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
601     llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
602                 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
603     return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
604   }
605 
606   std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
607   performBaseAdjustment(CodeGenFunction &CGF, Address Value,
608                         QualType SrcRecordTy);
609 
610   /// Performs a full virtual base adjustment.  Used to dereference
611   /// pointers to members of virtual bases.
612   llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
613                                  const CXXRecordDecl *RD, Address Base,
614                                  llvm::Value *VirtualBaseAdjustmentOffset,
615                                  llvm::Value *VBPtrOffset /* optional */);
616 
617   /// Emits a full member pointer with the fields common to data and
618   /// function member pointers.
619   llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
620                                         bool IsMemberFunction,
621                                         const CXXRecordDecl *RD,
622                                         CharUnits NonVirtualBaseAdjustment,
623                                         unsigned VBTableIndex);
624 
625   bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
626                                    llvm::Constant *MP);
627 
628   /// - Initialize all vbptrs of 'this' with RD as the complete type.
629   void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
630 
631   /// Caching wrapper around VBTableBuilder::enumerateVBTables().
632   const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
633 
634   /// Generate a thunk for calling a virtual member function MD.
635   llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
636                                          const MethodVFTableLocation &ML);
637 
638   llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
639                                         CharUnits offset);
640 
641 public:
642   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
643 
644   bool isZeroInitializable(const MemberPointerType *MPT) override;
645 
646   bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
647     const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
648     return RD->hasAttr<MSInheritanceAttr>();
649   }
650 
651   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
652 
653   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
654                                         CharUnits offset) override;
655   llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
656   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
657 
658   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
659                                            llvm::Value *L,
660                                            llvm::Value *R,
661                                            const MemberPointerType *MPT,
662                                            bool Inequality) override;
663 
664   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
665                                           llvm::Value *MemPtr,
666                                           const MemberPointerType *MPT) override;
667 
668   llvm::Value *
669   EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
670                                Address Base, llvm::Value *MemPtr,
671                                const MemberPointerType *MPT) override;
672 
673   llvm::Value *EmitNonNullMemberPointerConversion(
674       const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
675       CastKind CK, CastExpr::path_const_iterator PathBegin,
676       CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
677       CGBuilderTy &Builder);
678 
679   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
680                                            const CastExpr *E,
681                                            llvm::Value *Src) override;
682 
683   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
684                                               llvm::Constant *Src) override;
685 
686   llvm::Constant *EmitMemberPointerConversion(
687       const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
688       CastKind CK, CastExpr::path_const_iterator PathBegin,
689       CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
690 
691   CGCallee
692   EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
693                                   Address This, llvm::Value *&ThisPtrForCall,
694                                   llvm::Value *MemPtr,
695                                   const MemberPointerType *MPT) override;
696 
697   void emitCXXStructor(GlobalDecl GD) override;
698 
699   llvm::StructType *getCatchableTypeType() {
700     if (CatchableTypeType)
701       return CatchableTypeType;
702     llvm::Type *FieldTypes[] = {
703         CGM.IntTy,                           // Flags
704         getImageRelativeType(CGM.Int8PtrTy), // TypeDescriptor
705         CGM.IntTy,                           // NonVirtualAdjustment
706         CGM.IntTy,                           // OffsetToVBPtr
707         CGM.IntTy,                           // VBTableIndex
708         CGM.IntTy,                           // Size
709         getImageRelativeType(CGM.Int8PtrTy)  // CopyCtor
710     };
711     CatchableTypeType = llvm::StructType::create(
712         CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
713     return CatchableTypeType;
714   }
715 
716   llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
717     llvm::StructType *&CatchableTypeArrayType =
718         CatchableTypeArrayTypeMap[NumEntries];
719     if (CatchableTypeArrayType)
720       return CatchableTypeArrayType;
721 
722     llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
723     CTATypeName += llvm::utostr(NumEntries);
724     llvm::Type *CTType =
725         getImageRelativeType(getCatchableTypeType()->getPointerTo());
726     llvm::Type *FieldTypes[] = {
727         CGM.IntTy,                               // NumEntries
728         llvm::ArrayType::get(CTType, NumEntries) // CatchableTypes
729     };
730     CatchableTypeArrayType =
731         llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
732     return CatchableTypeArrayType;
733   }
734 
735   llvm::StructType *getThrowInfoType() {
736     if (ThrowInfoType)
737       return ThrowInfoType;
738     llvm::Type *FieldTypes[] = {
739         CGM.IntTy,                           // Flags
740         getImageRelativeType(CGM.Int8PtrTy), // CleanupFn
741         getImageRelativeType(CGM.Int8PtrTy), // ForwardCompat
742         getImageRelativeType(CGM.Int8PtrTy)  // CatchableTypeArray
743     };
744     ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
745                                              "eh.ThrowInfo");
746     return ThrowInfoType;
747   }
748 
749   llvm::FunctionCallee getThrowFn() {
750     // _CxxThrowException is passed an exception object and a ThrowInfo object
751     // which describes the exception.
752     llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
753     llvm::FunctionType *FTy =
754         llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
755     llvm::FunctionCallee Throw =
756         CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
757     // _CxxThrowException is stdcall on 32-bit x86 platforms.
758     if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
759       if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
760         Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
761     }
762     return Throw;
763   }
764 
765   llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
766                                           CXXCtorType CT);
767 
768   llvm::Constant *getCatchableType(QualType T,
769                                    uint32_t NVOffset = 0,
770                                    int32_t VBPtrOffset = -1,
771                                    uint32_t VBIndex = 0);
772 
773   llvm::GlobalVariable *getCatchableTypeArray(QualType T);
774 
775   llvm::GlobalVariable *getThrowInfo(QualType T) override;
776 
777   std::pair<llvm::Value *, const CXXRecordDecl *>
778   LoadVTablePtr(CodeGenFunction &CGF, Address This,
779                 const CXXRecordDecl *RD) override;
780 
781   virtual bool
782   isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
783 
784 private:
785   typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
786   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
787   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
788   /// All the vftables that have been referenced.
789   VFTablesMapTy VFTablesMap;
790   VTablesMapTy VTablesMap;
791 
792   /// This set holds the record decls we've deferred vtable emission for.
793   llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
794 
795 
796   /// All the vbtables which have been referenced.
797   llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
798 
799   /// Info on the global variable used to guard initialization of static locals.
800   /// The BitIndex field is only used for externally invisible declarations.
801   struct GuardInfo {
802     GuardInfo() : Guard(nullptr), BitIndex(0) {}
803     llvm::GlobalVariable *Guard;
804     unsigned BitIndex;
805   };
806 
807   /// Map from DeclContext to the current guard variable.  We assume that the
808   /// AST is visited in source code order.
809   llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
810   llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
811   llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
812 
813   llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
814   llvm::StructType *BaseClassDescriptorType;
815   llvm::StructType *ClassHierarchyDescriptorType;
816   llvm::StructType *CompleteObjectLocatorType;
817 
818   llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
819 
820   llvm::StructType *CatchableTypeType;
821   llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
822   llvm::StructType *ThrowInfoType;
823 };
824 
825 }
826 
827 CGCXXABI::RecordArgABI
828 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
829   // Use the default C calling convention rules for things that can be passed in
830   // registers, i.e. non-trivially copyable records or records marked with
831   // [[trivial_abi]].
832   if (RD->canPassInRegisters())
833     return RAA_Default;
834 
835   switch (CGM.getTarget().getTriple().getArch()) {
836   default:
837     // FIXME: Implement for other architectures.
838     return RAA_Indirect;
839 
840   case llvm::Triple::thumb:
841     // Pass things indirectly for now because it is simple.
842     // FIXME: This is incompatible with MSVC for arguments with a dtor and no
843     // copy ctor.
844     return RAA_Indirect;
845 
846   case llvm::Triple::x86: {
847     // If the argument has *required* alignment greater than four bytes, pass
848     // it indirectly. Prior to MSVC version 19.14, passing overaligned
849     // arguments was not supported and resulted in a compiler error. In 19.14
850     // and later versions, such arguments are now passed indirectly.
851     TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
852     if (Info.isAlignRequired() && Info.Align > 4)
853       return RAA_Indirect;
854 
855     // If C++ prohibits us from making a copy, construct the arguments directly
856     // into argument memory.
857     return RAA_DirectInMemory;
858   }
859 
860   case llvm::Triple::x86_64:
861   case llvm::Triple::aarch64:
862     return RAA_Indirect;
863   }
864 
865   llvm_unreachable("invalid enum");
866 }
867 
868 void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
869                                               const CXXDeleteExpr *DE,
870                                               Address Ptr,
871                                               QualType ElementType,
872                                               const CXXDestructorDecl *Dtor) {
873   // FIXME: Provide a source location here even though there's no
874   // CXXMemberCallExpr for dtor call.
875   bool UseGlobalDelete = DE->isGlobalDelete();
876   CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
877   llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
878   if (UseGlobalDelete)
879     CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
880 }
881 
882 void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
883   llvm::Value *Args[] = {
884       llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
885       llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
886   llvm::FunctionCallee Fn = getThrowFn();
887   if (isNoReturn)
888     CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
889   else
890     CGF.EmitRuntimeCallOrInvoke(Fn, Args);
891 }
892 
893 void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
894                                      const CXXCatchStmt *S) {
895   // In the MS ABI, the runtime handles the copy, and the catch handler is
896   // responsible for destruction.
897   VarDecl *CatchParam = S->getExceptionDecl();
898   llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
899   llvm::CatchPadInst *CPI =
900       cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
901   CGF.CurrentFuncletPad = CPI;
902 
903   // If this is a catch-all or the catch parameter is unnamed, we don't need to
904   // emit an alloca to the object.
905   if (!CatchParam || !CatchParam->getDeclName()) {
906     CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
907     return;
908   }
909 
910   CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
911   CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
912   CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
913   CGF.EmitAutoVarCleanups(var);
914 }
915 
916 /// We need to perform a generic polymorphic operation (like a typeid
917 /// or a cast), which requires an object with a vfptr.  Adjust the
918 /// address to point to an object with a vfptr.
919 std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
920 MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
921                                        QualType SrcRecordTy) {
922   Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
923   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
924   const ASTContext &Context = getContext();
925 
926   // If the class itself has a vfptr, great.  This check implicitly
927   // covers non-virtual base subobjects: a class with its own virtual
928   // functions would be a candidate to be a primary base.
929   if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
930     return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
931                            SrcDecl);
932 
933   // Okay, one of the vbases must have a vfptr, or else this isn't
934   // actually a polymorphic class.
935   const CXXRecordDecl *PolymorphicBase = nullptr;
936   for (auto &Base : SrcDecl->vbases()) {
937     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
938     if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
939       PolymorphicBase = BaseDecl;
940       break;
941     }
942   }
943   assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
944 
945   llvm::Value *Offset =
946     GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
947   llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
948       Value.getElementType(), Value.getPointer(), Offset);
949   CharUnits VBaseAlign =
950     CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
951   return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
952                          PolymorphicBase);
953 }
954 
955 bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
956                                                 QualType SrcRecordTy) {
957   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
958   return IsDeref &&
959          !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
960 }
961 
962 static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
963                                         llvm::Value *Argument) {
964   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
965   llvm::FunctionType *FTy =
966       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
967   llvm::Value *Args[] = {Argument};
968   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
969   return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
970 }
971 
972 void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
973   llvm::CallBase *Call =
974       emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
975   Call->setDoesNotReturn();
976   CGF.Builder.CreateUnreachable();
977 }
978 
979 llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
980                                          QualType SrcRecordTy,
981                                          Address ThisPtr,
982                                          llvm::Type *StdTypeInfoPtrTy) {
983   std::tie(ThisPtr, std::ignore, std::ignore) =
984       performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
985   llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
986   return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
987 }
988 
989 bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
990                                                          QualType SrcRecordTy) {
991   const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
992   return SrcIsPtr &&
993          !getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
994 }
995 
996 llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
997     CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
998     QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
999   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1000 
1001   llvm::Value *SrcRTTI =
1002       CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1003   llvm::Value *DestRTTI =
1004       CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1005 
1006   llvm::Value *Offset;
1007   std::tie(This, Offset, std::ignore) =
1008       performBaseAdjustment(CGF, This, SrcRecordTy);
1009   llvm::Value *ThisPtr = This.getPointer();
1010   Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
1011 
1012   // PVOID __RTDynamicCast(
1013   //   PVOID inptr,
1014   //   LONG VfDelta,
1015   //   PVOID SrcType,
1016   //   PVOID TargetType,
1017   //   BOOL isReference)
1018   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
1019                             CGF.Int8PtrTy, CGF.Int32Ty};
1020   llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1021       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1022       "__RTDynamicCast");
1023   llvm::Value *Args[] = {
1024       ThisPtr, Offset, SrcRTTI, DestRTTI,
1025       llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
1026   ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
1027   return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
1028 }
1029 
1030 llvm::Value *
1031 MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
1032                                        QualType SrcRecordTy,
1033                                        QualType DestTy) {
1034   std::tie(Value, std::ignore, std::ignore) =
1035       performBaseAdjustment(CGF, Value, SrcRecordTy);
1036 
1037   // PVOID __RTCastToVoid(
1038   //   PVOID inptr)
1039   llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
1040   llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
1041       llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
1042       "__RTCastToVoid");
1043   llvm::Value *Args[] = {Value.getPointer()};
1044   return CGF.EmitRuntimeCall(Function, Args);
1045 }
1046 
1047 bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
1048   return false;
1049 }
1050 
1051 llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
1052     CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
1053     const CXXRecordDecl *BaseClassDecl) {
1054   const ASTContext &Context = getContext();
1055   int64_t VBPtrChars =
1056       Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
1057   llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
1058   CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
1059   CharUnits VBTableChars =
1060       IntSize *
1061       CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
1062   llvm::Value *VBTableOffset =
1063       llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
1064 
1065   llvm::Value *VBPtrToNewBase =
1066       GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
1067   VBPtrToNewBase =
1068       CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
1069   return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
1070 }
1071 
1072 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
1073   return isa<CXXConstructorDecl>(GD.getDecl());
1074 }
1075 
1076 static bool isDeletingDtor(GlobalDecl GD) {
1077   return isa<CXXDestructorDecl>(GD.getDecl()) &&
1078          GD.getDtorType() == Dtor_Deleting;
1079 }
1080 
1081 bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
1082   return isDeletingDtor(GD);
1083 }
1084 
1085 static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
1086   // For AArch64, we use the C++14 definition of an aggregate, so we also
1087   // check for:
1088   //   No private or protected non static data members.
1089   //   No base classes
1090   //   No virtual functions
1091   // Additionally, we need to ensure that there is a trivial copy assignment
1092   // operator, a trivial destructor and no user-provided constructors.
1093   if (RD->hasProtectedFields() || RD->hasPrivateFields())
1094     return false;
1095   if (RD->getNumBases() > 0)
1096     return false;
1097   if (RD->isPolymorphic())
1098     return false;
1099   if (RD->hasNonTrivialCopyAssignment())
1100     return false;
1101   for (const CXXConstructorDecl *Ctor : RD->ctors())
1102     if (Ctor->isUserProvided())
1103       return false;
1104   if (RD->hasNonTrivialDestructor())
1105     return false;
1106   return true;
1107 }
1108 
1109 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
1110   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
1111   if (!RD)
1112     return false;
1113 
1114   // Normally, the C++ concept of "is trivially copyable" is used to determine
1115   // if a struct can be returned directly. However, as MSVC and the language
1116   // have evolved, the definition of "trivially copyable" has changed, while the
1117   // ABI must remain stable. AArch64 uses the C++14 concept of an "aggregate",
1118   // while other ISAs use the older concept of "plain old data".
1119   bool isTrivialForABI = RD->isPOD();
1120   bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
1121   if (isAArch64)
1122     isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
1123 
1124   // MSVC always returns structs indirectly from C++ instance methods.
1125   bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
1126 
1127   if (isIndirectReturn) {
1128     CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
1129     FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
1130 
1131     // MSVC always passes `this` before the `sret` parameter.
1132     FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
1133 
1134     // On AArch64, use the `inreg` attribute if the object is considered to not
1135     // be trivially copyable, or if this is an instance method struct return.
1136     FI.getReturnInfo().setInReg(isAArch64);
1137 
1138     return true;
1139   }
1140 
1141   // Otherwise, use the C ABI rules.
1142   return false;
1143 }
1144 
1145 llvm::BasicBlock *
1146 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
1147                                                const CXXRecordDecl *RD) {
1148   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1149   assert(IsMostDerivedClass &&
1150          "ctor for a class with virtual bases must have an implicit parameter");
1151   llvm::Value *IsCompleteObject =
1152     CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1153 
1154   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
1155   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
1156   CGF.Builder.CreateCondBr(IsCompleteObject,
1157                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
1158 
1159   CGF.EmitBlock(CallVbaseCtorsBB);
1160 
1161   // Fill in the vbtable pointers here.
1162   EmitVBPtrStores(CGF, RD);
1163 
1164   // CGF will put the base ctor calls in this basic block for us later.
1165 
1166   return SkipVbaseCtorsBB;
1167 }
1168 
1169 llvm::BasicBlock *
1170 MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
1171   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
1172   assert(IsMostDerivedClass &&
1173          "ctor for a class with virtual bases must have an implicit parameter");
1174   llvm::Value *IsCompleteObject =
1175       CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
1176 
1177   llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
1178   llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
1179   CGF.Builder.CreateCondBr(IsCompleteObject,
1180                            CallVbaseDtorsBB, SkipVbaseDtorsBB);
1181 
1182   CGF.EmitBlock(CallVbaseDtorsBB);
1183   // CGF will put the base dtor calls in this basic block for us later.
1184 
1185   return SkipVbaseDtorsBB;
1186 }
1187 
1188 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
1189     CodeGenFunction &CGF, const CXXRecordDecl *RD) {
1190   // In most cases, an override for a vbase virtual method can adjust
1191   // the "this" parameter by applying a constant offset.
1192   // However, this is not enough while a constructor or a destructor of some
1193   // class X is being executed if all the following conditions are met:
1194   //  - X has virtual bases, (1)
1195   //  - X overrides a virtual method M of a vbase Y, (2)
1196   //  - X itself is a vbase of the most derived class.
1197   //
1198   // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
1199   // which holds the extra amount of "this" adjustment we must do when we use
1200   // the X vftables (i.e. during X ctor or dtor).
1201   // Outside the ctors and dtors, the values of vtorDisps are zero.
1202 
1203   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1204   typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
1205   const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
1206   CGBuilderTy &Builder = CGF.Builder;
1207 
1208   unsigned AS = getThisAddress(CGF).getAddressSpace();
1209   llvm::Value *Int8This = nullptr;  // Initialize lazily.
1210 
1211   for (const CXXBaseSpecifier &S : RD->vbases()) {
1212     const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
1213     auto I = VBaseMap.find(VBase);
1214     assert(I != VBaseMap.end());
1215     if (!I->second.hasVtorDisp())
1216       continue;
1217 
1218     llvm::Value *VBaseOffset =
1219         GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
1220     uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
1221 
1222     // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
1223     llvm::Value *VtorDispValue = Builder.CreateSub(
1224         VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
1225         "vtordisp.value");
1226     VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
1227 
1228     if (!Int8This)
1229       Int8This = Builder.CreateBitCast(getThisValue(CGF),
1230                                        CGF.Int8Ty->getPointerTo(AS));
1231     llvm::Value *VtorDispPtr =
1232         Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
1233     // vtorDisp is always the 32-bits before the vbase in the class layout.
1234     VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
1235     VtorDispPtr = Builder.CreateBitCast(
1236         VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
1237 
1238     Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
1239                                CharUnits::fromQuantity(4));
1240   }
1241 }
1242 
1243 static bool hasDefaultCXXMethodCC(ASTContext &Context,
1244                                   const CXXMethodDecl *MD) {
1245   CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
1246       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
1247   CallingConv ActualCallingConv =
1248       MD->getType()->castAs<FunctionProtoType>()->getCallConv();
1249   return ExpectedCallingConv == ActualCallingConv;
1250 }
1251 
1252 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
1253   // There's only one constructor type in this ABI.
1254   CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
1255 
1256   // Exported default constructors either have a simple call-site where they use
1257   // the typical calling convention and have a single 'this' pointer for an
1258   // argument -or- they get a wrapper function which appropriately thunks to the
1259   // real default constructor.  This thunk is the default constructor closure.
1260   if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
1261       D->isDefined()) {
1262     if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
1263       llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
1264       Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
1265       CGM.setGVProperties(Fn, D);
1266     }
1267   }
1268 }
1269 
1270 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
1271                                       const CXXRecordDecl *RD) {
1272   Address This = getThisAddress(CGF);
1273   This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
1274   const ASTContext &Context = getContext();
1275   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1276 
1277   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1278   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1279     const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
1280     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1281     const ASTRecordLayout &SubobjectLayout =
1282         Context.getASTRecordLayout(VBT->IntroducingObject);
1283     CharUnits Offs = VBT->NonVirtualOffset;
1284     Offs += SubobjectLayout.getVBPtrOffset();
1285     if (VBT->getVBaseWithVPtr())
1286       Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
1287     Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
1288     llvm::Value *GVPtr =
1289         CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
1290     VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
1291                                       "vbptr." + VBT->ObjectWithVPtr->getName());
1292     CGF.Builder.CreateStore(GVPtr, VBPtr);
1293   }
1294 }
1295 
1296 CGCXXABI::AddedStructorArgCounts
1297 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
1298                                         SmallVectorImpl<CanQualType> &ArgTys) {
1299   AddedStructorArgCounts Added;
1300   // TODO: 'for base' flag
1301   if (isa<CXXDestructorDecl>(GD.getDecl()) &&
1302       GD.getDtorType() == Dtor_Deleting) {
1303     // The scalar deleting destructor takes an implicit int parameter.
1304     ArgTys.push_back(getContext().IntTy);
1305     ++Added.Suffix;
1306   }
1307   auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
1308   if (!CD)
1309     return Added;
1310 
1311   // All parameters are already in place except is_most_derived, which goes
1312   // after 'this' if it's variadic and last if it's not.
1313 
1314   const CXXRecordDecl *Class = CD->getParent();
1315   const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
1316   if (Class->getNumVBases()) {
1317     if (FPT->isVariadic()) {
1318       ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
1319       ++Added.Prefix;
1320     } else {
1321       ArgTys.push_back(getContext().IntTy);
1322       ++Added.Suffix;
1323     }
1324   }
1325 
1326   return Added;
1327 }
1328 
1329 void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
1330                                                  const CXXDestructorDecl *Dtor,
1331                                                  CXXDtorType DT) const {
1332   // Deleting destructor variants are never imported or exported. Give them the
1333   // default storage class.
1334   if (DT == Dtor_Deleting) {
1335     GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1336   } else {
1337     const NamedDecl *ND = Dtor;
1338     CGM.setDLLImportDLLExport(GV, ND);
1339   }
1340 }
1341 
1342 llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
1343     GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
1344   // Internal things are always internal, regardless of attributes. After this,
1345   // we know the thunk is externally visible.
1346   if (Linkage == GVA_Internal)
1347     return llvm::GlobalValue::InternalLinkage;
1348 
1349   switch (DT) {
1350   case Dtor_Base:
1351     // The base destructor most closely tracks the user-declared constructor, so
1352     // we delegate back to the normal declarator case.
1353     return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
1354                                            /*IsConstantVariable=*/false);
1355   case Dtor_Complete:
1356     // The complete destructor is like an inline function, but it may be
1357     // imported and therefore must be exported as well. This requires changing
1358     // the linkage if a DLL attribute is present.
1359     if (Dtor->hasAttr<DLLExportAttr>())
1360       return llvm::GlobalValue::WeakODRLinkage;
1361     if (Dtor->hasAttr<DLLImportAttr>())
1362       return llvm::GlobalValue::AvailableExternallyLinkage;
1363     return llvm::GlobalValue::LinkOnceODRLinkage;
1364   case Dtor_Deleting:
1365     // Deleting destructors are like inline functions. They have vague linkage
1366     // and are emitted everywhere they are used. They are internal if the class
1367     // is internal.
1368     return llvm::GlobalValue::LinkOnceODRLinkage;
1369   case Dtor_Comdat:
1370     llvm_unreachable("MS C++ ABI does not support comdat dtors");
1371   }
1372   llvm_unreachable("invalid dtor type");
1373 }
1374 
1375 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
1376   // The TU defining a dtor is only guaranteed to emit a base destructor.  All
1377   // other destructor variants are delegating thunks.
1378   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
1379 
1380   // If the class is dllexported, emit the complete (vbase) destructor wherever
1381   // the base dtor is emitted.
1382   // FIXME: To match MSVC, this should only be done when the class is exported
1383   // with -fdllexport-inlines enabled.
1384   if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
1385     CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
1386 }
1387 
1388 CharUnits
1389 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
1390   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1391 
1392   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1393     // Complete destructors take a pointer to the complete object as a
1394     // parameter, thus don't need this adjustment.
1395     if (GD.getDtorType() == Dtor_Complete)
1396       return CharUnits();
1397 
1398     // There's no Dtor_Base in vftable but it shares the this adjustment with
1399     // the deleting one, so look it up instead.
1400     GD = GlobalDecl(DD, Dtor_Deleting);
1401   }
1402 
1403   MethodVFTableLocation ML =
1404       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1405   CharUnits Adjustment = ML.VFPtrOffset;
1406 
1407   // Normal virtual instance methods need to adjust from the vfptr that first
1408   // defined the virtual method to the virtual base subobject, but destructors
1409   // do not.  The vector deleting destructor thunk applies this adjustment for
1410   // us if necessary.
1411   if (isa<CXXDestructorDecl>(MD))
1412     Adjustment = CharUnits::Zero();
1413 
1414   if (ML.VBase) {
1415     const ASTRecordLayout &DerivedLayout =
1416         getContext().getASTRecordLayout(MD->getParent());
1417     Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
1418   }
1419 
1420   return Adjustment;
1421 }
1422 
1423 Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
1424     CodeGenFunction &CGF, GlobalDecl GD, Address This,
1425     bool VirtualCall) {
1426   if (!VirtualCall) {
1427     // If the call of a virtual function is not virtual, we just have to
1428     // compensate for the adjustment the virtual function does in its prologue.
1429     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
1430     if (Adjustment.isZero())
1431       return This;
1432 
1433     This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
1434     assert(Adjustment.isPositive());
1435     return CGF.Builder.CreateConstByteGEP(This, Adjustment);
1436   }
1437 
1438   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1439 
1440   GlobalDecl LookupGD = GD;
1441   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
1442     // Complete dtors take a pointer to the complete object,
1443     // thus don't need adjustment.
1444     if (GD.getDtorType() == Dtor_Complete)
1445       return This;
1446 
1447     // There's only Dtor_Deleting in vftable but it shares the this adjustment
1448     // with the base one, so look up the deleting one instead.
1449     LookupGD = GlobalDecl(DD, Dtor_Deleting);
1450   }
1451   MethodVFTableLocation ML =
1452       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
1453 
1454   CharUnits StaticOffset = ML.VFPtrOffset;
1455 
1456   // Base destructors expect 'this' to point to the beginning of the base
1457   // subobject, not the first vfptr that happens to contain the virtual dtor.
1458   // However, we still need to apply the virtual base adjustment.
1459   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
1460     StaticOffset = CharUnits::Zero();
1461 
1462   Address Result = This;
1463   if (ML.VBase) {
1464     Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1465 
1466     const CXXRecordDecl *Derived = MD->getParent();
1467     const CXXRecordDecl *VBase = ML.VBase;
1468     llvm::Value *VBaseOffset =
1469       GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
1470     llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
1471         Result.getElementType(), Result.getPointer(), VBaseOffset);
1472     CharUnits VBaseAlign =
1473       CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
1474     Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
1475   }
1476   if (!StaticOffset.isZero()) {
1477     assert(StaticOffset.isPositive());
1478     Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
1479     if (ML.VBase) {
1480       // Non-virtual adjustment might result in a pointer outside the allocated
1481       // object, e.g. if the final overrider class is laid out after the virtual
1482       // base that declares a method in the most derived class.
1483       // FIXME: Update the code that emits this adjustment in thunks prologues.
1484       Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
1485     } else {
1486       Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
1487     }
1488   }
1489   return Result;
1490 }
1491 
1492 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
1493                                                 QualType &ResTy,
1494                                                 FunctionArgList &Params) {
1495   ASTContext &Context = getContext();
1496   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1497   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
1498   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1499     auto *IsMostDerived = ImplicitParamDecl::Create(
1500         Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1501         &Context.Idents.get("is_most_derived"), Context.IntTy,
1502         ImplicitParamDecl::Other);
1503     // The 'most_derived' parameter goes second if the ctor is variadic and last
1504     // if it's not.  Dtors can't be variadic.
1505     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1506     if (FPT->isVariadic())
1507       Params.insert(Params.begin() + 1, IsMostDerived);
1508     else
1509       Params.push_back(IsMostDerived);
1510     getStructorImplicitParamDecl(CGF) = IsMostDerived;
1511   } else if (isDeletingDtor(CGF.CurGD)) {
1512     auto *ShouldDelete = ImplicitParamDecl::Create(
1513         Context, /*DC=*/nullptr, CGF.CurGD.getDecl()->getLocation(),
1514         &Context.Idents.get("should_call_delete"), Context.IntTy,
1515         ImplicitParamDecl::Other);
1516     Params.push_back(ShouldDelete);
1517     getStructorImplicitParamDecl(CGF) = ShouldDelete;
1518   }
1519 }
1520 
1521 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
1522   // Naked functions have no prolog.
1523   if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
1524     return;
1525 
1526   // Overridden virtual methods of non-primary bases need to adjust the incoming
1527   // 'this' pointer in the prologue. In this hierarchy, C::b will subtract
1528   // sizeof(void*) to adjust from B* to C*:
1529   //   struct A { virtual void a(); };
1530   //   struct B { virtual void b(); };
1531   //   struct C : A, B { virtual void b(); };
1532   //
1533   // Leave the value stored in the 'this' alloca unadjusted, so that the
1534   // debugger sees the unadjusted value. Microsoft debuggers require this, and
1535   // will apply the ThisAdjustment in the method type information.
1536   // FIXME: Do something better for DWARF debuggers, which won't expect this,
1537   // without making our codegen depend on debug info settings.
1538   llvm::Value *This = loadIncomingCXXThis(CGF);
1539   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
1540   if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
1541     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
1542     if (!Adjustment.isZero()) {
1543       unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
1544       llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
1545                  *thisTy = This->getType();
1546       This = CGF.Builder.CreateBitCast(This, charPtrTy);
1547       assert(Adjustment.isPositive());
1548       This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
1549                                                     -Adjustment.getQuantity());
1550       This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
1551     }
1552   }
1553   setCXXABIThisValue(CGF, This);
1554 
1555   // If this is a function that the ABI specifies returns 'this', initialize
1556   // the return slot to 'this' at the start of the function.
1557   //
1558   // Unlike the setting of return types, this is done within the ABI
1559   // implementation instead of by clients of CGCXXABI because:
1560   // 1) getThisValue is currently protected
1561   // 2) in theory, an ABI could implement 'this' returns some other way;
1562   //    HasThisReturn only specifies a contract, not the implementation
1563   if (HasThisReturn(CGF.CurGD))
1564     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
1565   else if (hasMostDerivedReturn(CGF.CurGD))
1566     CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
1567                             CGF.ReturnValue);
1568 
1569   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
1570     assert(getStructorImplicitParamDecl(CGF) &&
1571            "no implicit parameter for a constructor with virtual bases?");
1572     getStructorImplicitParamValue(CGF)
1573       = CGF.Builder.CreateLoad(
1574           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1575           "is_most_derived");
1576   }
1577 
1578   if (isDeletingDtor(CGF.CurGD)) {
1579     assert(getStructorImplicitParamDecl(CGF) &&
1580            "no implicit parameter for a deleting destructor?");
1581     getStructorImplicitParamValue(CGF)
1582       = CGF.Builder.CreateLoad(
1583           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
1584           "should_call_delete");
1585   }
1586 }
1587 
1588 CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
1589     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
1590     bool ForVirtualBase, bool Delegating) {
1591   assert(Type == Ctor_Complete || Type == Ctor_Base);
1592 
1593   // Check if we need a 'most_derived' parameter.
1594   if (!D->getParent()->getNumVBases())
1595     return AddedStructorArgs{};
1596 
1597   // Add the 'most_derived' argument second if we are variadic or last if not.
1598   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1599   llvm::Value *MostDerivedArg;
1600   if (Delegating) {
1601     MostDerivedArg = getStructorImplicitParamValue(CGF);
1602   } else {
1603     MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
1604   }
1605   if (FPT->isVariadic()) {
1606     return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
1607   }
1608   return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
1609 }
1610 
1611 llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
1612     CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
1613     bool ForVirtualBase, bool Delegating) {
1614   return nullptr;
1615 }
1616 
1617 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
1618                                          const CXXDestructorDecl *DD,
1619                                          CXXDtorType Type, bool ForVirtualBase,
1620                                          bool Delegating, Address This,
1621                                          QualType ThisTy) {
1622   // Use the base destructor variant in place of the complete destructor variant
1623   // if the class has no virtual bases. This effectively implements some of the
1624   // -mconstructor-aliases optimization, but as part of the MS C++ ABI.
1625   if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
1626     Type = Dtor_Base;
1627 
1628   GlobalDecl GD(DD, Type);
1629   CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
1630 
1631   if (DD->isVirtual()) {
1632     assert(Type != CXXDtorType::Dtor_Deleting &&
1633            "The deleting destructor should only be called via a virtual call");
1634     This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
1635                                                     This, false);
1636   }
1637 
1638   llvm::BasicBlock *BaseDtorEndBB = nullptr;
1639   if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
1640     BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
1641   }
1642 
1643   llvm::Value *Implicit =
1644       getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
1645                                     Delegating); // = nullptr
1646   CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1647                             /*ImplicitParam=*/Implicit,
1648                             /*ImplicitParamTy=*/QualType(), nullptr);
1649   if (BaseDtorEndBB) {
1650     // Complete object handler should continue to be the remaining
1651     CGF.Builder.CreateBr(BaseDtorEndBB);
1652     CGF.EmitBlock(BaseDtorEndBB);
1653   }
1654 }
1655 
1656 void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
1657                                              const CXXRecordDecl *RD,
1658                                              llvm::GlobalVariable *VTable) {
1659   if (!CGM.getCodeGenOpts().LTOUnit)
1660     return;
1661 
1662   // TODO: Should VirtualFunctionElimination also be supported here?
1663   // See similar handling in CodeGenModule::EmitVTableTypeMetadata.
1664   if (CGM.getCodeGenOpts().WholeProgramVTables) {
1665     llvm::DenseSet<const CXXRecordDecl *> Visited;
1666     llvm::GlobalObject::VCallVisibility TypeVis =
1667         CGM.GetVCallVisibilityLevel(RD, Visited);
1668     if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1669       VTable->setVCallVisibilityMetadata(TypeVis);
1670   }
1671 
1672   // The location of the first virtual function pointer in the virtual table,
1673   // aka the "address point" on Itanium. This is at offset 0 if RTTI is
1674   // disabled, or sizeof(void*) if RTTI is enabled.
1675   CharUnits AddressPoint =
1676       getContext().getLangOpts().RTTIData
1677           ? getContext().toCharUnitsFromBits(
1678                 getContext().getTargetInfo().getPointerWidth(0))
1679           : CharUnits::Zero();
1680 
1681   if (Info.PathToIntroducingObject.empty()) {
1682     CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1683     return;
1684   }
1685 
1686   // Add a bitset entry for the least derived base belonging to this vftable.
1687   CGM.AddVTableTypeMetadata(VTable, AddressPoint,
1688                             Info.PathToIntroducingObject.back());
1689 
1690   // Add a bitset entry for each derived class that is laid out at the same
1691   // offset as the least derived base.
1692   for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
1693     const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
1694     const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
1695 
1696     const ASTRecordLayout &Layout =
1697         getContext().getASTRecordLayout(DerivedRD);
1698     CharUnits Offset;
1699     auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
1700     if (VBI == Layout.getVBaseOffsetsMap().end())
1701       Offset = Layout.getBaseClassOffset(BaseRD);
1702     else
1703       Offset = VBI->second.VBaseOffset;
1704     if (!Offset.isZero())
1705       return;
1706     CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
1707   }
1708 
1709   // Finally do the same for the most derived class.
1710   if (Info.FullOffsetInMDC.isZero())
1711     CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
1712 }
1713 
1714 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
1715                                             const CXXRecordDecl *RD) {
1716   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1717   const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
1718 
1719   for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
1720     llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
1721     if (VTable->hasInitializer())
1722       continue;
1723 
1724     const VTableLayout &VTLayout =
1725       VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
1726 
1727     llvm::Constant *RTTI = nullptr;
1728     if (any_of(VTLayout.vtable_components(),
1729                [](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
1730       RTTI = getMSCompleteObjectLocator(RD, *Info);
1731 
1732     ConstantInitBuilder builder(CGM);
1733     auto components = builder.beginStruct();
1734     CGVT.createVTableInitializer(components, VTLayout, RTTI,
1735                                  VTable->hasLocalLinkage());
1736     components.finishAndSetAsInitializer(VTable);
1737 
1738     emitVTableTypeMetadata(*Info, RD, VTable);
1739   }
1740 }
1741 
1742 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1743     CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1744   return Vptr.NearestVBase != nullptr;
1745 }
1746 
1747 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1748     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1749     const CXXRecordDecl *NearestVBase) {
1750   llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1751   if (!VTableAddressPoint) {
1752     assert(Base.getBase()->getNumVBases() &&
1753            !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1754   }
1755   return VTableAddressPoint;
1756 }
1757 
1758 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1759                               const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1760                               SmallString<256> &Name) {
1761   llvm::raw_svector_ostream Out(Name);
1762   MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1763 }
1764 
1765 llvm::Constant *
1766 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1767                                        const CXXRecordDecl *VTableClass) {
1768   (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1769   VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1770   return VFTablesMap[ID];
1771 }
1772 
1773 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1774     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1775   llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1776   assert(VFTable && "Couldn't find a vftable for the given base?");
1777   return VFTable;
1778 }
1779 
1780 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1781                                                        CharUnits VPtrOffset) {
1782   // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1783   // shouldn't be used in the given record type. We want to cache this result in
1784   // VFTablesMap, thus a simple zero check is not sufficient.
1785 
1786   VFTableIdTy ID(RD, VPtrOffset);
1787   VTablesMapTy::iterator I;
1788   bool Inserted;
1789   std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1790   if (!Inserted)
1791     return I->second;
1792 
1793   llvm::GlobalVariable *&VTable = I->second;
1794 
1795   MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1796   const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1797 
1798   if (DeferredVFTables.insert(RD).second) {
1799     // We haven't processed this record type before.
1800     // Queue up this vtable for possible deferred emission.
1801     CGM.addDeferredVTable(RD);
1802 
1803 #ifndef NDEBUG
1804     // Create all the vftables at once in order to make sure each vftable has
1805     // a unique mangled name.
1806     llvm::StringSet<> ObservedMangledNames;
1807     for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1808       SmallString<256> Name;
1809       mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1810       if (!ObservedMangledNames.insert(Name.str()).second)
1811         llvm_unreachable("Already saw this mangling before?");
1812     }
1813 #endif
1814   }
1815 
1816   const std::unique_ptr<VPtrInfo> *VFPtrI =
1817       llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
1818         return VPI->FullOffsetInMDC == VPtrOffset;
1819       });
1820   if (VFPtrI == VFPtrs.end()) {
1821     VFTablesMap[ID] = nullptr;
1822     return nullptr;
1823   }
1824   const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1825 
1826   SmallString<256> VFTableName;
1827   mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1828 
1829   // Classes marked __declspec(dllimport) need vftables generated on the
1830   // import-side in order to support features like constexpr.  No other
1831   // translation unit relies on the emission of the local vftable, translation
1832   // units are expected to generate them as needed.
1833   //
1834   // Because of this unique behavior, we maintain this logic here instead of
1835   // getVTableLinkage.
1836   llvm::GlobalValue::LinkageTypes VFTableLinkage =
1837       RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1838                                    : CGM.getVTableLinkage(RD);
1839   bool VFTableComesFromAnotherTU =
1840       llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1841       llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1842   bool VTableAliasIsRequred =
1843       !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1844 
1845   if (llvm::GlobalValue *VFTable =
1846           CGM.getModule().getNamedGlobal(VFTableName)) {
1847     VFTablesMap[ID] = VFTable;
1848     VTable = VTableAliasIsRequred
1849                  ? cast<llvm::GlobalVariable>(
1850                        cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
1851                  : cast<llvm::GlobalVariable>(VFTable);
1852     return VTable;
1853   }
1854 
1855   const VTableLayout &VTLayout =
1856       VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1857   llvm::GlobalValue::LinkageTypes VTableLinkage =
1858       VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1859 
1860   StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1861 
1862   llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1863 
1864   // Create a backing variable for the contents of VTable.  The VTable may
1865   // or may not include space for a pointer to RTTI data.
1866   llvm::GlobalValue *VFTable;
1867   VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1868                                     /*isConstant=*/true, VTableLinkage,
1869                                     /*Initializer=*/nullptr, VTableName);
1870   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1871 
1872   llvm::Comdat *C = nullptr;
1873   if (!VFTableComesFromAnotherTU &&
1874       (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1875        (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1876         VTableAliasIsRequred)))
1877     C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1878 
1879   // Only insert a pointer into the VFTable for RTTI data if we are not
1880   // importing it.  We never reference the RTTI data directly so there is no
1881   // need to make room for it.
1882   if (VTableAliasIsRequred) {
1883     llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1884                                  llvm::ConstantInt::get(CGM.Int32Ty, 0),
1885                                  llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1886     // Create a GEP which points just after the first entry in the VFTable,
1887     // this should be the location of the first virtual method.
1888     llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1889         VTable->getValueType(), VTable, GEPIndices);
1890     if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1891       VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1892       if (C)
1893         C->setSelectionKind(llvm::Comdat::Largest);
1894     }
1895     VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1896                                         /*AddressSpace=*/0, VFTableLinkage,
1897                                         VFTableName.str(), VTableGEP,
1898                                         &CGM.getModule());
1899     VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1900   } else {
1901     // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1902     // be referencing any RTTI data.
1903     // The GlobalVariable will end up being an appropriate definition of the
1904     // VFTable.
1905     VFTable = VTable;
1906   }
1907   if (C)
1908     VTable->setComdat(C);
1909 
1910   if (RD->hasAttr<DLLExportAttr>())
1911     VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1912 
1913   VFTablesMap[ID] = VFTable;
1914   return VTable;
1915 }
1916 
1917 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1918                                                     GlobalDecl GD,
1919                                                     Address This,
1920                                                     llvm::Type *Ty,
1921                                                     SourceLocation Loc) {
1922   CGBuilderTy &Builder = CGF.Builder;
1923 
1924   Ty = Ty->getPointerTo();
1925   Address VPtr =
1926       adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1927 
1928   auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1929   llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
1930                                          MethodDecl->getParent());
1931 
1932   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1933   MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1934 
1935   // Compute the identity of the most derived class whose virtual table is
1936   // located at the MethodVFTableLocation ML.
1937   auto getObjectWithVPtr = [&] {
1938     return llvm::find_if(VFTContext.getVFPtrOffsets(
1939                              ML.VBase ? ML.VBase : MethodDecl->getParent()),
1940                          [&](const std::unique_ptr<VPtrInfo> &Info) {
1941                            return Info->FullOffsetInMDC == ML.VFPtrOffset;
1942                          })
1943         ->get()
1944         ->ObjectWithVPtr;
1945   };
1946 
1947   llvm::Value *VFunc;
1948   if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1949     VFunc = CGF.EmitVTableTypeCheckedLoad(
1950         getObjectWithVPtr(), VTable, Ty,
1951         ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1952   } else {
1953     if (CGM.getCodeGenOpts().PrepareForLTO)
1954       CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1955 
1956     llvm::Value *VFuncPtr =
1957         Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
1958     VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
1959   }
1960 
1961   CGCallee Callee(GD, VFunc);
1962   return Callee;
1963 }
1964 
1965 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1966     CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1967     Address This, DeleteOrMemberCallExpr E) {
1968   auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1969   auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1970   assert((CE != nullptr) ^ (D != nullptr));
1971   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1972   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1973 
1974   // We have only one destructor in the vftable but can get both behaviors
1975   // by passing an implicit int parameter.
1976   GlobalDecl GD(Dtor, Dtor_Deleting);
1977   const CGFunctionInfo *FInfo =
1978       &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1979   llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1980   CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1981 
1982   ASTContext &Context = getContext();
1983   llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1984       llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1985       DtorType == Dtor_Deleting);
1986 
1987   QualType ThisTy;
1988   if (CE) {
1989     ThisTy = CE->getObjectType();
1990   } else {
1991     ThisTy = D->getDestroyedType();
1992   }
1993 
1994   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1995   RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1996                                         ImplicitParam, Context.IntTy, CE);
1997   return RV.getScalarVal();
1998 }
1999 
2000 const VBTableGlobals &
2001 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
2002   // At this layer, we can key the cache off of a single class, which is much
2003   // easier than caching each vbtable individually.
2004   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
2005   bool Added;
2006   std::tie(Entry, Added) =
2007       VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
2008   VBTableGlobals &VBGlobals = Entry->second;
2009   if (!Added)
2010     return VBGlobals;
2011 
2012   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2013   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
2014 
2015   // Cache the globals for all vbtables so we don't have to recompute the
2016   // mangled names.
2017   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
2018   for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
2019                                       E = VBGlobals.VBTables->end();
2020        I != E; ++I) {
2021     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
2022   }
2023 
2024   return VBGlobals;
2025 }
2026 
2027 llvm::Function *
2028 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
2029                                         const MethodVFTableLocation &ML) {
2030   assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
2031          "can't form pointers to ctors or virtual dtors");
2032 
2033   // Calculate the mangled name.
2034   SmallString<256> ThunkName;
2035   llvm::raw_svector_ostream Out(ThunkName);
2036   getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
2037 
2038   // If the thunk has been generated previously, just return it.
2039   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
2040     return cast<llvm::Function>(GV);
2041 
2042   // Create the llvm::Function.
2043   const CGFunctionInfo &FnInfo =
2044       CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2045   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2046   llvm::Function *ThunkFn =
2047       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2048                              ThunkName.str(), &CGM.getModule());
2049   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2050 
2051   ThunkFn->setLinkage(MD->isExternallyVisible()
2052                           ? llvm::GlobalValue::LinkOnceODRLinkage
2053                           : llvm::GlobalValue::InternalLinkage);
2054   if (MD->isExternallyVisible())
2055     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2056 
2057   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
2058   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2059 
2060   // Add the "thunk" attribute so that LLVM knows that the return type is
2061   // meaningless. These thunks can be used to call functions with differing
2062   // return types, and the caller is required to cast the prototype
2063   // appropriately to extract the correct value.
2064   ThunkFn->addFnAttr("thunk");
2065 
2066   // These thunks can be compared, so they are not unnamed.
2067   ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2068 
2069   // Start codegen.
2070   CodeGenFunction CGF(CGM);
2071   CGF.CurGD = GlobalDecl(MD);
2072   CGF.CurFuncIsThunk = true;
2073 
2074   // Build FunctionArgs, but only include the implicit 'this' parameter
2075   // declaration.
2076   FunctionArgList FunctionArgs;
2077   buildThisParam(CGF, FunctionArgs);
2078 
2079   // Start defining the function.
2080   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2081                     FunctionArgs, MD->getLocation(), SourceLocation());
2082   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2083 
2084   // Load the vfptr and then callee from the vftable.  The callee should have
2085   // adjusted 'this' so that the vfptr is at offset zero.
2086   llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
2087   llvm::Value *VTable = CGF.GetVTablePtr(
2088       getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
2089 
2090   llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
2091       ThunkPtrTy, VTable, ML.Index, "vfn");
2092   llvm::Value *Callee =
2093     CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
2094 
2095   CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2096 
2097   return ThunkFn;
2098 }
2099 
2100 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2101   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2102   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2103     const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2104     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2105     if (GV->isDeclaration())
2106       emitVBTableDefinition(*VBT, RD, GV);
2107   }
2108 }
2109 
2110 llvm::GlobalVariable *
2111 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2112                                   llvm::GlobalVariable::LinkageTypes Linkage) {
2113   SmallString<256> OutName;
2114   llvm::raw_svector_ostream Out(OutName);
2115   getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2116   StringRef Name = OutName.str();
2117 
2118   llvm::ArrayType *VBTableType =
2119       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2120 
2121   assert(!CGM.getModule().getNamedGlobal(Name) &&
2122          "vbtable with this name already exists: mangling bug?");
2123   CharUnits Alignment =
2124       CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2125   llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2126       Name, VBTableType, Linkage, Alignment.getQuantity());
2127   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2128 
2129   if (RD->hasAttr<DLLImportAttr>())
2130     GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2131   else if (RD->hasAttr<DLLExportAttr>())
2132     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2133 
2134   if (!GV->hasExternalLinkage())
2135     emitVBTableDefinition(VBT, RD, GV);
2136 
2137   return GV;
2138 }
2139 
2140 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2141                                             const CXXRecordDecl *RD,
2142                                             llvm::GlobalVariable *GV) const {
2143   const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2144 
2145   assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2146          "should only emit vbtables for classes with vbtables");
2147 
2148   const ASTRecordLayout &BaseLayout =
2149       getContext().getASTRecordLayout(VBT.IntroducingObject);
2150   const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2151 
2152   SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2153                                            nullptr);
2154 
2155   // The offset from ObjectWithVPtr's vbptr to itself always leads.
2156   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2157   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2158 
2159   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2160   for (const auto &I : ObjectWithVPtr->vbases()) {
2161     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2162     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2163     assert(!Offset.isNegative());
2164 
2165     // Make it relative to the subobject vbptr.
2166     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2167     if (VBT.getVBaseWithVPtr())
2168       CompleteVBPtrOffset +=
2169           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2170     Offset -= CompleteVBPtrOffset;
2171 
2172     unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2173     assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2174     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2175   }
2176 
2177   assert(Offsets.size() ==
2178          cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
2179   llvm::ArrayType *VBTableType =
2180     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2181   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2182   GV->setInitializer(Init);
2183 
2184   if (RD->hasAttr<DLLImportAttr>())
2185     GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2186 }
2187 
2188 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2189                                                     Address This,
2190                                                     const ThisAdjustment &TA) {
2191   if (TA.isEmpty())
2192     return This.getPointer();
2193 
2194   This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2195 
2196   llvm::Value *V;
2197   if (TA.Virtual.isEmpty()) {
2198     V = This.getPointer();
2199   } else {
2200     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2201     // Adjust the this argument based on the vtordisp value.
2202     Address VtorDispPtr =
2203         CGF.Builder.CreateConstInBoundsByteGEP(This,
2204                  CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2205     VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2206     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2207     V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
2208                               CGF.Builder.CreateNeg(VtorDisp));
2209 
2210     // Unfortunately, having applied the vtordisp means that we no
2211     // longer really have a known alignment for the vbptr step.
2212     // We'll assume the vbptr is pointer-aligned.
2213 
2214     if (TA.Virtual.Microsoft.VBPtrOffset) {
2215       // If the final overrider is defined in a virtual base other than the one
2216       // that holds the vfptr, we have to use a vtordispex thunk which looks up
2217       // the vbtable of the derived class.
2218       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2219       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2220       llvm::Value *VBPtr;
2221       llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
2222           CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
2223           -TA.Virtual.Microsoft.VBPtrOffset,
2224           TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2225       V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2226     }
2227   }
2228 
2229   if (TA.NonVirtual) {
2230     // Non-virtual adjustment might result in a pointer outside the allocated
2231     // object, e.g. if the final overrider class is laid out after the virtual
2232     // base that declares a method in the most derived class.
2233     V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
2234   }
2235 
2236   // Don't need to bitcast back, the call CodeGen will handle this.
2237   return V;
2238 }
2239 
2240 llvm::Value *
2241 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2242                                          const ReturnAdjustment &RA) {
2243   if (RA.isEmpty())
2244     return Ret.getPointer();
2245 
2246   auto OrigTy = Ret.getType();
2247   Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2248 
2249   llvm::Value *V = Ret.getPointer();
2250   if (RA.Virtual.Microsoft.VBIndex) {
2251     assert(RA.Virtual.Microsoft.VBIndex > 0);
2252     int32_t IntSize = CGF.getIntSize().getQuantity();
2253     llvm::Value *VBPtr;
2254     llvm::Value *VBaseOffset =
2255         GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2256                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2257     V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
2258   }
2259 
2260   if (RA.NonVirtual)
2261     V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2262 
2263   // Cast back to the original type.
2264   return CGF.Builder.CreateBitCast(V, OrigTy);
2265 }
2266 
2267 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2268                                    QualType elementType) {
2269   // Microsoft seems to completely ignore the possibility of a
2270   // two-argument usual deallocation function.
2271   return elementType.isDestructedType();
2272 }
2273 
2274 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2275   // Microsoft seems to completely ignore the possibility of a
2276   // two-argument usual deallocation function.
2277   return expr->getAllocatedType().isDestructedType();
2278 }
2279 
2280 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2281   // The array cookie is always a size_t; we then pad that out to the
2282   // alignment of the element type.
2283   ASTContext &Ctx = getContext();
2284   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2285                   Ctx.getTypeAlignInChars(type));
2286 }
2287 
2288 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2289                                                   Address allocPtr,
2290                                                   CharUnits cookieSize) {
2291   Address numElementsPtr =
2292     CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2293   return CGF.Builder.CreateLoad(numElementsPtr);
2294 }
2295 
2296 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2297                                                Address newPtr,
2298                                                llvm::Value *numElements,
2299                                                const CXXNewExpr *expr,
2300                                                QualType elementType) {
2301   assert(requiresArrayCookie(expr));
2302 
2303   // The size of the cookie.
2304   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2305 
2306   // Compute an offset to the cookie.
2307   Address cookiePtr = newPtr;
2308 
2309   // Write the number of elements into the appropriate slot.
2310   Address numElementsPtr
2311     = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2312   CGF.Builder.CreateStore(numElements, numElementsPtr);
2313 
2314   // Finally, compute a pointer to the actual data buffer by skipping
2315   // over the cookie completely.
2316   return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2317 }
2318 
2319 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2320                                         llvm::FunctionCallee Dtor,
2321                                         llvm::Constant *Addr) {
2322   // Create a function which calls the destructor.
2323   llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2324 
2325   // extern "C" int __tlregdtor(void (*f)(void));
2326   llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2327       CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2328 
2329   llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2330       TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2331   if (llvm::Function *TLRegDtorFn =
2332           dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2333     TLRegDtorFn->setDoesNotThrow();
2334 
2335   CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2336 }
2337 
2338 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2339                                          llvm::FunctionCallee Dtor,
2340                                          llvm::Constant *Addr) {
2341   if (D.isNoDestroy(CGM.getContext()))
2342     return;
2343 
2344   if (D.getTLSKind())
2345     return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2346 
2347   // The default behavior is to use atexit.
2348   CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2349 }
2350 
2351 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2352     CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2353     ArrayRef<llvm::Function *> CXXThreadLocalInits,
2354     ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2355   if (CXXThreadLocalInits.empty())
2356     return;
2357 
2358   CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2359                                   llvm::Triple::x86
2360                               ? "/include:___dyn_tls_init@12"
2361                               : "/include:__dyn_tls_init");
2362 
2363   // This will create a GV in the .CRT$XDU section.  It will point to our
2364   // initialization function.  The CRT will call all of these function
2365   // pointers at start-up time and, eventually, at thread-creation time.
2366   auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2367     llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2368         CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2369         llvm::GlobalVariable::InternalLinkage, InitFunc,
2370         Twine(InitFunc->getName(), "$initializer$"));
2371     InitFuncPtr->setSection(".CRT$XDU");
2372     // This variable has discardable linkage, we have to add it to @llvm.used to
2373     // ensure it won't get discarded.
2374     CGM.addUsedGlobal(InitFuncPtr);
2375     return InitFuncPtr;
2376   };
2377 
2378   std::vector<llvm::Function *> NonComdatInits;
2379   for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2380     llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2381         CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2382     llvm::Function *F = CXXThreadLocalInits[I];
2383 
2384     // If the GV is already in a comdat group, then we have to join it.
2385     if (llvm::Comdat *C = GV->getComdat())
2386       AddToXDU(F)->setComdat(C);
2387     else
2388       NonComdatInits.push_back(F);
2389   }
2390 
2391   if (!NonComdatInits.empty()) {
2392     llvm::FunctionType *FTy =
2393         llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2394     llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
2395         FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2396         SourceLocation(), /*TLS=*/true);
2397     CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2398 
2399     AddToXDU(InitFunc);
2400   }
2401 }
2402 
2403 static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
2404   // __tls_guard comes from the MSVC runtime and reflects
2405   // whether TLS has been initialized for a particular thread.
2406   // It is set from within __dyn_tls_init by the runtime.
2407   // Every library and executable has its own variable.
2408   llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
2409   llvm::Constant *TlsGuardConstant =
2410       CGM.CreateRuntimeVariable(VTy, "__tls_guard");
2411   llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
2412 
2413   TlsGuard->setThreadLocal(true);
2414 
2415   return TlsGuard;
2416 }
2417 
2418 static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
2419   // __dyn_tls_on_demand_init comes from the MSVC runtime and triggers
2420   // dynamic TLS initialization by calling __dyn_tls_init internally.
2421   llvm::FunctionType *FTy =
2422       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
2423                               /*isVarArg=*/false);
2424   return CGM.CreateRuntimeFunction(
2425       FTy, "__dyn_tls_on_demand_init",
2426       llvm::AttributeList::get(CGM.getLLVMContext(),
2427                                llvm::AttributeList::FunctionIndex,
2428                                llvm::Attribute::NoUnwind),
2429       /*Local=*/true);
2430 }
2431 
2432 static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
2433                               llvm::BasicBlock *DynInitBB,
2434                               llvm::BasicBlock *ContinueBB) {
2435   llvm::LoadInst *TlsGuardValue =
2436       CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
2437   llvm::Value *CmpResult =
2438       CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
2439   CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
2440 }
2441 
2442 static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
2443                                              llvm::GlobalValue *TlsGuard,
2444                                              llvm::BasicBlock *ContinueBB) {
2445   llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
2446   llvm::Function *InitializerFunction =
2447       cast<llvm::Function>(Initializer.getCallee());
2448   llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
2449   CallVal->setCallingConv(InitializerFunction->getCallingConv());
2450 
2451   CGF.Builder.CreateBr(ContinueBB);
2452 }
2453 
2454 static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
2455   llvm::BasicBlock *DynInitBB =
2456       CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
2457   llvm::BasicBlock *ContinueBB =
2458       CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
2459 
2460   llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
2461 
2462   emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
2463   CGF.Builder.SetInsertPoint(DynInitBB);
2464   emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
2465   CGF.Builder.SetInsertPoint(ContinueBB);
2466 }
2467 
2468 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2469                                                      const VarDecl *VD,
2470                                                      QualType LValType) {
2471   // Dynamic TLS initialization works by checking the state of a
2472   // guard variable (__tls_guard) to see whether TLS initialization
2473   // for a thread has happend yet.
2474   // If not, the initialization is triggered on-demand
2475   // by calling __dyn_tls_on_demand_init.
2476   emitDynamicTlsInitialization(CGF);
2477 
2478   // Emit the variable just like any regular global variable.
2479 
2480   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2481   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2482 
2483   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2484   V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
2485 
2486   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2487   Address Addr(V, RealVarTy, Alignment);
2488 
2489   LValue LV = VD->getType()->isReferenceType()
2490                   ? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2491                                                   AlignmentSource::Decl)
2492                   : CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
2493   return LV;
2494 }
2495 
2496 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2497   StringRef VarName("_Init_thread_epoch");
2498   CharUnits Align = CGM.getIntAlign();
2499   if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2500     return ConstantAddress(GV, GV->getValueType(), Align);
2501   auto *GV = new llvm::GlobalVariable(
2502       CGM.getModule(), CGM.IntTy,
2503       /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2504       /*Initializer=*/nullptr, VarName,
2505       /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2506   GV->setAlignment(Align.getAsAlign());
2507   return ConstantAddress(GV, GV->getValueType(), Align);
2508 }
2509 
2510 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2511   llvm::FunctionType *FTy =
2512       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2513                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2514   return CGM.CreateRuntimeFunction(
2515       FTy, "_Init_thread_header",
2516       llvm::AttributeList::get(CGM.getLLVMContext(),
2517                                llvm::AttributeList::FunctionIndex,
2518                                llvm::Attribute::NoUnwind),
2519       /*Local=*/true);
2520 }
2521 
2522 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2523   llvm::FunctionType *FTy =
2524       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2525                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2526   return CGM.CreateRuntimeFunction(
2527       FTy, "_Init_thread_footer",
2528       llvm::AttributeList::get(CGM.getLLVMContext(),
2529                                llvm::AttributeList::FunctionIndex,
2530                                llvm::Attribute::NoUnwind),
2531       /*Local=*/true);
2532 }
2533 
2534 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2535   llvm::FunctionType *FTy =
2536       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2537                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2538   return CGM.CreateRuntimeFunction(
2539       FTy, "_Init_thread_abort",
2540       llvm::AttributeList::get(CGM.getLLVMContext(),
2541                                llvm::AttributeList::FunctionIndex,
2542                                llvm::Attribute::NoUnwind),
2543       /*Local=*/true);
2544 }
2545 
2546 namespace {
2547 struct ResetGuardBit final : EHScopeStack::Cleanup {
2548   Address Guard;
2549   unsigned GuardNum;
2550   ResetGuardBit(Address Guard, unsigned GuardNum)
2551       : Guard(Guard), GuardNum(GuardNum) {}
2552 
2553   void Emit(CodeGenFunction &CGF, Flags flags) override {
2554     // Reset the bit in the mask so that the static variable may be
2555     // reinitialized.
2556     CGBuilderTy &Builder = CGF.Builder;
2557     llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2558     llvm::ConstantInt *Mask =
2559         llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2560     Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2561   }
2562 };
2563 
2564 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2565   llvm::Value *Guard;
2566   CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2567 
2568   void Emit(CodeGenFunction &CGF, Flags flags) override {
2569     // Calling _Init_thread_abort will reset the guard's state.
2570     CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2571   }
2572 };
2573 }
2574 
2575 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2576                                       llvm::GlobalVariable *GV,
2577                                       bool PerformInit) {
2578   // MSVC only uses guards for static locals.
2579   if (!D.isStaticLocal()) {
2580     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2581     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2582     llvm::Function *F = CGF.CurFn;
2583     F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2584     F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2585     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2586     return;
2587   }
2588 
2589   bool ThreadlocalStatic = D.getTLSKind();
2590   bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2591 
2592   // Thread-safe static variables which aren't thread-specific have a
2593   // per-variable guard.
2594   bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2595 
2596   CGBuilderTy &Builder = CGF.Builder;
2597   llvm::IntegerType *GuardTy = CGF.Int32Ty;
2598   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2599   CharUnits GuardAlign = CharUnits::fromQuantity(4);
2600 
2601   // Get the guard variable for this function if we have one already.
2602   GuardInfo *GI = nullptr;
2603   if (ThreadlocalStatic)
2604     GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2605   else if (!ThreadsafeStatic)
2606     GI = &GuardVariableMap[D.getDeclContext()];
2607 
2608   llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2609   unsigned GuardNum;
2610   if (D.isExternallyVisible()) {
2611     // Externally visible variables have to be numbered in Sema to properly
2612     // handle unreachable VarDecls.
2613     GuardNum = getContext().getStaticLocalNumber(&D);
2614     assert(GuardNum > 0);
2615     GuardNum--;
2616   } else if (HasPerVariableGuard) {
2617     GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2618   } else {
2619     // Non-externally visible variables are numbered here in CodeGen.
2620     GuardNum = GI->BitIndex++;
2621   }
2622 
2623   if (!HasPerVariableGuard && GuardNum >= 32) {
2624     if (D.isExternallyVisible())
2625       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2626     GuardNum %= 32;
2627     GuardVar = nullptr;
2628   }
2629 
2630   if (!GuardVar) {
2631     // Mangle the name for the guard.
2632     SmallString<256> GuardName;
2633     {
2634       llvm::raw_svector_ostream Out(GuardName);
2635       if (HasPerVariableGuard)
2636         getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2637                                                                Out);
2638       else
2639         getMangleContext().mangleStaticGuardVariable(&D, Out);
2640     }
2641 
2642     // Create the guard variable with a zero-initializer. Just absorb linkage,
2643     // visibility and dll storage class from the guarded variable.
2644     GuardVar =
2645         new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2646                                  GV->getLinkage(), Zero, GuardName.str());
2647     GuardVar->setVisibility(GV->getVisibility());
2648     GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2649     GuardVar->setAlignment(GuardAlign.getAsAlign());
2650     if (GuardVar->isWeakForLinker())
2651       GuardVar->setComdat(
2652           CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2653     if (D.getTLSKind())
2654       CGM.setTLSMode(GuardVar, D);
2655     if (GI && !HasPerVariableGuard)
2656       GI->Guard = GuardVar;
2657   }
2658 
2659   ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
2660 
2661   assert(GuardVar->getLinkage() == GV->getLinkage() &&
2662          "static local from the same function had different linkage");
2663 
2664   if (!HasPerVariableGuard) {
2665     // Pseudo code for the test:
2666     // if (!(GuardVar & MyGuardBit)) {
2667     //   GuardVar |= MyGuardBit;
2668     //   ... initialize the object ...;
2669     // }
2670 
2671     // Test our bit from the guard variable.
2672     llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2673     llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2674     llvm::Value *NeedsInit =
2675         Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2676     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2677     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2678     CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2679                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2680 
2681     // Set our bit in the guard variable and emit the initializer and add a global
2682     // destructor if appropriate.
2683     CGF.EmitBlock(InitBlock);
2684     Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2685     CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2686     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2687     CGF.PopCleanupBlock();
2688     Builder.CreateBr(EndBlock);
2689 
2690     // Continue.
2691     CGF.EmitBlock(EndBlock);
2692   } else {
2693     // Pseudo code for the test:
2694     // if (TSS > _Init_thread_epoch) {
2695     //   _Init_thread_header(&TSS);
2696     //   if (TSS == -1) {
2697     //     ... initialize the object ...;
2698     //     _Init_thread_footer(&TSS);
2699     //   }
2700     // }
2701     //
2702     // The algorithm is almost identical to what can be found in the appendix
2703     // found in N2325.
2704 
2705     // This BasicBLock determines whether or not we have any work to do.
2706     llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2707     FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2708     llvm::LoadInst *InitThreadEpoch =
2709         Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2710     llvm::Value *IsUninitialized =
2711         Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2712     llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2713     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2714     CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2715                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2716 
2717     // This BasicBlock attempts to determine whether or not this thread is
2718     // responsible for doing the initialization.
2719     CGF.EmitBlock(AttemptInitBlock);
2720     CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2721                                 GuardAddr.getPointer());
2722     llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2723     SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2724     llvm::Value *ShouldDoInit =
2725         Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2726     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2727     Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2728 
2729     // Ok, we ended up getting selected as the initializing thread.
2730     CGF.EmitBlock(InitBlock);
2731     CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2732     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2733     CGF.PopCleanupBlock();
2734     CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2735                                 GuardAddr.getPointer());
2736     Builder.CreateBr(EndBlock);
2737 
2738     CGF.EmitBlock(EndBlock);
2739   }
2740 }
2741 
2742 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2743   // Null-ness for function memptrs only depends on the first field, which is
2744   // the function pointer.  The rest don't matter, so we can zero initialize.
2745   if (MPT->isMemberFunctionPointer())
2746     return true;
2747 
2748   // The virtual base adjustment field is always -1 for null, so if we have one
2749   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
2750   // valid field offset.
2751   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2752   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2753   return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2754           RD->nullFieldOffsetIsZero());
2755 }
2756 
2757 llvm::Type *
2758 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2759   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2760   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2761   llvm::SmallVector<llvm::Type *, 4> fields;
2762   if (MPT->isMemberFunctionPointer())
2763     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
2764   else
2765     fields.push_back(CGM.IntTy);  // FieldOffset
2766 
2767   if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2768                                        Inheritance))
2769     fields.push_back(CGM.IntTy);
2770   if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2771     fields.push_back(CGM.IntTy);
2772   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2773     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
2774 
2775   if (fields.size() == 1)
2776     return fields[0];
2777   return llvm::StructType::get(CGM.getLLVMContext(), fields);
2778 }
2779 
2780 void MicrosoftCXXABI::
2781 GetNullMemberPointerFields(const MemberPointerType *MPT,
2782                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2783   assert(fields.empty());
2784   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2785   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2786   if (MPT->isMemberFunctionPointer()) {
2787     // FunctionPointerOrVirtualThunk
2788     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2789   } else {
2790     if (RD->nullFieldOffsetIsZero())
2791       fields.push_back(getZeroInt());  // FieldOffset
2792     else
2793       fields.push_back(getAllOnesInt());  // FieldOffset
2794   }
2795 
2796   if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2797                                        Inheritance))
2798     fields.push_back(getZeroInt());
2799   if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2800     fields.push_back(getZeroInt());
2801   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2802     fields.push_back(getAllOnesInt());
2803 }
2804 
2805 llvm::Constant *
2806 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2807   llvm::SmallVector<llvm::Constant *, 4> fields;
2808   GetNullMemberPointerFields(MPT, fields);
2809   if (fields.size() == 1)
2810     return fields[0];
2811   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2812   assert(Res->getType() == ConvertMemberPointerType(MPT));
2813   return Res;
2814 }
2815 
2816 llvm::Constant *
2817 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2818                                        bool IsMemberFunction,
2819                                        const CXXRecordDecl *RD,
2820                                        CharUnits NonVirtualBaseAdjustment,
2821                                        unsigned VBTableIndex) {
2822   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2823 
2824   // Single inheritance class member pointer are represented as scalars instead
2825   // of aggregates.
2826   if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2827     return FirstField;
2828 
2829   llvm::SmallVector<llvm::Constant *, 4> fields;
2830   fields.push_back(FirstField);
2831 
2832   if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2833     fields.push_back(llvm::ConstantInt::get(
2834       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2835 
2836   if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2837     CharUnits Offs = CharUnits::Zero();
2838     if (VBTableIndex)
2839       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2840     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2841   }
2842 
2843   // The rest of the fields are adjusted by conversions to a more derived class.
2844   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2845     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2846 
2847   return llvm::ConstantStruct::getAnon(fields);
2848 }
2849 
2850 llvm::Constant *
2851 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2852                                        CharUnits offset) {
2853   return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2854 }
2855 
2856 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2857                                                        CharUnits offset) {
2858   if (RD->getMSInheritanceModel() ==
2859       MSInheritanceModel::Virtual)
2860     offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2861   llvm::Constant *FirstField =
2862     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2863   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2864                                CharUnits::Zero(), /*VBTableIndex=*/0);
2865 }
2866 
2867 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2868                                                    QualType MPType) {
2869   const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2870   const ValueDecl *MPD = MP.getMemberPointerDecl();
2871   if (!MPD)
2872     return EmitNullMemberPointer(DstTy);
2873 
2874   ASTContext &Ctx = getContext();
2875   ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2876 
2877   llvm::Constant *C;
2878   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2879     C = EmitMemberFunctionPointer(MD);
2880   } else {
2881     // For a pointer to data member, start off with the offset of the field in
2882     // the class in which it was declared, and convert from there if necessary.
2883     // For indirect field decls, get the outermost anonymous field and use the
2884     // parent class.
2885     CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2886     const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2887     if (!FD)
2888       FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2889     const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2890     RD = RD->getMostRecentNonInjectedDecl();
2891     C = EmitMemberDataPointer(RD, FieldOffset);
2892   }
2893 
2894   if (!MemberPointerPath.empty()) {
2895     const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2896     const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2897     const MemberPointerType *SrcTy =
2898         Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2899             ->castAs<MemberPointerType>();
2900 
2901     bool DerivedMember = MP.isMemberPointerToDerivedMember();
2902     SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2903     const CXXRecordDecl *PrevRD = SrcRD;
2904     for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2905       const CXXRecordDecl *Base = nullptr;
2906       const CXXRecordDecl *Derived = nullptr;
2907       if (DerivedMember) {
2908         Base = PathElem;
2909         Derived = PrevRD;
2910       } else {
2911         Base = PrevRD;
2912         Derived = PathElem;
2913       }
2914       for (const CXXBaseSpecifier &BS : Derived->bases())
2915         if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2916             Base->getCanonicalDecl())
2917           DerivedToBasePath.push_back(&BS);
2918       PrevRD = PathElem;
2919     }
2920     assert(DerivedToBasePath.size() == MemberPointerPath.size());
2921 
2922     CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2923                                 : CK_BaseToDerivedMemberPointer;
2924     C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2925                                     DerivedToBasePath.end(), C);
2926   }
2927   return C;
2928 }
2929 
2930 llvm::Constant *
2931 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2932   assert(MD->isInstance() && "Member function must not be static!");
2933 
2934   CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2935   const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2936   CodeGenTypes &Types = CGM.getTypes();
2937 
2938   unsigned VBTableIndex = 0;
2939   llvm::Constant *FirstField;
2940   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2941   if (!MD->isVirtual()) {
2942     llvm::Type *Ty;
2943     // Check whether the function has a computable LLVM signature.
2944     if (Types.isFuncTypeConvertible(FPT)) {
2945       // The function has a computable LLVM signature; use the correct type.
2946       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2947     } else {
2948       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2949       // function type is incomplete.
2950       Ty = CGM.PtrDiffTy;
2951     }
2952     FirstField = CGM.GetAddrOfFunction(MD, Ty);
2953   } else {
2954     auto &VTableContext = CGM.getMicrosoftVTableContext();
2955     MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2956     FirstField = EmitVirtualMemPtrThunk(MD, ML);
2957     // Include the vfptr adjustment if the method is in a non-primary vftable.
2958     NonVirtualBaseAdjustment += ML.VFPtrOffset;
2959     if (ML.VBase)
2960       VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2961   }
2962 
2963   if (VBTableIndex == 0 &&
2964       RD->getMSInheritanceModel() ==
2965           MSInheritanceModel::Virtual)
2966     NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2967 
2968   // The rest of the fields are common with data member pointers.
2969   FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2970   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2971                                NonVirtualBaseAdjustment, VBTableIndex);
2972 }
2973 
2974 /// Member pointers are the same if they're either bitwise identical *or* both
2975 /// null.  Null-ness for function members is determined by the first field,
2976 /// while for data member pointers we must compare all fields.
2977 llvm::Value *
2978 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2979                                              llvm::Value *L,
2980                                              llvm::Value *R,
2981                                              const MemberPointerType *MPT,
2982                                              bool Inequality) {
2983   CGBuilderTy &Builder = CGF.Builder;
2984 
2985   // Handle != comparisons by switching the sense of all boolean operations.
2986   llvm::ICmpInst::Predicate Eq;
2987   llvm::Instruction::BinaryOps And, Or;
2988   if (Inequality) {
2989     Eq = llvm::ICmpInst::ICMP_NE;
2990     And = llvm::Instruction::Or;
2991     Or = llvm::Instruction::And;
2992   } else {
2993     Eq = llvm::ICmpInst::ICMP_EQ;
2994     And = llvm::Instruction::And;
2995     Or = llvm::Instruction::Or;
2996   }
2997 
2998   // If this is a single field member pointer (single inheritance), this is a
2999   // single icmp.
3000   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3001   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3002   if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
3003                                       Inheritance))
3004     return Builder.CreateICmp(Eq, L, R);
3005 
3006   // Compare the first field.
3007   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
3008   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
3009   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
3010 
3011   // Compare everything other than the first field.
3012   llvm::Value *Res = nullptr;
3013   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
3014   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
3015     llvm::Value *LF = Builder.CreateExtractValue(L, I);
3016     llvm::Value *RF = Builder.CreateExtractValue(R, I);
3017     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
3018     if (Res)
3019       Res = Builder.CreateBinOp(And, Res, Cmp);
3020     else
3021       Res = Cmp;
3022   }
3023 
3024   // Check if the first field is 0 if this is a function pointer.
3025   if (MPT->isMemberFunctionPointer()) {
3026     // (l1 == r1 && ...) || l0 == 0
3027     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
3028     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
3029     Res = Builder.CreateBinOp(Or, Res, IsZero);
3030   }
3031 
3032   // Combine the comparison of the first field, which must always be true for
3033   // this comparison to succeeed.
3034   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
3035 }
3036 
3037 llvm::Value *
3038 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
3039                                             llvm::Value *MemPtr,
3040                                             const MemberPointerType *MPT) {
3041   CGBuilderTy &Builder = CGF.Builder;
3042   llvm::SmallVector<llvm::Constant *, 4> fields;
3043   // We only need one field for member functions.
3044   if (MPT->isMemberFunctionPointer())
3045     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
3046   else
3047     GetNullMemberPointerFields(MPT, fields);
3048   assert(!fields.empty());
3049   llvm::Value *FirstField = MemPtr;
3050   if (MemPtr->getType()->isStructTy())
3051     FirstField = Builder.CreateExtractValue(MemPtr, 0);
3052   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
3053 
3054   // For function member pointers, we only need to test the function pointer
3055   // field.  The other fields if any can be garbage.
3056   if (MPT->isMemberFunctionPointer())
3057     return Res;
3058 
3059   // Otherwise, emit a series of compares and combine the results.
3060   for (int I = 1, E = fields.size(); I < E; ++I) {
3061     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
3062     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
3063     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
3064   }
3065   return Res;
3066 }
3067 
3068 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
3069                                                   llvm::Constant *Val) {
3070   // Function pointers are null if the pointer in the first field is null.
3071   if (MPT->isMemberFunctionPointer()) {
3072     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
3073       Val->getAggregateElement(0U) : Val;
3074     return FirstField->isNullValue();
3075   }
3076 
3077   // If it's not a function pointer and it's zero initializable, we can easily
3078   // check zero.
3079   if (isZeroInitializable(MPT) && Val->isNullValue())
3080     return true;
3081 
3082   // Otherwise, break down all the fields for comparison.  Hopefully these
3083   // little Constants are reused, while a big null struct might not be.
3084   llvm::SmallVector<llvm::Constant *, 4> Fields;
3085   GetNullMemberPointerFields(MPT, Fields);
3086   if (Fields.size() == 1) {
3087     assert(Val->getType()->isIntegerTy());
3088     return Val == Fields[0];
3089   }
3090 
3091   unsigned I, E;
3092   for (I = 0, E = Fields.size(); I != E; ++I) {
3093     if (Val->getAggregateElement(I) != Fields[I])
3094       break;
3095   }
3096   return I == E;
3097 }
3098 
3099 llvm::Value *
3100 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
3101                                          Address This,
3102                                          llvm::Value *VBPtrOffset,
3103                                          llvm::Value *VBTableOffset,
3104                                          llvm::Value **VBPtrOut) {
3105   CGBuilderTy &Builder = CGF.Builder;
3106   // Load the vbtable pointer from the vbptr in the instance.
3107   This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
3108   llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
3109       This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
3110   if (VBPtrOut) *VBPtrOut = VBPtr;
3111   VBPtr = Builder.CreateBitCast(VBPtr,
3112             CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
3113 
3114   CharUnits VBPtrAlign;
3115   if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
3116     VBPtrAlign = This.getAlignment().alignmentAtOffset(
3117                                    CharUnits::fromQuantity(CI->getSExtValue()));
3118   } else {
3119     VBPtrAlign = CGF.getPointerAlign();
3120   }
3121 
3122   llvm::Value *VBTable = Builder.CreateAlignedLoad(
3123       CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
3124 
3125   // Translate from byte offset to table index. It improves analyzability.
3126   llvm::Value *VBTableIndex = Builder.CreateAShr(
3127       VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
3128       "vbtindex", /*isExact=*/true);
3129 
3130   // Load an i32 offset from the vb-table.
3131   llvm::Value *VBaseOffs =
3132       Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
3133   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3134   return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
3135                                    CharUnits::fromQuantity(4), "vbase_offs");
3136 }
3137 
3138 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3139 // it.
3140 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3141     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3142     Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3143   CGBuilderTy &Builder = CGF.Builder;
3144   Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3145   llvm::BasicBlock *OriginalBB = nullptr;
3146   llvm::BasicBlock *SkipAdjustBB = nullptr;
3147   llvm::BasicBlock *VBaseAdjustBB = nullptr;
3148 
3149   // In the unspecified inheritance model, there might not be a vbtable at all,
3150   // in which case we need to skip the virtual base lookup.  If there is a
3151   // vbtable, the first entry is a no-op entry that gives back the original
3152   // base, so look for a virtual base adjustment offset of zero.
3153   if (VBPtrOffset) {
3154     OriginalBB = Builder.GetInsertBlock();
3155     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3156     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3157     llvm::Value *IsVirtual =
3158       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3159                            "memptr.is_vbase");
3160     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3161     CGF.EmitBlock(VBaseAdjustBB);
3162   }
3163 
3164   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3165   // know the vbptr offset.
3166   if (!VBPtrOffset) {
3167     CharUnits offs = CharUnits::Zero();
3168     if (!RD->hasDefinition()) {
3169       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3170       unsigned DiagID = Diags.getCustomDiagID(
3171           DiagnosticsEngine::Error,
3172           "member pointer representation requires a "
3173           "complete class type for %0 to perform this expression");
3174       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3175     } else if (RD->getNumVBases())
3176       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3177     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3178   }
3179   llvm::Value *VBPtr = nullptr;
3180   llvm::Value *VBaseOffs =
3181     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3182   llvm::Value *AdjustedBase =
3183     Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
3184 
3185   // Merge control flow with the case where we didn't have to adjust.
3186   if (VBaseAdjustBB) {
3187     Builder.CreateBr(SkipAdjustBB);
3188     CGF.EmitBlock(SkipAdjustBB);
3189     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3190     Phi->addIncoming(Base.getPointer(), OriginalBB);
3191     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3192     return Phi;
3193   }
3194   return AdjustedBase;
3195 }
3196 
3197 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3198     CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3199     const MemberPointerType *MPT) {
3200   assert(MPT->isMemberDataPointer());
3201   unsigned AS = Base.getAddressSpace();
3202   llvm::Type *PType =
3203       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3204   CGBuilderTy &Builder = CGF.Builder;
3205   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3206   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3207 
3208   // Extract the fields we need, regardless of model.  We'll apply them if we
3209   // have them.
3210   llvm::Value *FieldOffset = MemPtr;
3211   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3212   llvm::Value *VBPtrOffset = nullptr;
3213   if (MemPtr->getType()->isStructTy()) {
3214     // We need to extract values.
3215     unsigned I = 0;
3216     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3217     if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3218       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3219     if (inheritanceModelHasVBTableOffsetField(Inheritance))
3220       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3221   }
3222 
3223   llvm::Value *Addr;
3224   if (VirtualBaseAdjustmentOffset) {
3225     Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3226                              VBPtrOffset);
3227   } else {
3228     Addr = Base.getPointer();
3229   }
3230 
3231   // Cast to char*.
3232   Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3233 
3234   // Apply the offset, which we assume is non-null.
3235   Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
3236                                    "memptr.offset");
3237 
3238   // Cast the address to the appropriate pointer type, adopting the address
3239   // space of the base pointer.
3240   return Builder.CreateBitCast(Addr, PType);
3241 }
3242 
3243 llvm::Value *
3244 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3245                                              const CastExpr *E,
3246                                              llvm::Value *Src) {
3247   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3248          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3249          E->getCastKind() == CK_ReinterpretMemberPointer);
3250 
3251   // Use constant emission if we can.
3252   if (isa<llvm::Constant>(Src))
3253     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3254 
3255   // We may be adding or dropping fields from the member pointer, so we need
3256   // both types and the inheritance models of both records.
3257   const MemberPointerType *SrcTy =
3258     E->getSubExpr()->getType()->castAs<MemberPointerType>();
3259   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3260   bool IsFunc = SrcTy->isMemberFunctionPointer();
3261 
3262   // If the classes use the same null representation, reinterpret_cast is a nop.
3263   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3264   if (IsReinterpret && IsFunc)
3265     return Src;
3266 
3267   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3268   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3269   if (IsReinterpret &&
3270       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3271     return Src;
3272 
3273   CGBuilderTy &Builder = CGF.Builder;
3274 
3275   // Branch past the conversion if Src is null.
3276   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3277   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3278 
3279   // C++ 5.2.10p9: The null member pointer value is converted to the null member
3280   //   pointer value of the destination type.
3281   if (IsReinterpret) {
3282     // For reinterpret casts, sema ensures that src and dst are both functions
3283     // or data and have the same size, which means the LLVM types should match.
3284     assert(Src->getType() == DstNull->getType());
3285     return Builder.CreateSelect(IsNotNull, Src, DstNull);
3286   }
3287 
3288   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3289   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3290   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3291   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3292   CGF.EmitBlock(ConvertBB);
3293 
3294   llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3295       SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3296       Builder);
3297 
3298   Builder.CreateBr(ContinueBB);
3299 
3300   // In the continuation, choose between DstNull and Dst.
3301   CGF.EmitBlock(ContinueBB);
3302   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3303   Phi->addIncoming(DstNull, OriginalBB);
3304   Phi->addIncoming(Dst, ConvertBB);
3305   return Phi;
3306 }
3307 
3308 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3309     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3310     CastExpr::path_const_iterator PathBegin,
3311     CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3312     CGBuilderTy &Builder) {
3313   const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3314   const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3315   MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3316   MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3317   bool IsFunc = SrcTy->isMemberFunctionPointer();
3318   bool IsConstant = isa<llvm::Constant>(Src);
3319 
3320   // Decompose src.
3321   llvm::Value *FirstField = Src;
3322   llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3323   llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3324   llvm::Value *VBPtrOffset = getZeroInt();
3325   if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3326     // We need to extract values.
3327     unsigned I = 0;
3328     FirstField = Builder.CreateExtractValue(Src, I++);
3329     if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3330       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3331     if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3332       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3333     if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3334       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3335   }
3336 
3337   bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3338   const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3339   const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3340 
3341   // For data pointers, we adjust the field offset directly.  For functions, we
3342   // have a separate field.
3343   llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3344 
3345   // The virtual inheritance model has a quirk: the virtual base table is always
3346   // referenced when dereferencing a member pointer even if the member pointer
3347   // is non-virtual.  This is accounted for by adjusting the non-virtual offset
3348   // to point backwards to the top of the MDC from the first VBase.  Undo this
3349   // adjustment to normalize the member pointer.
3350   llvm::Value *SrcVBIndexEqZero =
3351       Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3352   if (SrcInheritance == MSInheritanceModel::Virtual) {
3353     if (int64_t SrcOffsetToFirstVBase =
3354             getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3355       llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3356           SrcVBIndexEqZero,
3357           llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3358           getZeroInt());
3359       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3360     }
3361   }
3362 
3363   // A non-zero vbindex implies that we are dealing with a source member in a
3364   // floating virtual base in addition to some non-virtual offset.  If the
3365   // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3366   // fixed, base.  The difference between these two cases is that the vbindex +
3367   // nvoffset *always* point to the member regardless of what context they are
3368   // evaluated in so long as the vbindex is adjusted.  A member inside a fixed
3369   // base requires explicit nv adjustment.
3370   llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3371       CGM.IntTy,
3372       CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3373           .getQuantity());
3374 
3375   llvm::Value *NVDisp;
3376   if (IsDerivedToBase)
3377     NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3378   else
3379     NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3380 
3381   NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3382 
3383   // Update the vbindex to an appropriate value in the destination because
3384   // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3385   llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3386   if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3387       inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3388     if (llvm::GlobalVariable *VDispMap =
3389             getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3390       llvm::Value *VBIndex = Builder.CreateExactUDiv(
3391           VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3392       if (IsConstant) {
3393         llvm::Constant *Mapping = VDispMap->getInitializer();
3394         VirtualBaseAdjustmentOffset =
3395             Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3396       } else {
3397         llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3398         VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
3399             CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
3400                                                  VDispMap, Idxs),
3401             CharUnits::fromQuantity(4));
3402       }
3403 
3404       DstVBIndexEqZero =
3405           Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3406     }
3407   }
3408 
3409   // Set the VBPtrOffset to zero if the vbindex is zero.  Otherwise, initialize
3410   // it to the offset of the vbptr.
3411   if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3412     llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3413         CGM.IntTy,
3414         getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3415     VBPtrOffset =
3416         Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3417   }
3418 
3419   // Likewise, apply a similar adjustment so that dereferencing the member
3420   // pointer correctly accounts for the distance between the start of the first
3421   // virtual base and the top of the MDC.
3422   if (DstInheritance == MSInheritanceModel::Virtual) {
3423     if (int64_t DstOffsetToFirstVBase =
3424             getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3425       llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3426           DstVBIndexEqZero,
3427           llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3428           getZeroInt());
3429       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3430     }
3431   }
3432 
3433   // Recompose dst from the null struct and the adjusted fields from src.
3434   llvm::Value *Dst;
3435   if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3436     Dst = FirstField;
3437   } else {
3438     Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3439     unsigned Idx = 0;
3440     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3441     if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3442       Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3443     if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3444       Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3445     if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3446       Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3447   }
3448   return Dst;
3449 }
3450 
3451 llvm::Constant *
3452 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3453                                              llvm::Constant *Src) {
3454   const MemberPointerType *SrcTy =
3455       E->getSubExpr()->getType()->castAs<MemberPointerType>();
3456   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3457 
3458   CastKind CK = E->getCastKind();
3459 
3460   return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3461                                      E->path_end(), Src);
3462 }
3463 
3464 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3465     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3466     CastExpr::path_const_iterator PathBegin,
3467     CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3468   assert(CK == CK_DerivedToBaseMemberPointer ||
3469          CK == CK_BaseToDerivedMemberPointer ||
3470          CK == CK_ReinterpretMemberPointer);
3471   // If src is null, emit a new null for dst.  We can't return src because dst
3472   // might have a new representation.
3473   if (MemberPointerConstantIsNull(SrcTy, Src))
3474     return EmitNullMemberPointer(DstTy);
3475 
3476   // We don't need to do anything for reinterpret_casts of non-null member
3477   // pointers.  We should only get here when the two type representations have
3478   // the same size.
3479   if (CK == CK_ReinterpretMemberPointer)
3480     return Src;
3481 
3482   CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3483   auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3484       SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3485 
3486   return Dst;
3487 }
3488 
3489 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3490     CodeGenFunction &CGF, const Expr *E, Address This,
3491     llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3492     const MemberPointerType *MPT) {
3493   assert(MPT->isMemberFunctionPointer());
3494   const FunctionProtoType *FPT =
3495     MPT->getPointeeType()->castAs<FunctionProtoType>();
3496   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3497   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3498       CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3499   CGBuilderTy &Builder = CGF.Builder;
3500 
3501   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3502 
3503   // Extract the fields we need, regardless of model.  We'll apply them if we
3504   // have them.
3505   llvm::Value *FunctionPointer = MemPtr;
3506   llvm::Value *NonVirtualBaseAdjustment = nullptr;
3507   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3508   llvm::Value *VBPtrOffset = nullptr;
3509   if (MemPtr->getType()->isStructTy()) {
3510     // We need to extract values.
3511     unsigned I = 0;
3512     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3513     if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3514       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3515     if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3516       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3517     if (inheritanceModelHasVBTableOffsetField(Inheritance))
3518       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3519   }
3520 
3521   if (VirtualBaseAdjustmentOffset) {
3522     ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3523                                    VirtualBaseAdjustmentOffset, VBPtrOffset);
3524   } else {
3525     ThisPtrForCall = This.getPointer();
3526   }
3527 
3528   if (NonVirtualBaseAdjustment) {
3529     // Apply the adjustment and cast back to the original struct type.
3530     llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3531     Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
3532     ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3533                                            "this.adjusted");
3534   }
3535 
3536   FunctionPointer =
3537     Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3538   CGCallee Callee(FPT, FunctionPointer);
3539   return Callee;
3540 }
3541 
3542 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3543   return new MicrosoftCXXABI(CGM);
3544 }
3545 
3546 // MS RTTI Overview:
3547 // The run time type information emitted by cl.exe contains 5 distinct types of
3548 // structures.  Many of them reference each other.
3549 //
3550 // TypeInfo:  Static classes that are returned by typeid.
3551 //
3552 // CompleteObjectLocator:  Referenced by vftables.  They contain information
3553 //   required for dynamic casting, including OffsetFromTop.  They also contain
3554 //   a reference to the TypeInfo for the type and a reference to the
3555 //   CompleteHierarchyDescriptor for the type.
3556 //
3557 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3558 //   Used during dynamic_cast to walk a class hierarchy.  References a base
3559 //   class array and the size of said array.
3560 //
3561 // BaseClassArray: Contains a list of classes in a hierarchy.  BaseClassArray is
3562 //   somewhat of a misnomer because the most derived class is also in the list
3563 //   as well as multiple copies of virtual bases (if they occur multiple times
3564 //   in the hierarchy.)  The BaseClassArray contains one BaseClassDescriptor for
3565 //   every path in the hierarchy, in pre-order depth first order.  Note, we do
3566 //   not declare a specific llvm type for BaseClassArray, it's merely an array
3567 //   of BaseClassDescriptor pointers.
3568 //
3569 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3570 //   BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3571 //   BaseClassArray is.  It contains information about a class within a
3572 //   hierarchy such as: is this base is ambiguous and what is its offset in the
3573 //   vbtable.  The names of the BaseClassDescriptors have all of their fields
3574 //   mangled into them so they can be aggressively deduplicated by the linker.
3575 
3576 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3577   StringRef MangledName("??_7type_info@@6B@");
3578   if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3579     return VTable;
3580   return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3581                                   /*isConstant=*/true,
3582                                   llvm::GlobalVariable::ExternalLinkage,
3583                                   /*Initializer=*/nullptr, MangledName);
3584 }
3585 
3586 namespace {
3587 
3588 /// A Helper struct that stores information about a class in a class
3589 /// hierarchy.  The information stored in these structs struct is used during
3590 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3591 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3592 // implicit depth first pre-order tree connectivity.  getFirstChild and
3593 // getNextSibling allow us to walk the tree efficiently.
3594 struct MSRTTIClass {
3595   enum {
3596     IsPrivateOnPath = 1 | 8,
3597     IsAmbiguous = 2,
3598     IsPrivate = 4,
3599     IsVirtual = 16,
3600     HasHierarchyDescriptor = 64
3601   };
3602   MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3603   uint32_t initialize(const MSRTTIClass *Parent,
3604                       const CXXBaseSpecifier *Specifier);
3605 
3606   MSRTTIClass *getFirstChild() { return this + 1; }
3607   static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3608     return Child + 1 + Child->NumBases;
3609   }
3610 
3611   const CXXRecordDecl *RD, *VirtualRoot;
3612   uint32_t Flags, NumBases, OffsetInVBase;
3613 };
3614 
3615 /// Recursively initialize the base class array.
3616 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3617                                  const CXXBaseSpecifier *Specifier) {
3618   Flags = HasHierarchyDescriptor;
3619   if (!Parent) {
3620     VirtualRoot = nullptr;
3621     OffsetInVBase = 0;
3622   } else {
3623     if (Specifier->getAccessSpecifier() != AS_public)
3624       Flags |= IsPrivate | IsPrivateOnPath;
3625     if (Specifier->isVirtual()) {
3626       Flags |= IsVirtual;
3627       VirtualRoot = RD;
3628       OffsetInVBase = 0;
3629     } else {
3630       if (Parent->Flags & IsPrivateOnPath)
3631         Flags |= IsPrivateOnPath;
3632       VirtualRoot = Parent->VirtualRoot;
3633       OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3634           .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3635     }
3636   }
3637   NumBases = 0;
3638   MSRTTIClass *Child = getFirstChild();
3639   for (const CXXBaseSpecifier &Base : RD->bases()) {
3640     NumBases += Child->initialize(this, &Base) + 1;
3641     Child = getNextChild(Child);
3642   }
3643   return NumBases;
3644 }
3645 
3646 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3647   switch (Ty->getLinkage()) {
3648   case NoLinkage:
3649   case InternalLinkage:
3650   case UniqueExternalLinkage:
3651     return llvm::GlobalValue::InternalLinkage;
3652 
3653   case VisibleNoLinkage:
3654   case ModuleInternalLinkage:
3655   case ModuleLinkage:
3656   case ExternalLinkage:
3657     return llvm::GlobalValue::LinkOnceODRLinkage;
3658   }
3659   llvm_unreachable("Invalid linkage!");
3660 }
3661 
3662 /// An ephemeral helper class for building MS RTTI types.  It caches some
3663 /// calls to the module and information about the most derived class in a
3664 /// hierarchy.
3665 struct MSRTTIBuilder {
3666   enum {
3667     HasBranchingHierarchy = 1,
3668     HasVirtualBranchingHierarchy = 2,
3669     HasAmbiguousBases = 4
3670   };
3671 
3672   MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3673       : CGM(ABI.CGM), Context(CGM.getContext()),
3674         VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3675         Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3676         ABI(ABI) {}
3677 
3678   llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3679   llvm::GlobalVariable *
3680   getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3681   llvm::GlobalVariable *getClassHierarchyDescriptor();
3682   llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3683 
3684   CodeGenModule &CGM;
3685   ASTContext &Context;
3686   llvm::LLVMContext &VMContext;
3687   llvm::Module &Module;
3688   const CXXRecordDecl *RD;
3689   llvm::GlobalVariable::LinkageTypes Linkage;
3690   MicrosoftCXXABI &ABI;
3691 };
3692 
3693 } // namespace
3694 
3695 /// Recursively serializes a class hierarchy in pre-order depth first
3696 /// order.
3697 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3698                                     const CXXRecordDecl *RD) {
3699   Classes.push_back(MSRTTIClass(RD));
3700   for (const CXXBaseSpecifier &Base : RD->bases())
3701     serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3702 }
3703 
3704 /// Find ambiguity among base classes.
3705 static void
3706 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3707   llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3708   llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3709   llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3710   for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3711     if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3712         !VirtualBases.insert(Class->RD).second) {
3713       Class = MSRTTIClass::getNextChild(Class);
3714       continue;
3715     }
3716     if (!UniqueBases.insert(Class->RD).second)
3717       AmbiguousBases.insert(Class->RD);
3718     Class++;
3719   }
3720   if (AmbiguousBases.empty())
3721     return;
3722   for (MSRTTIClass &Class : Classes)
3723     if (AmbiguousBases.count(Class.RD))
3724       Class.Flags |= MSRTTIClass::IsAmbiguous;
3725 }
3726 
3727 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3728   SmallString<256> MangledName;
3729   {
3730     llvm::raw_svector_ostream Out(MangledName);
3731     ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3732   }
3733 
3734   // Check to see if we've already declared this ClassHierarchyDescriptor.
3735   if (auto CHD = Module.getNamedGlobal(MangledName))
3736     return CHD;
3737 
3738   // Serialize the class hierarchy and initialize the CHD Fields.
3739   SmallVector<MSRTTIClass, 8> Classes;
3740   serializeClassHierarchy(Classes, RD);
3741   Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3742   detectAmbiguousBases(Classes);
3743   int Flags = 0;
3744   for (auto Class : Classes) {
3745     if (Class.RD->getNumBases() > 1)
3746       Flags |= HasBranchingHierarchy;
3747     // Note: cl.exe does not calculate "HasAmbiguousBases" correctly.  We
3748     // believe the field isn't actually used.
3749     if (Class.Flags & MSRTTIClass::IsAmbiguous)
3750       Flags |= HasAmbiguousBases;
3751   }
3752   if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3753     Flags |= HasVirtualBranchingHierarchy;
3754   // These gep indices are used to get the address of the first element of the
3755   // base class array.
3756   llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3757                                llvm::ConstantInt::get(CGM.IntTy, 0)};
3758 
3759   // Forward-declare the class hierarchy descriptor
3760   auto Type = ABI.getClassHierarchyDescriptorType();
3761   auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3762                                       /*Initializer=*/nullptr,
3763                                       MangledName);
3764   if (CHD->isWeakForLinker())
3765     CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3766 
3767   auto *Bases = getBaseClassArray(Classes);
3768 
3769   // Initialize the base class ClassHierarchyDescriptor.
3770   llvm::Constant *Fields[] = {
3771       llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3772       llvm::ConstantInt::get(CGM.IntTy, Flags),
3773       llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3774       ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3775           Bases->getValueType(), Bases,
3776           llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3777   };
3778   CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3779   return CHD;
3780 }
3781 
3782 llvm::GlobalVariable *
3783 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3784   SmallString<256> MangledName;
3785   {
3786     llvm::raw_svector_ostream Out(MangledName);
3787     ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3788   }
3789 
3790   // Forward-declare the base class array.
3791   // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3792   // mode) bytes of padding.  We provide a pointer sized amount of padding by
3793   // adding +1 to Classes.size().  The sections have pointer alignment and are
3794   // marked pick-any so it shouldn't matter.
3795   llvm::Type *PtrType = ABI.getImageRelativeType(
3796       ABI.getBaseClassDescriptorType()->getPointerTo());
3797   auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3798   auto *BCA =
3799       new llvm::GlobalVariable(Module, ArrType,
3800                                /*isConstant=*/true, Linkage,
3801                                /*Initializer=*/nullptr, MangledName);
3802   if (BCA->isWeakForLinker())
3803     BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3804 
3805   // Initialize the BaseClassArray.
3806   SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3807   for (MSRTTIClass &Class : Classes)
3808     BaseClassArrayData.push_back(
3809         ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3810   BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3811   BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3812   return BCA;
3813 }
3814 
3815 llvm::GlobalVariable *
3816 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3817   // Compute the fields for the BaseClassDescriptor.  They are computed up front
3818   // because they are mangled into the name of the object.
3819   uint32_t OffsetInVBTable = 0;
3820   int32_t VBPtrOffset = -1;
3821   if (Class.VirtualRoot) {
3822     auto &VTableContext = CGM.getMicrosoftVTableContext();
3823     OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3824     VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3825   }
3826 
3827   SmallString<256> MangledName;
3828   {
3829     llvm::raw_svector_ostream Out(MangledName);
3830     ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3831         Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3832         Class.Flags, Out);
3833   }
3834 
3835   // Check to see if we've already declared this object.
3836   if (auto BCD = Module.getNamedGlobal(MangledName))
3837     return BCD;
3838 
3839   // Forward-declare the base class descriptor.
3840   auto Type = ABI.getBaseClassDescriptorType();
3841   auto BCD =
3842       new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3843                                /*Initializer=*/nullptr, MangledName);
3844   if (BCD->isWeakForLinker())
3845     BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3846 
3847   // Initialize the BaseClassDescriptor.
3848   llvm::Constant *Fields[] = {
3849       ABI.getImageRelativeConstant(
3850           ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3851       llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3852       llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3853       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3854       llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3855       llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3856       ABI.getImageRelativeConstant(
3857           MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3858   };
3859   BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3860   return BCD;
3861 }
3862 
3863 llvm::GlobalVariable *
3864 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3865   SmallString<256> MangledName;
3866   {
3867     llvm::raw_svector_ostream Out(MangledName);
3868     ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3869   }
3870 
3871   // Check to see if we've already computed this complete object locator.
3872   if (auto COL = Module.getNamedGlobal(MangledName))
3873     return COL;
3874 
3875   // Compute the fields of the complete object locator.
3876   int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3877   int VFPtrOffset = 0;
3878   // The offset includes the vtordisp if one exists.
3879   if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3880     if (Context.getASTRecordLayout(RD)
3881       .getVBaseOffsetsMap()
3882       .find(VBase)
3883       ->second.hasVtorDisp())
3884       VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3885 
3886   // Forward-declare the complete object locator.
3887   llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3888   auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3889     /*Initializer=*/nullptr, MangledName);
3890 
3891   // Initialize the CompleteObjectLocator.
3892   llvm::Constant *Fields[] = {
3893       llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3894       llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3895       llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3896       ABI.getImageRelativeConstant(
3897           CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3898       ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3899       ABI.getImageRelativeConstant(COL),
3900   };
3901   llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3902   if (!ABI.isImageRelative())
3903     FieldsRef = FieldsRef.drop_back();
3904   COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3905   if (COL->isWeakForLinker())
3906     COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3907   return COL;
3908 }
3909 
3910 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3911                                    bool &IsConst, bool &IsVolatile,
3912                                    bool &IsUnaligned) {
3913   T = Context.getExceptionObjectType(T);
3914 
3915   // C++14 [except.handle]p3:
3916   //   A handler is a match for an exception object of type E if [...]
3917   //     - the handler is of type cv T or const T& where T is a pointer type and
3918   //       E is a pointer type that can be converted to T by [...]
3919   //         - a qualification conversion
3920   IsConst = false;
3921   IsVolatile = false;
3922   IsUnaligned = false;
3923   QualType PointeeType = T->getPointeeType();
3924   if (!PointeeType.isNull()) {
3925     IsConst = PointeeType.isConstQualified();
3926     IsVolatile = PointeeType.isVolatileQualified();
3927     IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3928   }
3929 
3930   // Member pointer types like "const int A::*" are represented by having RTTI
3931   // for "int A::*" and separately storing the const qualifier.
3932   if (const auto *MPTy = T->getAs<MemberPointerType>())
3933     T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3934                                      MPTy->getClass());
3935 
3936   // Pointer types like "const int * const *" are represented by having RTTI
3937   // for "const int **" and separately storing the const qualifier.
3938   if (T->isPointerType())
3939     T = Context.getPointerType(PointeeType.getUnqualifiedType());
3940 
3941   return T;
3942 }
3943 
3944 CatchTypeInfo
3945 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3946                                               QualType CatchHandlerType) {
3947   // TypeDescriptors for exceptions never have qualified pointer types,
3948   // qualifiers are stored separately in order to support qualification
3949   // conversions.
3950   bool IsConst, IsVolatile, IsUnaligned;
3951   Type =
3952       decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3953 
3954   bool IsReference = CatchHandlerType->isReferenceType();
3955 
3956   uint32_t Flags = 0;
3957   if (IsConst)
3958     Flags |= 1;
3959   if (IsVolatile)
3960     Flags |= 2;
3961   if (IsUnaligned)
3962     Flags |= 4;
3963   if (IsReference)
3964     Flags |= 8;
3965 
3966   return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3967                        Flags};
3968 }
3969 
3970 /// Gets a TypeDescriptor.  Returns a llvm::Constant * rather than a
3971 /// llvm::GlobalVariable * because different type descriptors have different
3972 /// types, and need to be abstracted.  They are abstracting by casting the
3973 /// address to an Int8PtrTy.
3974 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3975   SmallString<256> MangledName;
3976   {
3977     llvm::raw_svector_ostream Out(MangledName);
3978     getMangleContext().mangleCXXRTTI(Type, Out);
3979   }
3980 
3981   // Check to see if we've already declared this TypeDescriptor.
3982   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3983     return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3984 
3985   // Note for the future: If we would ever like to do deferred emission of
3986   // RTTI, check if emitting vtables opportunistically need any adjustment.
3987 
3988   // Compute the fields for the TypeDescriptor.
3989   SmallString<256> TypeInfoString;
3990   {
3991     llvm::raw_svector_ostream Out(TypeInfoString);
3992     getMangleContext().mangleCXXRTTIName(Type, Out);
3993   }
3994 
3995   // Declare and initialize the TypeDescriptor.
3996   llvm::Constant *Fields[] = {
3997     getTypeInfoVTable(CGM),                        // VFPtr
3998     llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3999     llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
4000   llvm::StructType *TypeDescriptorType =
4001       getTypeDescriptorType(TypeInfoString);
4002   auto *Var = new llvm::GlobalVariable(
4003       CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
4004       getLinkageForRTTI(Type),
4005       llvm::ConstantStruct::get(TypeDescriptorType, Fields),
4006       MangledName);
4007   if (Var->isWeakForLinker())
4008     Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
4009   return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
4010 }
4011 
4012 /// Gets or a creates a Microsoft CompleteObjectLocator.
4013 llvm::GlobalVariable *
4014 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
4015                                             const VPtrInfo &Info) {
4016   return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
4017 }
4018 
4019 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
4020   if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
4021     // There are no constructor variants, always emit the complete destructor.
4022     llvm::Function *Fn =
4023         CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
4024     CGM.maybeSetTrivialComdat(*ctor, *Fn);
4025     return;
4026   }
4027 
4028   auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
4029 
4030   // Emit the base destructor if the base and complete (vbase) destructors are
4031   // equivalent. This effectively implements -mconstructor-aliases as part of
4032   // the ABI.
4033   if (GD.getDtorType() == Dtor_Complete &&
4034       dtor->getParent()->getNumVBases() == 0)
4035     GD = GD.getWithDtorType(Dtor_Base);
4036 
4037   // The base destructor is equivalent to the base destructor of its
4038   // base class if there is exactly one non-virtual base class with a
4039   // non-trivial destructor, there are no fields with a non-trivial
4040   // destructor, and the body of the destructor is trivial.
4041   if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
4042     return;
4043 
4044   llvm::Function *Fn = CGM.codegenCXXStructor(GD);
4045   if (Fn->isWeakForLinker())
4046     Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
4047 }
4048 
4049 llvm::Function *
4050 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
4051                                          CXXCtorType CT) {
4052   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
4053 
4054   // Calculate the mangled name.
4055   SmallString<256> ThunkName;
4056   llvm::raw_svector_ostream Out(ThunkName);
4057   getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
4058 
4059   // If the thunk has been generated previously, just return it.
4060   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
4061     return cast<llvm::Function>(GV);
4062 
4063   // Create the llvm::Function.
4064   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
4065   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
4066   const CXXRecordDecl *RD = CD->getParent();
4067   QualType RecordTy = getContext().getRecordType(RD);
4068   llvm::Function *ThunkFn = llvm::Function::Create(
4069       ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
4070   ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
4071       FnInfo.getEffectiveCallingConvention()));
4072   if (ThunkFn->isWeakForLinker())
4073     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
4074   bool IsCopy = CT == Ctor_CopyingClosure;
4075 
4076   // Start codegen.
4077   CodeGenFunction CGF(CGM);
4078   CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
4079 
4080   // Build FunctionArgs.
4081   FunctionArgList FunctionArgs;
4082 
4083   // A constructor always starts with a 'this' pointer as its first argument.
4084   buildThisParam(CGF, FunctionArgs);
4085 
4086   // Following the 'this' pointer is a reference to the source object that we
4087   // are copying from.
4088   ImplicitParamDecl SrcParam(
4089       getContext(), /*DC=*/nullptr, SourceLocation(),
4090       &getContext().Idents.get("src"),
4091       getContext().getLValueReferenceType(RecordTy,
4092                                           /*SpelledAsLValue=*/true),
4093       ImplicitParamDecl::Other);
4094   if (IsCopy)
4095     FunctionArgs.push_back(&SrcParam);
4096 
4097   // Constructors for classes which utilize virtual bases have an additional
4098   // parameter which indicates whether or not it is being delegated to by a more
4099   // derived constructor.
4100   ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
4101                                   SourceLocation(),
4102                                   &getContext().Idents.get("is_most_derived"),
4103                                   getContext().IntTy, ImplicitParamDecl::Other);
4104   // Only add the parameter to the list if the class has virtual bases.
4105   if (RD->getNumVBases() > 0)
4106     FunctionArgs.push_back(&IsMostDerived);
4107 
4108   // Start defining the function.
4109   auto NL = ApplyDebugLocation::CreateEmpty(CGF);
4110   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
4111                     FunctionArgs, CD->getLocation(), SourceLocation());
4112   // Create a scope with an artificial location for the body of this function.
4113   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
4114   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
4115   llvm::Value *This = getThisValue(CGF);
4116 
4117   llvm::Value *SrcVal =
4118       IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
4119              : nullptr;
4120 
4121   CallArgList Args;
4122 
4123   // Push the this ptr.
4124   Args.add(RValue::get(This), CD->getThisType());
4125 
4126   // Push the src ptr.
4127   if (SrcVal)
4128     Args.add(RValue::get(SrcVal), SrcParam.getType());
4129 
4130   // Add the rest of the default arguments.
4131   SmallVector<const Stmt *, 4> ArgVec;
4132   ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
4133   for (const ParmVarDecl *PD : params) {
4134     assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4135     ArgVec.push_back(PD->getDefaultArg());
4136   }
4137 
4138   CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4139 
4140   const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4141   CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4142 
4143   // Insert any ABI-specific implicit constructor arguments.
4144   AddedStructorArgCounts ExtraArgs =
4145       addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4146                                  /*ForVirtualBase=*/false,
4147                                  /*Delegating=*/false, Args);
4148   // Call the destructor with our arguments.
4149   llvm::Constant *CalleePtr =
4150       CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4151   CGCallee Callee =
4152       CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4153   const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4154       Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4155   CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4156 
4157   Cleanups.ForceCleanup();
4158 
4159   // Emit the ret instruction, remove any temporary instructions created for the
4160   // aid of CodeGen.
4161   CGF.FinishFunction(SourceLocation());
4162 
4163   return ThunkFn;
4164 }
4165 
4166 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4167                                                   uint32_t NVOffset,
4168                                                   int32_t VBPtrOffset,
4169                                                   uint32_t VBIndex) {
4170   assert(!T->isReferenceType());
4171 
4172   CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4173   const CXXConstructorDecl *CD =
4174       RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4175   CXXCtorType CT = Ctor_Complete;
4176   if (CD)
4177     if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4178       CT = Ctor_CopyingClosure;
4179 
4180   uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4181   SmallString<256> MangledName;
4182   {
4183     llvm::raw_svector_ostream Out(MangledName);
4184     getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4185                                               VBPtrOffset, VBIndex, Out);
4186   }
4187   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4188     return getImageRelativeConstant(GV);
4189 
4190   // The TypeDescriptor is used by the runtime to determine if a catch handler
4191   // is appropriate for the exception object.
4192   llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4193 
4194   // The runtime is responsible for calling the copy constructor if the
4195   // exception is caught by value.
4196   llvm::Constant *CopyCtor;
4197   if (CD) {
4198     if (CT == Ctor_CopyingClosure)
4199       CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4200     else
4201       CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4202 
4203     CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4204   } else {
4205     CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4206   }
4207   CopyCtor = getImageRelativeConstant(CopyCtor);
4208 
4209   bool IsScalar = !RD;
4210   bool HasVirtualBases = false;
4211   bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4212   QualType PointeeType = T;
4213   if (T->isPointerType())
4214     PointeeType = T->getPointeeType();
4215   if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4216     HasVirtualBases = RD->getNumVBases() > 0;
4217     if (IdentifierInfo *II = RD->getIdentifier())
4218       IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4219   }
4220 
4221   // Encode the relevant CatchableType properties into the Flags bitfield.
4222   // FIXME: Figure out how bits 2 or 8 can get set.
4223   uint32_t Flags = 0;
4224   if (IsScalar)
4225     Flags |= 1;
4226   if (HasVirtualBases)
4227     Flags |= 4;
4228   if (IsStdBadAlloc)
4229     Flags |= 16;
4230 
4231   llvm::Constant *Fields[] = {
4232       llvm::ConstantInt::get(CGM.IntTy, Flags),       // Flags
4233       TD,                                             // TypeDescriptor
4234       llvm::ConstantInt::get(CGM.IntTy, NVOffset),    // NonVirtualAdjustment
4235       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4236       llvm::ConstantInt::get(CGM.IntTy, VBIndex),     // VBTableIndex
4237       llvm::ConstantInt::get(CGM.IntTy, Size),        // Size
4238       CopyCtor                                        // CopyCtor
4239   };
4240   llvm::StructType *CTType = getCatchableTypeType();
4241   auto *GV = new llvm::GlobalVariable(
4242       CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4243       llvm::ConstantStruct::get(CTType, Fields), MangledName);
4244   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4245   GV->setSection(".xdata");
4246   if (GV->isWeakForLinker())
4247     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4248   return getImageRelativeConstant(GV);
4249 }
4250 
4251 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4252   assert(!T->isReferenceType());
4253 
4254   // See if we've already generated a CatchableTypeArray for this type before.
4255   llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4256   if (CTA)
4257     return CTA;
4258 
4259   // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4260   // using a SmallSetVector.  Duplicates may arise due to virtual bases
4261   // occurring more than once in the hierarchy.
4262   llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4263 
4264   // C++14 [except.handle]p3:
4265   //   A handler is a match for an exception object of type E if [...]
4266   //     - the handler is of type cv T or cv T& and T is an unambiguous public
4267   //       base class of E, or
4268   //     - the handler is of type cv T or const T& where T is a pointer type and
4269   //       E is a pointer type that can be converted to T by [...]
4270   //         - a standard pointer conversion (4.10) not involving conversions to
4271   //           pointers to private or protected or ambiguous classes
4272   const CXXRecordDecl *MostDerivedClass = nullptr;
4273   bool IsPointer = T->isPointerType();
4274   if (IsPointer)
4275     MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4276   else
4277     MostDerivedClass = T->getAsCXXRecordDecl();
4278 
4279   // Collect all the unambiguous public bases of the MostDerivedClass.
4280   if (MostDerivedClass) {
4281     const ASTContext &Context = getContext();
4282     const ASTRecordLayout &MostDerivedLayout =
4283         Context.getASTRecordLayout(MostDerivedClass);
4284     MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4285     SmallVector<MSRTTIClass, 8> Classes;
4286     serializeClassHierarchy(Classes, MostDerivedClass);
4287     Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4288     detectAmbiguousBases(Classes);
4289     for (const MSRTTIClass &Class : Classes) {
4290       // Skip any ambiguous or private bases.
4291       if (Class.Flags &
4292           (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4293         continue;
4294       // Write down how to convert from a derived pointer to a base pointer.
4295       uint32_t OffsetInVBTable = 0;
4296       int32_t VBPtrOffset = -1;
4297       if (Class.VirtualRoot) {
4298         OffsetInVBTable =
4299           VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4300         VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4301       }
4302 
4303       // Turn our record back into a pointer if the exception object is a
4304       // pointer.
4305       QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4306       if (IsPointer)
4307         RTTITy = Context.getPointerType(RTTITy);
4308       CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4309                                              VBPtrOffset, OffsetInVBTable));
4310     }
4311   }
4312 
4313   // C++14 [except.handle]p3:
4314   //   A handler is a match for an exception object of type E if
4315   //     - The handler is of type cv T or cv T& and E and T are the same type
4316   //       (ignoring the top-level cv-qualifiers)
4317   CatchableTypes.insert(getCatchableType(T));
4318 
4319   // C++14 [except.handle]p3:
4320   //   A handler is a match for an exception object of type E if
4321   //     - the handler is of type cv T or const T& where T is a pointer type and
4322   //       E is a pointer type that can be converted to T by [...]
4323   //         - a standard pointer conversion (4.10) not involving conversions to
4324   //           pointers to private or protected or ambiguous classes
4325   //
4326   // C++14 [conv.ptr]p2:
4327   //   A prvalue of type "pointer to cv T," where T is an object type, can be
4328   //   converted to a prvalue of type "pointer to cv void".
4329   if (IsPointer && T->getPointeeType()->isObjectType())
4330     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4331 
4332   // C++14 [except.handle]p3:
4333   //   A handler is a match for an exception object of type E if [...]
4334   //     - the handler is of type cv T or const T& where T is a pointer or
4335   //       pointer to member type and E is std::nullptr_t.
4336   //
4337   // We cannot possibly list all possible pointer types here, making this
4338   // implementation incompatible with the standard.  However, MSVC includes an
4339   // entry for pointer-to-void in this case.  Let's do the same.
4340   if (T->isNullPtrType())
4341     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4342 
4343   uint32_t NumEntries = CatchableTypes.size();
4344   llvm::Type *CTType =
4345       getImageRelativeType(getCatchableTypeType()->getPointerTo());
4346   llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4347   llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4348   llvm::Constant *Fields[] = {
4349       llvm::ConstantInt::get(CGM.IntTy, NumEntries),    // NumEntries
4350       llvm::ConstantArray::get(
4351           AT, llvm::makeArrayRef(CatchableTypes.begin(),
4352                                  CatchableTypes.end())) // CatchableTypes
4353   };
4354   SmallString<256> MangledName;
4355   {
4356     llvm::raw_svector_ostream Out(MangledName);
4357     getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4358   }
4359   CTA = new llvm::GlobalVariable(
4360       CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4361       llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4362   CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4363   CTA->setSection(".xdata");
4364   if (CTA->isWeakForLinker())
4365     CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4366   return CTA;
4367 }
4368 
4369 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4370   bool IsConst, IsVolatile, IsUnaligned;
4371   T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4372 
4373   // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4374   // the exception object may be caught as.
4375   llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4376   // The first field in a CatchableTypeArray is the number of CatchableTypes.
4377   // This is used as a component of the mangled name which means that we need to
4378   // know what it is in order to see if we have previously generated the
4379   // ThrowInfo.
4380   uint32_t NumEntries =
4381       cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4382           ->getLimitedValue();
4383 
4384   SmallString<256> MangledName;
4385   {
4386     llvm::raw_svector_ostream Out(MangledName);
4387     getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4388                                           NumEntries, Out);
4389   }
4390 
4391   // Reuse a previously generated ThrowInfo if we have generated an appropriate
4392   // one before.
4393   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4394     return GV;
4395 
4396   // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4397   // be at least as CV qualified.  Encode this requirement into the Flags
4398   // bitfield.
4399   uint32_t Flags = 0;
4400   if (IsConst)
4401     Flags |= 1;
4402   if (IsVolatile)
4403     Flags |= 2;
4404   if (IsUnaligned)
4405     Flags |= 4;
4406 
4407   // The cleanup-function (a destructor) must be called when the exception
4408   // object's lifetime ends.
4409   llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4410   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4411     if (CXXDestructorDecl *DtorD = RD->getDestructor())
4412       if (!DtorD->isTrivial())
4413         CleanupFn = llvm::ConstantExpr::getBitCast(
4414             CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4415             CGM.Int8PtrTy);
4416   // This is unused as far as we can tell, initialize it to null.
4417   llvm::Constant *ForwardCompat =
4418       getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4419   llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4420       llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4421   llvm::StructType *TIType = getThrowInfoType();
4422   llvm::Constant *Fields[] = {
4423       llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4424       getImageRelativeConstant(CleanupFn),      // CleanupFn
4425       ForwardCompat,                            // ForwardCompat
4426       PointerToCatchableTypes                   // CatchableTypeArray
4427   };
4428   auto *GV = new llvm::GlobalVariable(
4429       CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4430       llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
4431   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4432   GV->setSection(".xdata");
4433   if (GV->isWeakForLinker())
4434     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4435   return GV;
4436 }
4437 
4438 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4439   const Expr *SubExpr = E->getSubExpr();
4440   assert(SubExpr && "SubExpr cannot be null");
4441   QualType ThrowType = SubExpr->getType();
4442   // The exception object lives on the stack and it's address is passed to the
4443   // runtime function.
4444   Address AI = CGF.CreateMemTemp(ThrowType);
4445   CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4446                        /*IsInit=*/true);
4447 
4448   // The so-called ThrowInfo is used to describe how the exception object may be
4449   // caught.
4450   llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4451 
4452   // Call into the runtime to throw the exception.
4453   llvm::Value *Args[] = {
4454     CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4455     TI
4456   };
4457   CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4458 }
4459 
4460 std::pair<llvm::Value *, const CXXRecordDecl *>
4461 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4462                                const CXXRecordDecl *RD) {
4463   std::tie(This, std::ignore, RD) =
4464       performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4465   return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4466 }
4467 
4468 bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
4469     const CXXRecordDecl *CXXRD) const {
4470   // MSVC Windows on Arm64 considers a type not HFA if it is not an
4471   // aggregate according to the C++14 spec. This is not consistent with the
4472   // AAPCS64, but is defacto spec on that platform.
4473   return !CGM.getTarget().getTriple().isAArch64() ||
4474          isTrivialForAArch64MSVC(CXXRD);
4475 }
4476