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