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     Components.finishAndSetAsInitializer(VTable);
1695 
1696     emitVTableTypeMetadata(*Info, RD, VTable);
1697   }
1698 }
1699 
1700 bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
1701     CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
1702   return Vptr.NearestVBase != nullptr;
1703 }
1704 
1705 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
1706     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
1707     const CXXRecordDecl *NearestVBase) {
1708   llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
1709   if (!VTableAddressPoint) {
1710     assert(Base.getBase()->getNumVBases() &&
1711            !getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
1712   }
1713   return VTableAddressPoint;
1714 }
1715 
1716 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
1717                               const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
1718                               SmallString<256> &Name) {
1719   llvm::raw_svector_ostream Out(Name);
1720   MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
1721 }
1722 
1723 llvm::Constant *
1724 MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
1725                                        const CXXRecordDecl *VTableClass) {
1726   (void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
1727   VFTableIdTy ID(VTableClass, Base.getBaseOffset());
1728   return VFTablesMap[ID];
1729 }
1730 
1731 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
1732     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
1733   llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
1734   assert(VFTable && "Couldn't find a vftable for the given base?");
1735   return VFTable;
1736 }
1737 
1738 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
1739                                                        CharUnits VPtrOffset) {
1740   // getAddrOfVTable may return 0 if asked to get an address of a vtable which
1741   // shouldn't be used in the given record type. We want to cache this result in
1742   // VFTablesMap, thus a simple zero check is not sufficient.
1743 
1744   VFTableIdTy ID(RD, VPtrOffset);
1745   VTablesMapTy::iterator I;
1746   bool Inserted;
1747   std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
1748   if (!Inserted)
1749     return I->second;
1750 
1751   llvm::GlobalVariable *&VTable = I->second;
1752 
1753   MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
1754   const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
1755 
1756   if (DeferredVFTables.insert(RD).second) {
1757     // We haven't processed this record type before.
1758     // Queue up this vtable for possible deferred emission.
1759     CGM.addDeferredVTable(RD);
1760 
1761 #ifndef NDEBUG
1762     // Create all the vftables at once in order to make sure each vftable has
1763     // a unique mangled name.
1764     llvm::StringSet<> ObservedMangledNames;
1765     for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
1766       SmallString<256> Name;
1767       mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
1768       if (!ObservedMangledNames.insert(Name.str()).second)
1769         llvm_unreachable("Already saw this mangling before?");
1770     }
1771 #endif
1772   }
1773 
1774   const std::unique_ptr<VPtrInfo> *VFPtrI = std::find_if(
1775       VFPtrs.begin(), VFPtrs.end(), [&](const std::unique_ptr<VPtrInfo>& VPI) {
1776         return VPI->FullOffsetInMDC == VPtrOffset;
1777       });
1778   if (VFPtrI == VFPtrs.end()) {
1779     VFTablesMap[ID] = nullptr;
1780     return nullptr;
1781   }
1782   const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
1783 
1784   SmallString<256> VFTableName;
1785   mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
1786 
1787   // Classes marked __declspec(dllimport) need vftables generated on the
1788   // import-side in order to support features like constexpr.  No other
1789   // translation unit relies on the emission of the local vftable, translation
1790   // units are expected to generate them as needed.
1791   //
1792   // Because of this unique behavior, we maintain this logic here instead of
1793   // getVTableLinkage.
1794   llvm::GlobalValue::LinkageTypes VFTableLinkage =
1795       RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
1796                                    : CGM.getVTableLinkage(RD);
1797   bool VFTableComesFromAnotherTU =
1798       llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
1799       llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
1800   bool VTableAliasIsRequred =
1801       !VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
1802 
1803   if (llvm::GlobalValue *VFTable =
1804           CGM.getModule().getNamedGlobal(VFTableName)) {
1805     VFTablesMap[ID] = VFTable;
1806     VTable = VTableAliasIsRequred
1807                  ? cast<llvm::GlobalVariable>(
1808                        cast<llvm::GlobalAlias>(VFTable)->getBaseObject())
1809                  : cast<llvm::GlobalVariable>(VFTable);
1810     return VTable;
1811   }
1812 
1813   const VTableLayout &VTLayout =
1814       VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
1815   llvm::GlobalValue::LinkageTypes VTableLinkage =
1816       VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
1817 
1818   StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
1819 
1820   llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
1821 
1822   // Create a backing variable for the contents of VTable.  The VTable may
1823   // or may not include space for a pointer to RTTI data.
1824   llvm::GlobalValue *VFTable;
1825   VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
1826                                     /*isConstant=*/true, VTableLinkage,
1827                                     /*Initializer=*/nullptr, VTableName);
1828   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1829 
1830   llvm::Comdat *C = nullptr;
1831   if (!VFTableComesFromAnotherTU &&
1832       (llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
1833        (llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
1834         VTableAliasIsRequred)))
1835     C = CGM.getModule().getOrInsertComdat(VFTableName.str());
1836 
1837   // Only insert a pointer into the VFTable for RTTI data if we are not
1838   // importing it.  We never reference the RTTI data directly so there is no
1839   // need to make room for it.
1840   if (VTableAliasIsRequred) {
1841     llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
1842                                  llvm::ConstantInt::get(CGM.Int32Ty, 0),
1843                                  llvm::ConstantInt::get(CGM.Int32Ty, 1)};
1844     // Create a GEP which points just after the first entry in the VFTable,
1845     // this should be the location of the first virtual method.
1846     llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
1847         VTable->getValueType(), VTable, GEPIndices);
1848     if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
1849       VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
1850       if (C)
1851         C->setSelectionKind(llvm::Comdat::Largest);
1852     }
1853     VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
1854                                         /*AddressSpace=*/0, VFTableLinkage,
1855                                         VFTableName.str(), VTableGEP,
1856                                         &CGM.getModule());
1857     VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1858   } else {
1859     // We don't need a GlobalAlias to be a symbol for the VTable if we won't
1860     // be referencing any RTTI data.
1861     // The GlobalVariable will end up being an appropriate definition of the
1862     // VFTable.
1863     VFTable = VTable;
1864   }
1865   if (C)
1866     VTable->setComdat(C);
1867 
1868   if (RD->hasAttr<DLLExportAttr>())
1869     VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1870 
1871   VFTablesMap[ID] = VFTable;
1872   return VTable;
1873 }
1874 
1875 CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1876                                                     GlobalDecl GD,
1877                                                     Address This,
1878                                                     llvm::Type *Ty,
1879                                                     SourceLocation Loc) {
1880   CGBuilderTy &Builder = CGF.Builder;
1881 
1882   Ty = Ty->getPointerTo()->getPointerTo();
1883   Address VPtr =
1884       adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1885 
1886   auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
1887   llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty, MethodDecl->getParent());
1888 
1889   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
1890   MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
1891 
1892   // Compute the identity of the most derived class whose virtual table is
1893   // located at the MethodVFTableLocation ML.
1894   auto getObjectWithVPtr = [&] {
1895     return llvm::find_if(VFTContext.getVFPtrOffsets(
1896                              ML.VBase ? ML.VBase : MethodDecl->getParent()),
1897                          [&](const std::unique_ptr<VPtrInfo> &Info) {
1898                            return Info->FullOffsetInMDC == ML.VFPtrOffset;
1899                          })
1900         ->get()
1901         ->ObjectWithVPtr;
1902   };
1903 
1904   llvm::Value *VFunc;
1905   if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
1906     VFunc = CGF.EmitVTableTypeCheckedLoad(
1907         getObjectWithVPtr(), VTable,
1908         ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
1909   } else {
1910     if (CGM.getCodeGenOpts().PrepareForLTO)
1911       CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
1912 
1913     llvm::Value *VFuncPtr =
1914         Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1915     VFunc = Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
1916   }
1917 
1918   CGCallee Callee(GD, VFunc);
1919   return Callee;
1920 }
1921 
1922 llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
1923     CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
1924     Address This, DeleteOrMemberCallExpr E) {
1925   auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
1926   auto *D = E.dyn_cast<const CXXDeleteExpr *>();
1927   assert((CE != nullptr) ^ (D != nullptr));
1928   assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
1929   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1930 
1931   // We have only one destructor in the vftable but can get both behaviors
1932   // by passing an implicit int parameter.
1933   GlobalDecl GD(Dtor, Dtor_Deleting);
1934   const CGFunctionInfo *FInfo =
1935       &CGM.getTypes().arrangeCXXStructorDeclaration(GD);
1936   llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1937   CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
1938 
1939   ASTContext &Context = getContext();
1940   llvm::Value *ImplicitParam = llvm::ConstantInt::get(
1941       llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1942       DtorType == Dtor_Deleting);
1943 
1944   QualType ThisTy;
1945   if (CE) {
1946     ThisTy = CE->getObjectType();
1947   } else {
1948     ThisTy = D->getDestroyedType();
1949   }
1950 
1951   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1952   RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
1953                                         ImplicitParam, Context.IntTy, CE);
1954   return RV.getScalarVal();
1955 }
1956 
1957 const VBTableGlobals &
1958 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1959   // At this layer, we can key the cache off of a single class, which is much
1960   // easier than caching each vbtable individually.
1961   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1962   bool Added;
1963   std::tie(Entry, Added) =
1964       VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1965   VBTableGlobals &VBGlobals = Entry->second;
1966   if (!Added)
1967     return VBGlobals;
1968 
1969   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1970   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1971 
1972   // Cache the globals for all vbtables so we don't have to recompute the
1973   // mangled names.
1974   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1975   for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1976                                       E = VBGlobals.VBTables->end();
1977        I != E; ++I) {
1978     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1979   }
1980 
1981   return VBGlobals;
1982 }
1983 
1984 llvm::Function *
1985 MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
1986                                         const MethodVFTableLocation &ML) {
1987   assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
1988          "can't form pointers to ctors or virtual dtors");
1989 
1990   // Calculate the mangled name.
1991   SmallString<256> ThunkName;
1992   llvm::raw_svector_ostream Out(ThunkName);
1993   getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
1994 
1995   // If the thunk has been generated previously, just return it.
1996   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1997     return cast<llvm::Function>(GV);
1998 
1999   // Create the llvm::Function.
2000   const CGFunctionInfo &FnInfo =
2001       CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
2002   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
2003   llvm::Function *ThunkFn =
2004       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
2005                              ThunkName.str(), &CGM.getModule());
2006   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
2007 
2008   ThunkFn->setLinkage(MD->isExternallyVisible()
2009                           ? llvm::GlobalValue::LinkOnceODRLinkage
2010                           : llvm::GlobalValue::InternalLinkage);
2011   if (MD->isExternallyVisible())
2012     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
2013 
2014   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
2015   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
2016 
2017   // Add the "thunk" attribute so that LLVM knows that the return type is
2018   // meaningless. These thunks can be used to call functions with differing
2019   // return types, and the caller is required to cast the prototype
2020   // appropriately to extract the correct value.
2021   ThunkFn->addFnAttr("thunk");
2022 
2023   // These thunks can be compared, so they are not unnamed.
2024   ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
2025 
2026   // Start codegen.
2027   CodeGenFunction CGF(CGM);
2028   CGF.CurGD = GlobalDecl(MD);
2029   CGF.CurFuncIsThunk = true;
2030 
2031   // Build FunctionArgs, but only include the implicit 'this' parameter
2032   // declaration.
2033   FunctionArgList FunctionArgs;
2034   buildThisParam(CGF, FunctionArgs);
2035 
2036   // Start defining the function.
2037   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
2038                     FunctionArgs, MD->getLocation(), SourceLocation());
2039   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
2040 
2041   // Load the vfptr and then callee from the vftable.  The callee should have
2042   // adjusted 'this' so that the vfptr is at offset zero.
2043   llvm::Value *VTable = CGF.GetVTablePtr(
2044       getThisAddress(CGF), ThunkTy->getPointerTo()->getPointerTo(), MD->getParent());
2045 
2046   llvm::Value *VFuncPtr =
2047       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
2048   llvm::Value *Callee =
2049     CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.getPointerAlign());
2050 
2051   CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
2052 
2053   return ThunkFn;
2054 }
2055 
2056 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
2057   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
2058   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
2059     const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
2060     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
2061     if (GV->isDeclaration())
2062       emitVBTableDefinition(*VBT, RD, GV);
2063   }
2064 }
2065 
2066 llvm::GlobalVariable *
2067 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
2068                                   llvm::GlobalVariable::LinkageTypes Linkage) {
2069   SmallString<256> OutName;
2070   llvm::raw_svector_ostream Out(OutName);
2071   getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
2072   StringRef Name = OutName.str();
2073 
2074   llvm::ArrayType *VBTableType =
2075       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
2076 
2077   assert(!CGM.getModule().getNamedGlobal(Name) &&
2078          "vbtable with this name already exists: mangling bug?");
2079   CharUnits Alignment =
2080       CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
2081   llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
2082       Name, VBTableType, Linkage, Alignment.getQuantity());
2083   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2084 
2085   if (RD->hasAttr<DLLImportAttr>())
2086     GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2087   else if (RD->hasAttr<DLLExportAttr>())
2088     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2089 
2090   if (!GV->hasExternalLinkage())
2091     emitVBTableDefinition(VBT, RD, GV);
2092 
2093   return GV;
2094 }
2095 
2096 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
2097                                             const CXXRecordDecl *RD,
2098                                             llvm::GlobalVariable *GV) const {
2099   const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
2100 
2101   assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
2102          "should only emit vbtables for classes with vbtables");
2103 
2104   const ASTRecordLayout &BaseLayout =
2105       getContext().getASTRecordLayout(VBT.IntroducingObject);
2106   const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
2107 
2108   SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
2109                                            nullptr);
2110 
2111   // The offset from ObjectWithVPtr's vbptr to itself always leads.
2112   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
2113   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
2114 
2115   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
2116   for (const auto &I : ObjectWithVPtr->vbases()) {
2117     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
2118     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
2119     assert(!Offset.isNegative());
2120 
2121     // Make it relative to the subobject vbptr.
2122     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
2123     if (VBT.getVBaseWithVPtr())
2124       CompleteVBPtrOffset +=
2125           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
2126     Offset -= CompleteVBPtrOffset;
2127 
2128     unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
2129     assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
2130     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
2131   }
2132 
2133   assert(Offsets.size() ==
2134          cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
2135                                ->getElementType())->getNumElements());
2136   llvm::ArrayType *VBTableType =
2137     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
2138   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
2139   GV->setInitializer(Init);
2140 
2141   if (RD->hasAttr<DLLImportAttr>())
2142     GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
2143 }
2144 
2145 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
2146                                                     Address This,
2147                                                     const ThisAdjustment &TA) {
2148   if (TA.isEmpty())
2149     return This.getPointer();
2150 
2151   This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
2152 
2153   llvm::Value *V;
2154   if (TA.Virtual.isEmpty()) {
2155     V = This.getPointer();
2156   } else {
2157     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
2158     // Adjust the this argument based on the vtordisp value.
2159     Address VtorDispPtr =
2160         CGF.Builder.CreateConstInBoundsByteGEP(This,
2161                  CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
2162     VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
2163     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
2164     V = CGF.Builder.CreateGEP(This.getPointer(),
2165                               CGF.Builder.CreateNeg(VtorDisp));
2166 
2167     // Unfortunately, having applied the vtordisp means that we no
2168     // longer really have a known alignment for the vbptr step.
2169     // We'll assume the vbptr is pointer-aligned.
2170 
2171     if (TA.Virtual.Microsoft.VBPtrOffset) {
2172       // If the final overrider is defined in a virtual base other than the one
2173       // that holds the vfptr, we have to use a vtordispex thunk which looks up
2174       // the vbtable of the derived class.
2175       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
2176       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
2177       llvm::Value *VBPtr;
2178       llvm::Value *VBaseOffset =
2179           GetVBaseOffsetFromVBPtr(CGF, Address(V, CGF.getPointerAlign()),
2180                                   -TA.Virtual.Microsoft.VBPtrOffset,
2181                                   TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
2182       V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2183     }
2184   }
2185 
2186   if (TA.NonVirtual) {
2187     // Non-virtual adjustment might result in a pointer outside the allocated
2188     // object, e.g. if the final overrider class is laid out after the virtual
2189     // base that declares a method in the most derived class.
2190     V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
2191   }
2192 
2193   // Don't need to bitcast back, the call CodeGen will handle this.
2194   return V;
2195 }
2196 
2197 llvm::Value *
2198 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
2199                                          const ReturnAdjustment &RA) {
2200   if (RA.isEmpty())
2201     return Ret.getPointer();
2202 
2203   auto OrigTy = Ret.getType();
2204   Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
2205 
2206   llvm::Value *V = Ret.getPointer();
2207   if (RA.Virtual.Microsoft.VBIndex) {
2208     assert(RA.Virtual.Microsoft.VBIndex > 0);
2209     int32_t IntSize = CGF.getIntSize().getQuantity();
2210     llvm::Value *VBPtr;
2211     llvm::Value *VBaseOffset =
2212         GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
2213                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
2214     V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
2215   }
2216 
2217   if (RA.NonVirtual)
2218     V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
2219 
2220   // Cast back to the original type.
2221   return CGF.Builder.CreateBitCast(V, OrigTy);
2222 }
2223 
2224 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
2225                                    QualType elementType) {
2226   // Microsoft seems to completely ignore the possibility of a
2227   // two-argument usual deallocation function.
2228   return elementType.isDestructedType();
2229 }
2230 
2231 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
2232   // Microsoft seems to completely ignore the possibility of a
2233   // two-argument usual deallocation function.
2234   return expr->getAllocatedType().isDestructedType();
2235 }
2236 
2237 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
2238   // The array cookie is always a size_t; we then pad that out to the
2239   // alignment of the element type.
2240   ASTContext &Ctx = getContext();
2241   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
2242                   Ctx.getTypeAlignInChars(type));
2243 }
2244 
2245 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
2246                                                   Address allocPtr,
2247                                                   CharUnits cookieSize) {
2248   Address numElementsPtr =
2249     CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
2250   return CGF.Builder.CreateLoad(numElementsPtr);
2251 }
2252 
2253 Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
2254                                                Address newPtr,
2255                                                llvm::Value *numElements,
2256                                                const CXXNewExpr *expr,
2257                                                QualType elementType) {
2258   assert(requiresArrayCookie(expr));
2259 
2260   // The size of the cookie.
2261   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
2262 
2263   // Compute an offset to the cookie.
2264   Address cookiePtr = newPtr;
2265 
2266   // Write the number of elements into the appropriate slot.
2267   Address numElementsPtr
2268     = CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
2269   CGF.Builder.CreateStore(numElements, numElementsPtr);
2270 
2271   // Finally, compute a pointer to the actual data buffer by skipping
2272   // over the cookie completely.
2273   return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
2274 }
2275 
2276 static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
2277                                         llvm::FunctionCallee Dtor,
2278                                         llvm::Constant *Addr) {
2279   // Create a function which calls the destructor.
2280   llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
2281 
2282   // extern "C" int __tlregdtor(void (*f)(void));
2283   llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
2284       CGF.IntTy, DtorStub->getType(), /*isVarArg=*/false);
2285 
2286   llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
2287       TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), /*Local=*/true);
2288   if (llvm::Function *TLRegDtorFn =
2289           dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
2290     TLRegDtorFn->setDoesNotThrow();
2291 
2292   CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
2293 }
2294 
2295 void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
2296                                          llvm::FunctionCallee Dtor,
2297                                          llvm::Constant *Addr) {
2298   if (D.isNoDestroy(CGM.getContext()))
2299     return;
2300 
2301   if (D.getTLSKind())
2302     return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
2303 
2304   // The default behavior is to use atexit.
2305   CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
2306 }
2307 
2308 void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
2309     CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
2310     ArrayRef<llvm::Function *> CXXThreadLocalInits,
2311     ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
2312   if (CXXThreadLocalInits.empty())
2313     return;
2314 
2315   CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
2316                                   llvm::Triple::x86
2317                               ? "/include:___dyn_tls_init@12"
2318                               : "/include:__dyn_tls_init");
2319 
2320   // This will create a GV in the .CRT$XDU section.  It will point to our
2321   // initialization function.  The CRT will call all of these function
2322   // pointers at start-up time and, eventually, at thread-creation time.
2323   auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
2324     llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
2325         CGM.getModule(), InitFunc->getType(), /*isConstant=*/true,
2326         llvm::GlobalVariable::InternalLinkage, InitFunc,
2327         Twine(InitFunc->getName(), "$initializer$"));
2328     InitFuncPtr->setSection(".CRT$XDU");
2329     // This variable has discardable linkage, we have to add it to @llvm.used to
2330     // ensure it won't get discarded.
2331     CGM.addUsedGlobal(InitFuncPtr);
2332     return InitFuncPtr;
2333   };
2334 
2335   std::vector<llvm::Function *> NonComdatInits;
2336   for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
2337     llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
2338         CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
2339     llvm::Function *F = CXXThreadLocalInits[I];
2340 
2341     // If the GV is already in a comdat group, then we have to join it.
2342     if (llvm::Comdat *C = GV->getComdat())
2343       AddToXDU(F)->setComdat(C);
2344     else
2345       NonComdatInits.push_back(F);
2346   }
2347 
2348   if (!NonComdatInits.empty()) {
2349     llvm::FunctionType *FTy =
2350         llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
2351     llvm::Function *InitFunc = CGM.CreateGlobalInitOrDestructFunction(
2352         FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
2353         SourceLocation(), /*TLS=*/true);
2354     CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
2355 
2356     AddToXDU(InitFunc);
2357   }
2358 }
2359 
2360 LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
2361                                                      const VarDecl *VD,
2362                                                      QualType LValType) {
2363   CGF.CGM.ErrorUnsupported(VD, "thread wrappers");
2364   return LValue();
2365 }
2366 
2367 static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
2368   StringRef VarName("_Init_thread_epoch");
2369   CharUnits Align = CGM.getIntAlign();
2370   if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
2371     return ConstantAddress(GV, Align);
2372   auto *GV = new llvm::GlobalVariable(
2373       CGM.getModule(), CGM.IntTy,
2374       /*isConstant=*/false, llvm::GlobalVariable::ExternalLinkage,
2375       /*Initializer=*/nullptr, VarName,
2376       /*InsertBefore=*/nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
2377   GV->setAlignment(Align.getAsAlign());
2378   return ConstantAddress(GV, Align);
2379 }
2380 
2381 static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
2382   llvm::FunctionType *FTy =
2383       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2384                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2385   return CGM.CreateRuntimeFunction(
2386       FTy, "_Init_thread_header",
2387       llvm::AttributeList::get(CGM.getLLVMContext(),
2388                                llvm::AttributeList::FunctionIndex,
2389                                llvm::Attribute::NoUnwind),
2390       /*Local=*/true);
2391 }
2392 
2393 static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
2394   llvm::FunctionType *FTy =
2395       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2396                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2397   return CGM.CreateRuntimeFunction(
2398       FTy, "_Init_thread_footer",
2399       llvm::AttributeList::get(CGM.getLLVMContext(),
2400                                llvm::AttributeList::FunctionIndex,
2401                                llvm::Attribute::NoUnwind),
2402       /*Local=*/true);
2403 }
2404 
2405 static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
2406   llvm::FunctionType *FTy =
2407       llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
2408                               CGM.IntTy->getPointerTo(), /*isVarArg=*/false);
2409   return CGM.CreateRuntimeFunction(
2410       FTy, "_Init_thread_abort",
2411       llvm::AttributeList::get(CGM.getLLVMContext(),
2412                                llvm::AttributeList::FunctionIndex,
2413                                llvm::Attribute::NoUnwind),
2414       /*Local=*/true);
2415 }
2416 
2417 namespace {
2418 struct ResetGuardBit final : EHScopeStack::Cleanup {
2419   Address Guard;
2420   unsigned GuardNum;
2421   ResetGuardBit(Address Guard, unsigned GuardNum)
2422       : Guard(Guard), GuardNum(GuardNum) {}
2423 
2424   void Emit(CodeGenFunction &CGF, Flags flags) override {
2425     // Reset the bit in the mask so that the static variable may be
2426     // reinitialized.
2427     CGBuilderTy &Builder = CGF.Builder;
2428     llvm::LoadInst *LI = Builder.CreateLoad(Guard);
2429     llvm::ConstantInt *Mask =
2430         llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
2431     Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
2432   }
2433 };
2434 
2435 struct CallInitThreadAbort final : EHScopeStack::Cleanup {
2436   llvm::Value *Guard;
2437   CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
2438 
2439   void Emit(CodeGenFunction &CGF, Flags flags) override {
2440     // Calling _Init_thread_abort will reset the guard's state.
2441     CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
2442   }
2443 };
2444 }
2445 
2446 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
2447                                       llvm::GlobalVariable *GV,
2448                                       bool PerformInit) {
2449   // MSVC only uses guards for static locals.
2450   if (!D.isStaticLocal()) {
2451     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
2452     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
2453     llvm::Function *F = CGF.CurFn;
2454     F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
2455     F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
2456     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2457     return;
2458   }
2459 
2460   bool ThreadlocalStatic = D.getTLSKind();
2461   bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
2462 
2463   // Thread-safe static variables which aren't thread-specific have a
2464   // per-variable guard.
2465   bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
2466 
2467   CGBuilderTy &Builder = CGF.Builder;
2468   llvm::IntegerType *GuardTy = CGF.Int32Ty;
2469   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
2470   CharUnits GuardAlign = CharUnits::fromQuantity(4);
2471 
2472   // Get the guard variable for this function if we have one already.
2473   GuardInfo *GI = nullptr;
2474   if (ThreadlocalStatic)
2475     GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
2476   else if (!ThreadsafeStatic)
2477     GI = &GuardVariableMap[D.getDeclContext()];
2478 
2479   llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
2480   unsigned GuardNum;
2481   if (D.isExternallyVisible()) {
2482     // Externally visible variables have to be numbered in Sema to properly
2483     // handle unreachable VarDecls.
2484     GuardNum = getContext().getStaticLocalNumber(&D);
2485     assert(GuardNum > 0);
2486     GuardNum--;
2487   } else if (HasPerVariableGuard) {
2488     GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
2489   } else {
2490     // Non-externally visible variables are numbered here in CodeGen.
2491     GuardNum = GI->BitIndex++;
2492   }
2493 
2494   if (!HasPerVariableGuard && GuardNum >= 32) {
2495     if (D.isExternallyVisible())
2496       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
2497     GuardNum %= 32;
2498     GuardVar = nullptr;
2499   }
2500 
2501   if (!GuardVar) {
2502     // Mangle the name for the guard.
2503     SmallString<256> GuardName;
2504     {
2505       llvm::raw_svector_ostream Out(GuardName);
2506       if (HasPerVariableGuard)
2507         getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
2508                                                                Out);
2509       else
2510         getMangleContext().mangleStaticGuardVariable(&D, Out);
2511     }
2512 
2513     // Create the guard variable with a zero-initializer. Just absorb linkage,
2514     // visibility and dll storage class from the guarded variable.
2515     GuardVar =
2516         new llvm::GlobalVariable(CGM.getModule(), GuardTy, /*isConstant=*/false,
2517                                  GV->getLinkage(), Zero, GuardName.str());
2518     GuardVar->setVisibility(GV->getVisibility());
2519     GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
2520     GuardVar->setAlignment(GuardAlign.getAsAlign());
2521     if (GuardVar->isWeakForLinker())
2522       GuardVar->setComdat(
2523           CGM.getModule().getOrInsertComdat(GuardVar->getName()));
2524     if (D.getTLSKind())
2525       GuardVar->setThreadLocal(true);
2526     if (GI && !HasPerVariableGuard)
2527       GI->Guard = GuardVar;
2528   }
2529 
2530   ConstantAddress GuardAddr(GuardVar, GuardAlign);
2531 
2532   assert(GuardVar->getLinkage() == GV->getLinkage() &&
2533          "static local from the same function had different linkage");
2534 
2535   if (!HasPerVariableGuard) {
2536     // Pseudo code for the test:
2537     // if (!(GuardVar & MyGuardBit)) {
2538     //   GuardVar |= MyGuardBit;
2539     //   ... initialize the object ...;
2540     // }
2541 
2542     // Test our bit from the guard variable.
2543     llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
2544     llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
2545     llvm::Value *NeedsInit =
2546         Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
2547     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2548     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2549     CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
2550                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2551 
2552     // Set our bit in the guard variable and emit the initializer and add a global
2553     // destructor if appropriate.
2554     CGF.EmitBlock(InitBlock);
2555     Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
2556     CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
2557     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2558     CGF.PopCleanupBlock();
2559     Builder.CreateBr(EndBlock);
2560 
2561     // Continue.
2562     CGF.EmitBlock(EndBlock);
2563   } else {
2564     // Pseudo code for the test:
2565     // if (TSS > _Init_thread_epoch) {
2566     //   _Init_thread_header(&TSS);
2567     //   if (TSS == -1) {
2568     //     ... initialize the object ...;
2569     //     _Init_thread_footer(&TSS);
2570     //   }
2571     // }
2572     //
2573     // The algorithm is almost identical to what can be found in the appendix
2574     // found in N2325.
2575 
2576     // This BasicBLock determines whether or not we have any work to do.
2577     llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
2578     FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2579     llvm::LoadInst *InitThreadEpoch =
2580         Builder.CreateLoad(getInitThreadEpochPtr(CGM));
2581     llvm::Value *IsUninitialized =
2582         Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
2583     llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
2584     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
2585     CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
2586                                  CodeGenFunction::GuardKind::VariableGuard, &D);
2587 
2588     // This BasicBlock attempts to determine whether or not this thread is
2589     // responsible for doing the initialization.
2590     CGF.EmitBlock(AttemptInitBlock);
2591     CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
2592                                 GuardAddr.getPointer());
2593     llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
2594     SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
2595     llvm::Value *ShouldDoInit =
2596         Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
2597     llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
2598     Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
2599 
2600     // Ok, we ended up getting selected as the initializing thread.
2601     CGF.EmitBlock(InitBlock);
2602     CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
2603     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
2604     CGF.PopCleanupBlock();
2605     CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
2606                                 GuardAddr.getPointer());
2607     Builder.CreateBr(EndBlock);
2608 
2609     CGF.EmitBlock(EndBlock);
2610   }
2611 }
2612 
2613 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
2614   // Null-ness for function memptrs only depends on the first field, which is
2615   // the function pointer.  The rest don't matter, so we can zero initialize.
2616   if (MPT->isMemberFunctionPointer())
2617     return true;
2618 
2619   // The virtual base adjustment field is always -1 for null, so if we have one
2620   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
2621   // valid field offset.
2622   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2623   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2624   return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
2625           RD->nullFieldOffsetIsZero());
2626 }
2627 
2628 llvm::Type *
2629 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
2630   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2631   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2632   llvm::SmallVector<llvm::Type *, 4> fields;
2633   if (MPT->isMemberFunctionPointer())
2634     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
2635   else
2636     fields.push_back(CGM.IntTy);  // FieldOffset
2637 
2638   if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2639                                        Inheritance))
2640     fields.push_back(CGM.IntTy);
2641   if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2642     fields.push_back(CGM.IntTy);
2643   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2644     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
2645 
2646   if (fields.size() == 1)
2647     return fields[0];
2648   return llvm::StructType::get(CGM.getLLVMContext(), fields);
2649 }
2650 
2651 void MicrosoftCXXABI::
2652 GetNullMemberPointerFields(const MemberPointerType *MPT,
2653                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
2654   assert(fields.empty());
2655   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2656   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2657   if (MPT->isMemberFunctionPointer()) {
2658     // FunctionPointerOrVirtualThunk
2659     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2660   } else {
2661     if (RD->nullFieldOffsetIsZero())
2662       fields.push_back(getZeroInt());  // FieldOffset
2663     else
2664       fields.push_back(getAllOnesInt());  // FieldOffset
2665   }
2666 
2667   if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
2668                                        Inheritance))
2669     fields.push_back(getZeroInt());
2670   if (inheritanceModelHasVBPtrOffsetField(Inheritance))
2671     fields.push_back(getZeroInt());
2672   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2673     fields.push_back(getAllOnesInt());
2674 }
2675 
2676 llvm::Constant *
2677 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
2678   llvm::SmallVector<llvm::Constant *, 4> fields;
2679   GetNullMemberPointerFields(MPT, fields);
2680   if (fields.size() == 1)
2681     return fields[0];
2682   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
2683   assert(Res->getType() == ConvertMemberPointerType(MPT));
2684   return Res;
2685 }
2686 
2687 llvm::Constant *
2688 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
2689                                        bool IsMemberFunction,
2690                                        const CXXRecordDecl *RD,
2691                                        CharUnits NonVirtualBaseAdjustment,
2692                                        unsigned VBTableIndex) {
2693   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2694 
2695   // Single inheritance class member pointer are represented as scalars instead
2696   // of aggregates.
2697   if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
2698     return FirstField;
2699 
2700   llvm::SmallVector<llvm::Constant *, 4> fields;
2701   fields.push_back(FirstField);
2702 
2703   if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
2704     fields.push_back(llvm::ConstantInt::get(
2705       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
2706 
2707   if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
2708     CharUnits Offs = CharUnits::Zero();
2709     if (VBTableIndex)
2710       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
2711     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
2712   }
2713 
2714   // The rest of the fields are adjusted by conversions to a more derived class.
2715   if (inheritanceModelHasVBTableOffsetField(Inheritance))
2716     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
2717 
2718   return llvm::ConstantStruct::getAnon(fields);
2719 }
2720 
2721 llvm::Constant *
2722 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
2723                                        CharUnits offset) {
2724   return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
2725 }
2726 
2727 llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
2728                                                        CharUnits offset) {
2729   if (RD->getMSInheritanceModel() ==
2730       MSInheritanceModel::Virtual)
2731     offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
2732   llvm::Constant *FirstField =
2733     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
2734   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
2735                                CharUnits::Zero(), /*VBTableIndex=*/0);
2736 }
2737 
2738 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
2739                                                    QualType MPType) {
2740   const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
2741   const ValueDecl *MPD = MP.getMemberPointerDecl();
2742   if (!MPD)
2743     return EmitNullMemberPointer(DstTy);
2744 
2745   ASTContext &Ctx = getContext();
2746   ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
2747 
2748   llvm::Constant *C;
2749   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
2750     C = EmitMemberFunctionPointer(MD);
2751   } else {
2752     // For a pointer to data member, start off with the offset of the field in
2753     // the class in which it was declared, and convert from there if necessary.
2754     // For indirect field decls, get the outermost anonymous field and use the
2755     // parent class.
2756     CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
2757     const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
2758     if (!FD)
2759       FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
2760     const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
2761     RD = RD->getMostRecentNonInjectedDecl();
2762     C = EmitMemberDataPointer(RD, FieldOffset);
2763   }
2764 
2765   if (!MemberPointerPath.empty()) {
2766     const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
2767     const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
2768     const MemberPointerType *SrcTy =
2769         Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
2770             ->castAs<MemberPointerType>();
2771 
2772     bool DerivedMember = MP.isMemberPointerToDerivedMember();
2773     SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
2774     const CXXRecordDecl *PrevRD = SrcRD;
2775     for (const CXXRecordDecl *PathElem : MemberPointerPath) {
2776       const CXXRecordDecl *Base = nullptr;
2777       const CXXRecordDecl *Derived = nullptr;
2778       if (DerivedMember) {
2779         Base = PathElem;
2780         Derived = PrevRD;
2781       } else {
2782         Base = PrevRD;
2783         Derived = PathElem;
2784       }
2785       for (const CXXBaseSpecifier &BS : Derived->bases())
2786         if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
2787             Base->getCanonicalDecl())
2788           DerivedToBasePath.push_back(&BS);
2789       PrevRD = PathElem;
2790     }
2791     assert(DerivedToBasePath.size() == MemberPointerPath.size());
2792 
2793     CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
2794                                 : CK_BaseToDerivedMemberPointer;
2795     C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
2796                                     DerivedToBasePath.end(), C);
2797   }
2798   return C;
2799 }
2800 
2801 llvm::Constant *
2802 MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
2803   assert(MD->isInstance() && "Member function must not be static!");
2804 
2805   CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
2806   const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
2807   CodeGenTypes &Types = CGM.getTypes();
2808 
2809   unsigned VBTableIndex = 0;
2810   llvm::Constant *FirstField;
2811   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
2812   if (!MD->isVirtual()) {
2813     llvm::Type *Ty;
2814     // Check whether the function has a computable LLVM signature.
2815     if (Types.isFuncTypeConvertible(FPT)) {
2816       // The function has a computable LLVM signature; use the correct type.
2817       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
2818     } else {
2819       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
2820       // function type is incomplete.
2821       Ty = CGM.PtrDiffTy;
2822     }
2823     FirstField = CGM.GetAddrOfFunction(MD, Ty);
2824   } else {
2825     auto &VTableContext = CGM.getMicrosoftVTableContext();
2826     MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
2827     FirstField = EmitVirtualMemPtrThunk(MD, ML);
2828     // Include the vfptr adjustment if the method is in a non-primary vftable.
2829     NonVirtualBaseAdjustment += ML.VFPtrOffset;
2830     if (ML.VBase)
2831       VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
2832   }
2833 
2834   if (VBTableIndex == 0 &&
2835       RD->getMSInheritanceModel() ==
2836           MSInheritanceModel::Virtual)
2837     NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
2838 
2839   // The rest of the fields are common with data member pointers.
2840   FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
2841   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
2842                                NonVirtualBaseAdjustment, VBTableIndex);
2843 }
2844 
2845 /// Member pointers are the same if they're either bitwise identical *or* both
2846 /// null.  Null-ness for function members is determined by the first field,
2847 /// while for data member pointers we must compare all fields.
2848 llvm::Value *
2849 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
2850                                              llvm::Value *L,
2851                                              llvm::Value *R,
2852                                              const MemberPointerType *MPT,
2853                                              bool Inequality) {
2854   CGBuilderTy &Builder = CGF.Builder;
2855 
2856   // Handle != comparisons by switching the sense of all boolean operations.
2857   llvm::ICmpInst::Predicate Eq;
2858   llvm::Instruction::BinaryOps And, Or;
2859   if (Inequality) {
2860     Eq = llvm::ICmpInst::ICMP_NE;
2861     And = llvm::Instruction::Or;
2862     Or = llvm::Instruction::And;
2863   } else {
2864     Eq = llvm::ICmpInst::ICMP_EQ;
2865     And = llvm::Instruction::And;
2866     Or = llvm::Instruction::Or;
2867   }
2868 
2869   // If this is a single field member pointer (single inheritance), this is a
2870   // single icmp.
2871   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2872   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
2873   if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
2874                                       Inheritance))
2875     return Builder.CreateICmp(Eq, L, R);
2876 
2877   // Compare the first field.
2878   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
2879   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
2880   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
2881 
2882   // Compare everything other than the first field.
2883   llvm::Value *Res = nullptr;
2884   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
2885   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
2886     llvm::Value *LF = Builder.CreateExtractValue(L, I);
2887     llvm::Value *RF = Builder.CreateExtractValue(R, I);
2888     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
2889     if (Res)
2890       Res = Builder.CreateBinOp(And, Res, Cmp);
2891     else
2892       Res = Cmp;
2893   }
2894 
2895   // Check if the first field is 0 if this is a function pointer.
2896   if (MPT->isMemberFunctionPointer()) {
2897     // (l1 == r1 && ...) || l0 == 0
2898     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
2899     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
2900     Res = Builder.CreateBinOp(Or, Res, IsZero);
2901   }
2902 
2903   // Combine the comparison of the first field, which must always be true for
2904   // this comparison to succeeed.
2905   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
2906 }
2907 
2908 llvm::Value *
2909 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
2910                                             llvm::Value *MemPtr,
2911                                             const MemberPointerType *MPT) {
2912   CGBuilderTy &Builder = CGF.Builder;
2913   llvm::SmallVector<llvm::Constant *, 4> fields;
2914   // We only need one field for member functions.
2915   if (MPT->isMemberFunctionPointer())
2916     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
2917   else
2918     GetNullMemberPointerFields(MPT, fields);
2919   assert(!fields.empty());
2920   llvm::Value *FirstField = MemPtr;
2921   if (MemPtr->getType()->isStructTy())
2922     FirstField = Builder.CreateExtractValue(MemPtr, 0);
2923   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
2924 
2925   // For function member pointers, we only need to test the function pointer
2926   // field.  The other fields if any can be garbage.
2927   if (MPT->isMemberFunctionPointer())
2928     return Res;
2929 
2930   // Otherwise, emit a series of compares and combine the results.
2931   for (int I = 1, E = fields.size(); I < E; ++I) {
2932     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
2933     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
2934     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
2935   }
2936   return Res;
2937 }
2938 
2939 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
2940                                                   llvm::Constant *Val) {
2941   // Function pointers are null if the pointer in the first field is null.
2942   if (MPT->isMemberFunctionPointer()) {
2943     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
2944       Val->getAggregateElement(0U) : Val;
2945     return FirstField->isNullValue();
2946   }
2947 
2948   // If it's not a function pointer and it's zero initializable, we can easily
2949   // check zero.
2950   if (isZeroInitializable(MPT) && Val->isNullValue())
2951     return true;
2952 
2953   // Otherwise, break down all the fields for comparison.  Hopefully these
2954   // little Constants are reused, while a big null struct might not be.
2955   llvm::SmallVector<llvm::Constant *, 4> Fields;
2956   GetNullMemberPointerFields(MPT, Fields);
2957   if (Fields.size() == 1) {
2958     assert(Val->getType()->isIntegerTy());
2959     return Val == Fields[0];
2960   }
2961 
2962   unsigned I, E;
2963   for (I = 0, E = Fields.size(); I != E; ++I) {
2964     if (Val->getAggregateElement(I) != Fields[I])
2965       break;
2966   }
2967   return I == E;
2968 }
2969 
2970 llvm::Value *
2971 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
2972                                          Address This,
2973                                          llvm::Value *VBPtrOffset,
2974                                          llvm::Value *VBTableOffset,
2975                                          llvm::Value **VBPtrOut) {
2976   CGBuilderTy &Builder = CGF.Builder;
2977   // Load the vbtable pointer from the vbptr in the instance.
2978   This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
2979   llvm::Value *VBPtr =
2980     Builder.CreateInBoundsGEP(This.getPointer(), VBPtrOffset, "vbptr");
2981   if (VBPtrOut) *VBPtrOut = VBPtr;
2982   VBPtr = Builder.CreateBitCast(VBPtr,
2983             CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
2984 
2985   CharUnits VBPtrAlign;
2986   if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
2987     VBPtrAlign = This.getAlignment().alignmentAtOffset(
2988                                    CharUnits::fromQuantity(CI->getSExtValue()));
2989   } else {
2990     VBPtrAlign = CGF.getPointerAlign();
2991   }
2992 
2993   llvm::Value *VBTable = Builder.CreateAlignedLoad(VBPtr, VBPtrAlign, "vbtable");
2994 
2995   // Translate from byte offset to table index. It improves analyzability.
2996   llvm::Value *VBTableIndex = Builder.CreateAShr(
2997       VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
2998       "vbtindex", /*isExact=*/true);
2999 
3000   // Load an i32 offset from the vb-table.
3001   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableIndex);
3002   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
3003   return Builder.CreateAlignedLoad(VBaseOffs, CharUnits::fromQuantity(4),
3004                                    "vbase_offs");
3005 }
3006 
3007 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
3008 // it.
3009 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
3010     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
3011     Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
3012   CGBuilderTy &Builder = CGF.Builder;
3013   Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
3014   llvm::BasicBlock *OriginalBB = nullptr;
3015   llvm::BasicBlock *SkipAdjustBB = nullptr;
3016   llvm::BasicBlock *VBaseAdjustBB = nullptr;
3017 
3018   // In the unspecified inheritance model, there might not be a vbtable at all,
3019   // in which case we need to skip the virtual base lookup.  If there is a
3020   // vbtable, the first entry is a no-op entry that gives back the original
3021   // base, so look for a virtual base adjustment offset of zero.
3022   if (VBPtrOffset) {
3023     OriginalBB = Builder.GetInsertBlock();
3024     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
3025     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
3026     llvm::Value *IsVirtual =
3027       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
3028                            "memptr.is_vbase");
3029     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
3030     CGF.EmitBlock(VBaseAdjustBB);
3031   }
3032 
3033   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
3034   // know the vbptr offset.
3035   if (!VBPtrOffset) {
3036     CharUnits offs = CharUnits::Zero();
3037     if (!RD->hasDefinition()) {
3038       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
3039       unsigned DiagID = Diags.getCustomDiagID(
3040           DiagnosticsEngine::Error,
3041           "member pointer representation requires a "
3042           "complete class type for %0 to perform this expression");
3043       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
3044     } else if (RD->getNumVBases())
3045       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
3046     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
3047   }
3048   llvm::Value *VBPtr = nullptr;
3049   llvm::Value *VBaseOffs =
3050     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
3051   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
3052 
3053   // Merge control flow with the case where we didn't have to adjust.
3054   if (VBaseAdjustBB) {
3055     Builder.CreateBr(SkipAdjustBB);
3056     CGF.EmitBlock(SkipAdjustBB);
3057     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
3058     Phi->addIncoming(Base.getPointer(), OriginalBB);
3059     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
3060     return Phi;
3061   }
3062   return AdjustedBase;
3063 }
3064 
3065 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
3066     CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
3067     const MemberPointerType *MPT) {
3068   assert(MPT->isMemberDataPointer());
3069   unsigned AS = Base.getAddressSpace();
3070   llvm::Type *PType =
3071       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
3072   CGBuilderTy &Builder = CGF.Builder;
3073   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3074   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3075 
3076   // Extract the fields we need, regardless of model.  We'll apply them if we
3077   // have them.
3078   llvm::Value *FieldOffset = MemPtr;
3079   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3080   llvm::Value *VBPtrOffset = nullptr;
3081   if (MemPtr->getType()->isStructTy()) {
3082     // We need to extract values.
3083     unsigned I = 0;
3084     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
3085     if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3086       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3087     if (inheritanceModelHasVBTableOffsetField(Inheritance))
3088       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3089   }
3090 
3091   llvm::Value *Addr;
3092   if (VirtualBaseAdjustmentOffset) {
3093     Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
3094                              VBPtrOffset);
3095   } else {
3096     Addr = Base.getPointer();
3097   }
3098 
3099   // Cast to char*.
3100   Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
3101 
3102   // Apply the offset, which we assume is non-null.
3103   Addr = Builder.CreateInBoundsGEP(Addr, FieldOffset, "memptr.offset");
3104 
3105   // Cast the address to the appropriate pointer type, adopting the address
3106   // space of the base pointer.
3107   return Builder.CreateBitCast(Addr, PType);
3108 }
3109 
3110 llvm::Value *
3111 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
3112                                              const CastExpr *E,
3113                                              llvm::Value *Src) {
3114   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
3115          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
3116          E->getCastKind() == CK_ReinterpretMemberPointer);
3117 
3118   // Use constant emission if we can.
3119   if (isa<llvm::Constant>(Src))
3120     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
3121 
3122   // We may be adding or dropping fields from the member pointer, so we need
3123   // both types and the inheritance models of both records.
3124   const MemberPointerType *SrcTy =
3125     E->getSubExpr()->getType()->castAs<MemberPointerType>();
3126   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3127   bool IsFunc = SrcTy->isMemberFunctionPointer();
3128 
3129   // If the classes use the same null representation, reinterpret_cast is a nop.
3130   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
3131   if (IsReinterpret && IsFunc)
3132     return Src;
3133 
3134   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3135   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3136   if (IsReinterpret &&
3137       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
3138     return Src;
3139 
3140   CGBuilderTy &Builder = CGF.Builder;
3141 
3142   // Branch past the conversion if Src is null.
3143   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
3144   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
3145 
3146   // C++ 5.2.10p9: The null member pointer value is converted to the null member
3147   //   pointer value of the destination type.
3148   if (IsReinterpret) {
3149     // For reinterpret casts, sema ensures that src and dst are both functions
3150     // or data and have the same size, which means the LLVM types should match.
3151     assert(Src->getType() == DstNull->getType());
3152     return Builder.CreateSelect(IsNotNull, Src, DstNull);
3153   }
3154 
3155   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
3156   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
3157   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
3158   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
3159   CGF.EmitBlock(ConvertBB);
3160 
3161   llvm::Value *Dst = EmitNonNullMemberPointerConversion(
3162       SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
3163       Builder);
3164 
3165   Builder.CreateBr(ContinueBB);
3166 
3167   // In the continuation, choose between DstNull and Dst.
3168   CGF.EmitBlock(ContinueBB);
3169   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
3170   Phi->addIncoming(DstNull, OriginalBB);
3171   Phi->addIncoming(Dst, ConvertBB);
3172   return Phi;
3173 }
3174 
3175 llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
3176     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3177     CastExpr::path_const_iterator PathBegin,
3178     CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
3179     CGBuilderTy &Builder) {
3180   const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
3181   const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
3182   MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
3183   MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
3184   bool IsFunc = SrcTy->isMemberFunctionPointer();
3185   bool IsConstant = isa<llvm::Constant>(Src);
3186 
3187   // Decompose src.
3188   llvm::Value *FirstField = Src;
3189   llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
3190   llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
3191   llvm::Value *VBPtrOffset = getZeroInt();
3192   if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
3193     // We need to extract values.
3194     unsigned I = 0;
3195     FirstField = Builder.CreateExtractValue(Src, I++);
3196     if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
3197       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
3198     if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
3199       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
3200     if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
3201       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
3202   }
3203 
3204   bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
3205   const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
3206   const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
3207 
3208   // For data pointers, we adjust the field offset directly.  For functions, we
3209   // have a separate field.
3210   llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
3211 
3212   // The virtual inheritance model has a quirk: the virtual base table is always
3213   // referenced when dereferencing a member pointer even if the member pointer
3214   // is non-virtual.  This is accounted for by adjusting the non-virtual offset
3215   // to point backwards to the top of the MDC from the first VBase.  Undo this
3216   // adjustment to normalize the member pointer.
3217   llvm::Value *SrcVBIndexEqZero =
3218       Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3219   if (SrcInheritance == MSInheritanceModel::Virtual) {
3220     if (int64_t SrcOffsetToFirstVBase =
3221             getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
3222       llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
3223           SrcVBIndexEqZero,
3224           llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
3225           getZeroInt());
3226       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
3227     }
3228   }
3229 
3230   // A non-zero vbindex implies that we are dealing with a source member in a
3231   // floating virtual base in addition to some non-virtual offset.  If the
3232   // vbindex is zero, we are dealing with a source that exists in a non-virtual,
3233   // fixed, base.  The difference between these two cases is that the vbindex +
3234   // nvoffset *always* point to the member regardless of what context they are
3235   // evaluated in so long as the vbindex is adjusted.  A member inside a fixed
3236   // base requires explicit nv adjustment.
3237   llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
3238       CGM.IntTy,
3239       CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
3240           .getQuantity());
3241 
3242   llvm::Value *NVDisp;
3243   if (IsDerivedToBase)
3244     NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
3245   else
3246     NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
3247 
3248   NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
3249 
3250   // Update the vbindex to an appropriate value in the destination because
3251   // SrcRD's vbtable might not be a strict prefix of the one in DstRD.
3252   llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
3253   if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
3254       inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
3255     if (llvm::GlobalVariable *VDispMap =
3256             getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
3257       llvm::Value *VBIndex = Builder.CreateExactUDiv(
3258           VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
3259       if (IsConstant) {
3260         llvm::Constant *Mapping = VDispMap->getInitializer();
3261         VirtualBaseAdjustmentOffset =
3262             Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
3263       } else {
3264         llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
3265         VirtualBaseAdjustmentOffset =
3266             Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(VDispMap, Idxs),
3267                                       CharUnits::fromQuantity(4));
3268       }
3269 
3270       DstVBIndexEqZero =
3271           Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
3272     }
3273   }
3274 
3275   // Set the VBPtrOffset to zero if the vbindex is zero.  Otherwise, initialize
3276   // it to the offset of the vbptr.
3277   if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
3278     llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
3279         CGM.IntTy,
3280         getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
3281     VBPtrOffset =
3282         Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
3283   }
3284 
3285   // Likewise, apply a similar adjustment so that dereferencing the member
3286   // pointer correctly accounts for the distance between the start of the first
3287   // virtual base and the top of the MDC.
3288   if (DstInheritance == MSInheritanceModel::Virtual) {
3289     if (int64_t DstOffsetToFirstVBase =
3290             getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
3291       llvm::Value *DoDstAdjustment = Builder.CreateSelect(
3292           DstVBIndexEqZero,
3293           llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
3294           getZeroInt());
3295       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
3296     }
3297   }
3298 
3299   // Recompose dst from the null struct and the adjusted fields from src.
3300   llvm::Value *Dst;
3301   if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
3302     Dst = FirstField;
3303   } else {
3304     Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
3305     unsigned Idx = 0;
3306     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
3307     if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
3308       Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
3309     if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
3310       Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
3311     if (inheritanceModelHasVBTableOffsetField(DstInheritance))
3312       Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
3313   }
3314   return Dst;
3315 }
3316 
3317 llvm::Constant *
3318 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
3319                                              llvm::Constant *Src) {
3320   const MemberPointerType *SrcTy =
3321       E->getSubExpr()->getType()->castAs<MemberPointerType>();
3322   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
3323 
3324   CastKind CK = E->getCastKind();
3325 
3326   return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
3327                                      E->path_end(), Src);
3328 }
3329 
3330 llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
3331     const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
3332     CastExpr::path_const_iterator PathBegin,
3333     CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
3334   assert(CK == CK_DerivedToBaseMemberPointer ||
3335          CK == CK_BaseToDerivedMemberPointer ||
3336          CK == CK_ReinterpretMemberPointer);
3337   // If src is null, emit a new null for dst.  We can't return src because dst
3338   // might have a new representation.
3339   if (MemberPointerConstantIsNull(SrcTy, Src))
3340     return EmitNullMemberPointer(DstTy);
3341 
3342   // We don't need to do anything for reinterpret_casts of non-null member
3343   // pointers.  We should only get here when the two type representations have
3344   // the same size.
3345   if (CK == CK_ReinterpretMemberPointer)
3346     return Src;
3347 
3348   CGBuilderTy Builder(CGM, CGM.getLLVMContext());
3349   auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
3350       SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
3351 
3352   return Dst;
3353 }
3354 
3355 CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
3356     CodeGenFunction &CGF, const Expr *E, Address This,
3357     llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
3358     const MemberPointerType *MPT) {
3359   assert(MPT->isMemberFunctionPointer());
3360   const FunctionProtoType *FPT =
3361     MPT->getPointeeType()->castAs<FunctionProtoType>();
3362   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
3363   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
3364       CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
3365   CGBuilderTy &Builder = CGF.Builder;
3366 
3367   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
3368 
3369   // Extract the fields we need, regardless of model.  We'll apply them if we
3370   // have them.
3371   llvm::Value *FunctionPointer = MemPtr;
3372   llvm::Value *NonVirtualBaseAdjustment = nullptr;
3373   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
3374   llvm::Value *VBPtrOffset = nullptr;
3375   if (MemPtr->getType()->isStructTy()) {
3376     // We need to extract values.
3377     unsigned I = 0;
3378     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
3379     if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
3380       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
3381     if (inheritanceModelHasVBPtrOffsetField(Inheritance))
3382       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
3383     if (inheritanceModelHasVBTableOffsetField(Inheritance))
3384       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
3385   }
3386 
3387   if (VirtualBaseAdjustmentOffset) {
3388     ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
3389                                    VirtualBaseAdjustmentOffset, VBPtrOffset);
3390   } else {
3391     ThisPtrForCall = This.getPointer();
3392   }
3393 
3394   if (NonVirtualBaseAdjustment) {
3395     // Apply the adjustment and cast back to the original struct type.
3396     llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
3397     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
3398     ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
3399                                            "this.adjusted");
3400   }
3401 
3402   FunctionPointer =
3403     Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
3404   CGCallee Callee(FPT, FunctionPointer);
3405   return Callee;
3406 }
3407 
3408 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
3409   return new MicrosoftCXXABI(CGM);
3410 }
3411 
3412 // MS RTTI Overview:
3413 // The run time type information emitted by cl.exe contains 5 distinct types of
3414 // structures.  Many of them reference each other.
3415 //
3416 // TypeInfo:  Static classes that are returned by typeid.
3417 //
3418 // CompleteObjectLocator:  Referenced by vftables.  They contain information
3419 //   required for dynamic casting, including OffsetFromTop.  They also contain
3420 //   a reference to the TypeInfo for the type and a reference to the
3421 //   CompleteHierarchyDescriptor for the type.
3422 //
3423 // ClassHierarchyDescriptor: Contains information about a class hierarchy.
3424 //   Used during dynamic_cast to walk a class hierarchy.  References a base
3425 //   class array and the size of said array.
3426 //
3427 // BaseClassArray: Contains a list of classes in a hierarchy.  BaseClassArray is
3428 //   somewhat of a misnomer because the most derived class is also in the list
3429 //   as well as multiple copies of virtual bases (if they occur multiple times
3430 //   in the hierarchy.)  The BaseClassArray contains one BaseClassDescriptor for
3431 //   every path in the hierarchy, in pre-order depth first order.  Note, we do
3432 //   not declare a specific llvm type for BaseClassArray, it's merely an array
3433 //   of BaseClassDescriptor pointers.
3434 //
3435 // BaseClassDescriptor: Contains information about a class in a class hierarchy.
3436 //   BaseClassDescriptor is also somewhat of a misnomer for the same reason that
3437 //   BaseClassArray is.  It contains information about a class within a
3438 //   hierarchy such as: is this base is ambiguous and what is its offset in the
3439 //   vbtable.  The names of the BaseClassDescriptors have all of their fields
3440 //   mangled into them so they can be aggressively deduplicated by the linker.
3441 
3442 static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
3443   StringRef MangledName("??_7type_info@@6B@");
3444   if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
3445     return VTable;
3446   return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
3447                                   /*isConstant=*/true,
3448                                   llvm::GlobalVariable::ExternalLinkage,
3449                                   /*Initializer=*/nullptr, MangledName);
3450 }
3451 
3452 namespace {
3453 
3454 /// A Helper struct that stores information about a class in a class
3455 /// hierarchy.  The information stored in these structs struct is used during
3456 /// the generation of ClassHierarchyDescriptors and BaseClassDescriptors.
3457 // During RTTI creation, MSRTTIClasses are stored in a contiguous array with
3458 // implicit depth first pre-order tree connectivity.  getFirstChild and
3459 // getNextSibling allow us to walk the tree efficiently.
3460 struct MSRTTIClass {
3461   enum {
3462     IsPrivateOnPath = 1 | 8,
3463     IsAmbiguous = 2,
3464     IsPrivate = 4,
3465     IsVirtual = 16,
3466     HasHierarchyDescriptor = 64
3467   };
3468   MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
3469   uint32_t initialize(const MSRTTIClass *Parent,
3470                       const CXXBaseSpecifier *Specifier);
3471 
3472   MSRTTIClass *getFirstChild() { return this + 1; }
3473   static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
3474     return Child + 1 + Child->NumBases;
3475   }
3476 
3477   const CXXRecordDecl *RD, *VirtualRoot;
3478   uint32_t Flags, NumBases, OffsetInVBase;
3479 };
3480 
3481 /// Recursively initialize the base class array.
3482 uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
3483                                  const CXXBaseSpecifier *Specifier) {
3484   Flags = HasHierarchyDescriptor;
3485   if (!Parent) {
3486     VirtualRoot = nullptr;
3487     OffsetInVBase = 0;
3488   } else {
3489     if (Specifier->getAccessSpecifier() != AS_public)
3490       Flags |= IsPrivate | IsPrivateOnPath;
3491     if (Specifier->isVirtual()) {
3492       Flags |= IsVirtual;
3493       VirtualRoot = RD;
3494       OffsetInVBase = 0;
3495     } else {
3496       if (Parent->Flags & IsPrivateOnPath)
3497         Flags |= IsPrivateOnPath;
3498       VirtualRoot = Parent->VirtualRoot;
3499       OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
3500           .getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
3501     }
3502   }
3503   NumBases = 0;
3504   MSRTTIClass *Child = getFirstChild();
3505   for (const CXXBaseSpecifier &Base : RD->bases()) {
3506     NumBases += Child->initialize(this, &Base) + 1;
3507     Child = getNextChild(Child);
3508   }
3509   return NumBases;
3510 }
3511 
3512 static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
3513   switch (Ty->getLinkage()) {
3514   case NoLinkage:
3515   case InternalLinkage:
3516   case UniqueExternalLinkage:
3517     return llvm::GlobalValue::InternalLinkage;
3518 
3519   case VisibleNoLinkage:
3520   case ModuleInternalLinkage:
3521   case ModuleLinkage:
3522   case ExternalLinkage:
3523     return llvm::GlobalValue::LinkOnceODRLinkage;
3524   }
3525   llvm_unreachable("Invalid linkage!");
3526 }
3527 
3528 /// An ephemeral helper class for building MS RTTI types.  It caches some
3529 /// calls to the module and information about the most derived class in a
3530 /// hierarchy.
3531 struct MSRTTIBuilder {
3532   enum {
3533     HasBranchingHierarchy = 1,
3534     HasVirtualBranchingHierarchy = 2,
3535     HasAmbiguousBases = 4
3536   };
3537 
3538   MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
3539       : CGM(ABI.CGM), Context(CGM.getContext()),
3540         VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
3541         Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
3542         ABI(ABI) {}
3543 
3544   llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
3545   llvm::GlobalVariable *
3546   getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
3547   llvm::GlobalVariable *getClassHierarchyDescriptor();
3548   llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
3549 
3550   CodeGenModule &CGM;
3551   ASTContext &Context;
3552   llvm::LLVMContext &VMContext;
3553   llvm::Module &Module;
3554   const CXXRecordDecl *RD;
3555   llvm::GlobalVariable::LinkageTypes Linkage;
3556   MicrosoftCXXABI &ABI;
3557 };
3558 
3559 } // namespace
3560 
3561 /// Recursively serializes a class hierarchy in pre-order depth first
3562 /// order.
3563 static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
3564                                     const CXXRecordDecl *RD) {
3565   Classes.push_back(MSRTTIClass(RD));
3566   for (const CXXBaseSpecifier &Base : RD->bases())
3567     serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
3568 }
3569 
3570 /// Find ambiguity among base classes.
3571 static void
3572 detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
3573   llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
3574   llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
3575   llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
3576   for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
3577     if ((Class->Flags & MSRTTIClass::IsVirtual) &&
3578         !VirtualBases.insert(Class->RD).second) {
3579       Class = MSRTTIClass::getNextChild(Class);
3580       continue;
3581     }
3582     if (!UniqueBases.insert(Class->RD).second)
3583       AmbiguousBases.insert(Class->RD);
3584     Class++;
3585   }
3586   if (AmbiguousBases.empty())
3587     return;
3588   for (MSRTTIClass &Class : Classes)
3589     if (AmbiguousBases.count(Class.RD))
3590       Class.Flags |= MSRTTIClass::IsAmbiguous;
3591 }
3592 
3593 llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
3594   SmallString<256> MangledName;
3595   {
3596     llvm::raw_svector_ostream Out(MangledName);
3597     ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
3598   }
3599 
3600   // Check to see if we've already declared this ClassHierarchyDescriptor.
3601   if (auto CHD = Module.getNamedGlobal(MangledName))
3602     return CHD;
3603 
3604   // Serialize the class hierarchy and initialize the CHD Fields.
3605   SmallVector<MSRTTIClass, 8> Classes;
3606   serializeClassHierarchy(Classes, RD);
3607   Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
3608   detectAmbiguousBases(Classes);
3609   int Flags = 0;
3610   for (auto Class : Classes) {
3611     if (Class.RD->getNumBases() > 1)
3612       Flags |= HasBranchingHierarchy;
3613     // Note: cl.exe does not calculate "HasAmbiguousBases" correctly.  We
3614     // believe the field isn't actually used.
3615     if (Class.Flags & MSRTTIClass::IsAmbiguous)
3616       Flags |= HasAmbiguousBases;
3617   }
3618   if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
3619     Flags |= HasVirtualBranchingHierarchy;
3620   // These gep indices are used to get the address of the first element of the
3621   // base class array.
3622   llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
3623                                llvm::ConstantInt::get(CGM.IntTy, 0)};
3624 
3625   // Forward-declare the class hierarchy descriptor
3626   auto Type = ABI.getClassHierarchyDescriptorType();
3627   auto CHD = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3628                                       /*Initializer=*/nullptr,
3629                                       MangledName);
3630   if (CHD->isWeakForLinker())
3631     CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
3632 
3633   auto *Bases = getBaseClassArray(Classes);
3634 
3635   // Initialize the base class ClassHierarchyDescriptor.
3636   llvm::Constant *Fields[] = {
3637       llvm::ConstantInt::get(CGM.IntTy, 0), // reserved by the runtime
3638       llvm::ConstantInt::get(CGM.IntTy, Flags),
3639       llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
3640       ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
3641           Bases->getValueType(), Bases,
3642           llvm::ArrayRef<llvm::Value *>(GEPIndices))),
3643   };
3644   CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3645   return CHD;
3646 }
3647 
3648 llvm::GlobalVariable *
3649 MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
3650   SmallString<256> MangledName;
3651   {
3652     llvm::raw_svector_ostream Out(MangledName);
3653     ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
3654   }
3655 
3656   // Forward-declare the base class array.
3657   // cl.exe pads the base class array with 1 (in 32 bit mode) or 4 (in 64 bit
3658   // mode) bytes of padding.  We provide a pointer sized amount of padding by
3659   // adding +1 to Classes.size().  The sections have pointer alignment and are
3660   // marked pick-any so it shouldn't matter.
3661   llvm::Type *PtrType = ABI.getImageRelativeType(
3662       ABI.getBaseClassDescriptorType()->getPointerTo());
3663   auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
3664   auto *BCA =
3665       new llvm::GlobalVariable(Module, ArrType,
3666                                /*isConstant=*/true, Linkage,
3667                                /*Initializer=*/nullptr, MangledName);
3668   if (BCA->isWeakForLinker())
3669     BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
3670 
3671   // Initialize the BaseClassArray.
3672   SmallVector<llvm::Constant *, 8> BaseClassArrayData;
3673   for (MSRTTIClass &Class : Classes)
3674     BaseClassArrayData.push_back(
3675         ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
3676   BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
3677   BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
3678   return BCA;
3679 }
3680 
3681 llvm::GlobalVariable *
3682 MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
3683   // Compute the fields for the BaseClassDescriptor.  They are computed up front
3684   // because they are mangled into the name of the object.
3685   uint32_t OffsetInVBTable = 0;
3686   int32_t VBPtrOffset = -1;
3687   if (Class.VirtualRoot) {
3688     auto &VTableContext = CGM.getMicrosoftVTableContext();
3689     OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
3690     VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
3691   }
3692 
3693   SmallString<256> MangledName;
3694   {
3695     llvm::raw_svector_ostream Out(MangledName);
3696     ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
3697         Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
3698         Class.Flags, Out);
3699   }
3700 
3701   // Check to see if we've already declared this object.
3702   if (auto BCD = Module.getNamedGlobal(MangledName))
3703     return BCD;
3704 
3705   // Forward-declare the base class descriptor.
3706   auto Type = ABI.getBaseClassDescriptorType();
3707   auto BCD =
3708       new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3709                                /*Initializer=*/nullptr, MangledName);
3710   if (BCD->isWeakForLinker())
3711     BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
3712 
3713   // Initialize the BaseClassDescriptor.
3714   llvm::Constant *Fields[] = {
3715       ABI.getImageRelativeConstant(
3716           ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
3717       llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
3718       llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
3719       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
3720       llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
3721       llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
3722       ABI.getImageRelativeConstant(
3723           MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
3724   };
3725   BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
3726   return BCD;
3727 }
3728 
3729 llvm::GlobalVariable *
3730 MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
3731   SmallString<256> MangledName;
3732   {
3733     llvm::raw_svector_ostream Out(MangledName);
3734     ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
3735   }
3736 
3737   // Check to see if we've already computed this complete object locator.
3738   if (auto COL = Module.getNamedGlobal(MangledName))
3739     return COL;
3740 
3741   // Compute the fields of the complete object locator.
3742   int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
3743   int VFPtrOffset = 0;
3744   // The offset includes the vtordisp if one exists.
3745   if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
3746     if (Context.getASTRecordLayout(RD)
3747       .getVBaseOffsetsMap()
3748       .find(VBase)
3749       ->second.hasVtorDisp())
3750       VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
3751 
3752   // Forward-declare the complete object locator.
3753   llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
3754   auto COL = new llvm::GlobalVariable(Module, Type, /*isConstant=*/true, Linkage,
3755     /*Initializer=*/nullptr, MangledName);
3756 
3757   // Initialize the CompleteObjectLocator.
3758   llvm::Constant *Fields[] = {
3759       llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
3760       llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
3761       llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
3762       ABI.getImageRelativeConstant(
3763           CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
3764       ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
3765       ABI.getImageRelativeConstant(COL),
3766   };
3767   llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
3768   if (!ABI.isImageRelative())
3769     FieldsRef = FieldsRef.drop_back();
3770   COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
3771   if (COL->isWeakForLinker())
3772     COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
3773   return COL;
3774 }
3775 
3776 static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
3777                                    bool &IsConst, bool &IsVolatile,
3778                                    bool &IsUnaligned) {
3779   T = Context.getExceptionObjectType(T);
3780 
3781   // C++14 [except.handle]p3:
3782   //   A handler is a match for an exception object of type E if [...]
3783   //     - the handler is of type cv T or const T& where T is a pointer type and
3784   //       E is a pointer type that can be converted to T by [...]
3785   //         - a qualification conversion
3786   IsConst = false;
3787   IsVolatile = false;
3788   IsUnaligned = false;
3789   QualType PointeeType = T->getPointeeType();
3790   if (!PointeeType.isNull()) {
3791     IsConst = PointeeType.isConstQualified();
3792     IsVolatile = PointeeType.isVolatileQualified();
3793     IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
3794   }
3795 
3796   // Member pointer types like "const int A::*" are represented by having RTTI
3797   // for "int A::*" and separately storing the const qualifier.
3798   if (const auto *MPTy = T->getAs<MemberPointerType>())
3799     T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
3800                                      MPTy->getClass());
3801 
3802   // Pointer types like "const int * const *" are represented by having RTTI
3803   // for "const int **" and separately storing the const qualifier.
3804   if (T->isPointerType())
3805     T = Context.getPointerType(PointeeType.getUnqualifiedType());
3806 
3807   return T;
3808 }
3809 
3810 CatchTypeInfo
3811 MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
3812                                               QualType CatchHandlerType) {
3813   // TypeDescriptors for exceptions never have qualified pointer types,
3814   // qualifiers are stored separately in order to support qualification
3815   // conversions.
3816   bool IsConst, IsVolatile, IsUnaligned;
3817   Type =
3818       decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
3819 
3820   bool IsReference = CatchHandlerType->isReferenceType();
3821 
3822   uint32_t Flags = 0;
3823   if (IsConst)
3824     Flags |= 1;
3825   if (IsVolatile)
3826     Flags |= 2;
3827   if (IsUnaligned)
3828     Flags |= 4;
3829   if (IsReference)
3830     Flags |= 8;
3831 
3832   return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
3833                        Flags};
3834 }
3835 
3836 /// Gets a TypeDescriptor.  Returns a llvm::Constant * rather than a
3837 /// llvm::GlobalVariable * because different type descriptors have different
3838 /// types, and need to be abstracted.  They are abstracting by casting the
3839 /// address to an Int8PtrTy.
3840 llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
3841   SmallString<256> MangledName;
3842   {
3843     llvm::raw_svector_ostream Out(MangledName);
3844     getMangleContext().mangleCXXRTTI(Type, Out);
3845   }
3846 
3847   // Check to see if we've already declared this TypeDescriptor.
3848   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
3849     return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
3850 
3851   // Note for the future: If we would ever like to do deferred emission of
3852   // RTTI, check if emitting vtables opportunistically need any adjustment.
3853 
3854   // Compute the fields for the TypeDescriptor.
3855   SmallString<256> TypeInfoString;
3856   {
3857     llvm::raw_svector_ostream Out(TypeInfoString);
3858     getMangleContext().mangleCXXRTTIName(Type, Out);
3859   }
3860 
3861   // Declare and initialize the TypeDescriptor.
3862   llvm::Constant *Fields[] = {
3863     getTypeInfoVTable(CGM),                        // VFPtr
3864     llvm::ConstantPointerNull::get(CGM.Int8PtrTy), // Runtime data
3865     llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
3866   llvm::StructType *TypeDescriptorType =
3867       getTypeDescriptorType(TypeInfoString);
3868   auto *Var = new llvm::GlobalVariable(
3869       CGM.getModule(), TypeDescriptorType, /*isConstant=*/false,
3870       getLinkageForRTTI(Type),
3871       llvm::ConstantStruct::get(TypeDescriptorType, Fields),
3872       MangledName);
3873   if (Var->isWeakForLinker())
3874     Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
3875   return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
3876 }
3877 
3878 /// Gets or a creates a Microsoft CompleteObjectLocator.
3879 llvm::GlobalVariable *
3880 MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
3881                                             const VPtrInfo &Info) {
3882   return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
3883 }
3884 
3885 void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
3886   if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
3887     // There are no constructor variants, always emit the complete destructor.
3888     llvm::Function *Fn =
3889         CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
3890     CGM.maybeSetTrivialComdat(*ctor, *Fn);
3891     return;
3892   }
3893 
3894   auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
3895 
3896   // Emit the base destructor if the base and complete (vbase) destructors are
3897   // equivalent. This effectively implements -mconstructor-aliases as part of
3898   // the ABI.
3899   if (GD.getDtorType() == Dtor_Complete &&
3900       dtor->getParent()->getNumVBases() == 0)
3901     GD = GD.getWithDtorType(Dtor_Base);
3902 
3903   // The base destructor is equivalent to the base destructor of its
3904   // base class if there is exactly one non-virtual base class with a
3905   // non-trivial destructor, there are no fields with a non-trivial
3906   // destructor, and the body of the destructor is trivial.
3907   if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
3908     return;
3909 
3910   llvm::Function *Fn = CGM.codegenCXXStructor(GD);
3911   if (Fn->isWeakForLinker())
3912     Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
3913 }
3914 
3915 llvm::Function *
3916 MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
3917                                          CXXCtorType CT) {
3918   assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
3919 
3920   // Calculate the mangled name.
3921   SmallString<256> ThunkName;
3922   llvm::raw_svector_ostream Out(ThunkName);
3923   getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
3924 
3925   // If the thunk has been generated previously, just return it.
3926   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
3927     return cast<llvm::Function>(GV);
3928 
3929   // Create the llvm::Function.
3930   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
3931   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
3932   const CXXRecordDecl *RD = CD->getParent();
3933   QualType RecordTy = getContext().getRecordType(RD);
3934   llvm::Function *ThunkFn = llvm::Function::Create(
3935       ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
3936   ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
3937       FnInfo.getEffectiveCallingConvention()));
3938   if (ThunkFn->isWeakForLinker())
3939     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
3940   bool IsCopy = CT == Ctor_CopyingClosure;
3941 
3942   // Start codegen.
3943   CodeGenFunction CGF(CGM);
3944   CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
3945 
3946   // Build FunctionArgs.
3947   FunctionArgList FunctionArgs;
3948 
3949   // A constructor always starts with a 'this' pointer as its first argument.
3950   buildThisParam(CGF, FunctionArgs);
3951 
3952   // Following the 'this' pointer is a reference to the source object that we
3953   // are copying from.
3954   ImplicitParamDecl SrcParam(
3955       getContext(), /*DC=*/nullptr, SourceLocation(),
3956       &getContext().Idents.get("src"),
3957       getContext().getLValueReferenceType(RecordTy,
3958                                           /*SpelledAsLValue=*/true),
3959       ImplicitParamDecl::Other);
3960   if (IsCopy)
3961     FunctionArgs.push_back(&SrcParam);
3962 
3963   // Constructors for classes which utilize virtual bases have an additional
3964   // parameter which indicates whether or not it is being delegated to by a more
3965   // derived constructor.
3966   ImplicitParamDecl IsMostDerived(getContext(), /*DC=*/nullptr,
3967                                   SourceLocation(),
3968                                   &getContext().Idents.get("is_most_derived"),
3969                                   getContext().IntTy, ImplicitParamDecl::Other);
3970   // Only add the parameter to the list if the class has virtual bases.
3971   if (RD->getNumVBases() > 0)
3972     FunctionArgs.push_back(&IsMostDerived);
3973 
3974   // Start defining the function.
3975   auto NL = ApplyDebugLocation::CreateEmpty(CGF);
3976   CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
3977                     FunctionArgs, CD->getLocation(), SourceLocation());
3978   // Create a scope with an artificial location for the body of this function.
3979   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
3980   setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
3981   llvm::Value *This = getThisValue(CGF);
3982 
3983   llvm::Value *SrcVal =
3984       IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
3985              : nullptr;
3986 
3987   CallArgList Args;
3988 
3989   // Push the this ptr.
3990   Args.add(RValue::get(This), CD->getThisType());
3991 
3992   // Push the src ptr.
3993   if (SrcVal)
3994     Args.add(RValue::get(SrcVal), SrcParam.getType());
3995 
3996   // Add the rest of the default arguments.
3997   SmallVector<const Stmt *, 4> ArgVec;
3998   ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
3999   for (const ParmVarDecl *PD : params) {
4000     assert(PD->hasDefaultArg() && "ctor closure lacks default args");
4001     ArgVec.push_back(PD->getDefaultArg());
4002   }
4003 
4004   CodeGenFunction::RunCleanupsScope Cleanups(CGF);
4005 
4006   const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
4007   CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
4008 
4009   // Insert any ABI-specific implicit constructor arguments.
4010   AddedStructorArgCounts ExtraArgs =
4011       addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
4012                                  /*ForVirtualBase=*/false,
4013                                  /*Delegating=*/false, Args);
4014   // Call the destructor with our arguments.
4015   llvm::Constant *CalleePtr =
4016       CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4017   CGCallee Callee =
4018       CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
4019   const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
4020       Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
4021   CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
4022 
4023   Cleanups.ForceCleanup();
4024 
4025   // Emit the ret instruction, remove any temporary instructions created for the
4026   // aid of CodeGen.
4027   CGF.FinishFunction(SourceLocation());
4028 
4029   return ThunkFn;
4030 }
4031 
4032 llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
4033                                                   uint32_t NVOffset,
4034                                                   int32_t VBPtrOffset,
4035                                                   uint32_t VBIndex) {
4036   assert(!T->isReferenceType());
4037 
4038   CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4039   const CXXConstructorDecl *CD =
4040       RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
4041   CXXCtorType CT = Ctor_Complete;
4042   if (CD)
4043     if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
4044       CT = Ctor_CopyingClosure;
4045 
4046   uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
4047   SmallString<256> MangledName;
4048   {
4049     llvm::raw_svector_ostream Out(MangledName);
4050     getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
4051                                               VBPtrOffset, VBIndex, Out);
4052   }
4053   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4054     return getImageRelativeConstant(GV);
4055 
4056   // The TypeDescriptor is used by the runtime to determine if a catch handler
4057   // is appropriate for the exception object.
4058   llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
4059 
4060   // The runtime is responsible for calling the copy constructor if the
4061   // exception is caught by value.
4062   llvm::Constant *CopyCtor;
4063   if (CD) {
4064     if (CT == Ctor_CopyingClosure)
4065       CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
4066     else
4067       CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
4068 
4069     CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
4070   } else {
4071     CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4072   }
4073   CopyCtor = getImageRelativeConstant(CopyCtor);
4074 
4075   bool IsScalar = !RD;
4076   bool HasVirtualBases = false;
4077   bool IsStdBadAlloc = false; // std::bad_alloc is special for some reason.
4078   QualType PointeeType = T;
4079   if (T->isPointerType())
4080     PointeeType = T->getPointeeType();
4081   if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
4082     HasVirtualBases = RD->getNumVBases() > 0;
4083     if (IdentifierInfo *II = RD->getIdentifier())
4084       IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
4085   }
4086 
4087   // Encode the relevant CatchableType properties into the Flags bitfield.
4088   // FIXME: Figure out how bits 2 or 8 can get set.
4089   uint32_t Flags = 0;
4090   if (IsScalar)
4091     Flags |= 1;
4092   if (HasVirtualBases)
4093     Flags |= 4;
4094   if (IsStdBadAlloc)
4095     Flags |= 16;
4096 
4097   llvm::Constant *Fields[] = {
4098       llvm::ConstantInt::get(CGM.IntTy, Flags),       // Flags
4099       TD,                                             // TypeDescriptor
4100       llvm::ConstantInt::get(CGM.IntTy, NVOffset),    // NonVirtualAdjustment
4101       llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), // OffsetToVBPtr
4102       llvm::ConstantInt::get(CGM.IntTy, VBIndex),     // VBTableIndex
4103       llvm::ConstantInt::get(CGM.IntTy, Size),        // Size
4104       CopyCtor                                        // CopyCtor
4105   };
4106   llvm::StructType *CTType = getCatchableTypeType();
4107   auto *GV = new llvm::GlobalVariable(
4108       CGM.getModule(), CTType, /*isConstant=*/true, getLinkageForRTTI(T),
4109       llvm::ConstantStruct::get(CTType, Fields), MangledName);
4110   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4111   GV->setSection(".xdata");
4112   if (GV->isWeakForLinker())
4113     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4114   return getImageRelativeConstant(GV);
4115 }
4116 
4117 llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
4118   assert(!T->isReferenceType());
4119 
4120   // See if we've already generated a CatchableTypeArray for this type before.
4121   llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
4122   if (CTA)
4123     return CTA;
4124 
4125   // Ensure that we don't have duplicate entries in our CatchableTypeArray by
4126   // using a SmallSetVector.  Duplicates may arise due to virtual bases
4127   // occurring more than once in the hierarchy.
4128   llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
4129 
4130   // C++14 [except.handle]p3:
4131   //   A handler is a match for an exception object of type E if [...]
4132   //     - the handler is of type cv T or cv T& and T is an unambiguous public
4133   //       base class of E, or
4134   //     - the handler is of type cv T or const T& where T is a pointer type and
4135   //       E is a pointer type that can be converted to T by [...]
4136   //         - a standard pointer conversion (4.10) not involving conversions to
4137   //           pointers to private or protected or ambiguous classes
4138   const CXXRecordDecl *MostDerivedClass = nullptr;
4139   bool IsPointer = T->isPointerType();
4140   if (IsPointer)
4141     MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
4142   else
4143     MostDerivedClass = T->getAsCXXRecordDecl();
4144 
4145   // Collect all the unambiguous public bases of the MostDerivedClass.
4146   if (MostDerivedClass) {
4147     const ASTContext &Context = getContext();
4148     const ASTRecordLayout &MostDerivedLayout =
4149         Context.getASTRecordLayout(MostDerivedClass);
4150     MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
4151     SmallVector<MSRTTIClass, 8> Classes;
4152     serializeClassHierarchy(Classes, MostDerivedClass);
4153     Classes.front().initialize(/*Parent=*/nullptr, /*Specifier=*/nullptr);
4154     detectAmbiguousBases(Classes);
4155     for (const MSRTTIClass &Class : Classes) {
4156       // Skip any ambiguous or private bases.
4157       if (Class.Flags &
4158           (MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
4159         continue;
4160       // Write down how to convert from a derived pointer to a base pointer.
4161       uint32_t OffsetInVBTable = 0;
4162       int32_t VBPtrOffset = -1;
4163       if (Class.VirtualRoot) {
4164         OffsetInVBTable =
4165           VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
4166         VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
4167       }
4168 
4169       // Turn our record back into a pointer if the exception object is a
4170       // pointer.
4171       QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
4172       if (IsPointer)
4173         RTTITy = Context.getPointerType(RTTITy);
4174       CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
4175                                              VBPtrOffset, OffsetInVBTable));
4176     }
4177   }
4178 
4179   // C++14 [except.handle]p3:
4180   //   A handler is a match for an exception object of type E if
4181   //     - The handler is of type cv T or cv T& and E and T are the same type
4182   //       (ignoring the top-level cv-qualifiers)
4183   CatchableTypes.insert(getCatchableType(T));
4184 
4185   // C++14 [except.handle]p3:
4186   //   A handler is a match for an exception object of type E if
4187   //     - the handler is of type cv T or const T& where T is a pointer type and
4188   //       E is a pointer type that can be converted to T by [...]
4189   //         - a standard pointer conversion (4.10) not involving conversions to
4190   //           pointers to private or protected or ambiguous classes
4191   //
4192   // C++14 [conv.ptr]p2:
4193   //   A prvalue of type "pointer to cv T," where T is an object type, can be
4194   //   converted to a prvalue of type "pointer to cv void".
4195   if (IsPointer && T->getPointeeType()->isObjectType())
4196     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4197 
4198   // C++14 [except.handle]p3:
4199   //   A handler is a match for an exception object of type E if [...]
4200   //     - the handler is of type cv T or const T& where T is a pointer or
4201   //       pointer to member type and E is std::nullptr_t.
4202   //
4203   // We cannot possibly list all possible pointer types here, making this
4204   // implementation incompatible with the standard.  However, MSVC includes an
4205   // entry for pointer-to-void in this case.  Let's do the same.
4206   if (T->isNullPtrType())
4207     CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
4208 
4209   uint32_t NumEntries = CatchableTypes.size();
4210   llvm::Type *CTType =
4211       getImageRelativeType(getCatchableTypeType()->getPointerTo());
4212   llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
4213   llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
4214   llvm::Constant *Fields[] = {
4215       llvm::ConstantInt::get(CGM.IntTy, NumEntries),    // NumEntries
4216       llvm::ConstantArray::get(
4217           AT, llvm::makeArrayRef(CatchableTypes.begin(),
4218                                  CatchableTypes.end())) // CatchableTypes
4219   };
4220   SmallString<256> MangledName;
4221   {
4222     llvm::raw_svector_ostream Out(MangledName);
4223     getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
4224   }
4225   CTA = new llvm::GlobalVariable(
4226       CGM.getModule(), CTAType, /*isConstant=*/true, getLinkageForRTTI(T),
4227       llvm::ConstantStruct::get(CTAType, Fields), MangledName);
4228   CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4229   CTA->setSection(".xdata");
4230   if (CTA->isWeakForLinker())
4231     CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
4232   return CTA;
4233 }
4234 
4235 llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
4236   bool IsConst, IsVolatile, IsUnaligned;
4237   T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
4238 
4239   // The CatchableTypeArray enumerates the various (CV-unqualified) types that
4240   // the exception object may be caught as.
4241   llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
4242   // The first field in a CatchableTypeArray is the number of CatchableTypes.
4243   // This is used as a component of the mangled name which means that we need to
4244   // know what it is in order to see if we have previously generated the
4245   // ThrowInfo.
4246   uint32_t NumEntries =
4247       cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
4248           ->getLimitedValue();
4249 
4250   SmallString<256> MangledName;
4251   {
4252     llvm::raw_svector_ostream Out(MangledName);
4253     getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
4254                                           NumEntries, Out);
4255   }
4256 
4257   // Reuse a previously generated ThrowInfo if we have generated an appropriate
4258   // one before.
4259   if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
4260     return GV;
4261 
4262   // The RTTI TypeDescriptor uses an unqualified type but catch clauses must
4263   // be at least as CV qualified.  Encode this requirement into the Flags
4264   // bitfield.
4265   uint32_t Flags = 0;
4266   if (IsConst)
4267     Flags |= 1;
4268   if (IsVolatile)
4269     Flags |= 2;
4270   if (IsUnaligned)
4271     Flags |= 4;
4272 
4273   // The cleanup-function (a destructor) must be called when the exception
4274   // object's lifetime ends.
4275   llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
4276   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4277     if (CXXDestructorDecl *DtorD = RD->getDestructor())
4278       if (!DtorD->isTrivial())
4279         CleanupFn = llvm::ConstantExpr::getBitCast(
4280             CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
4281             CGM.Int8PtrTy);
4282   // This is unused as far as we can tell, initialize it to null.
4283   llvm::Constant *ForwardCompat =
4284       getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
4285   llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
4286       llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
4287   llvm::StructType *TIType = getThrowInfoType();
4288   llvm::Constant *Fields[] = {
4289       llvm::ConstantInt::get(CGM.IntTy, Flags), // Flags
4290       getImageRelativeConstant(CleanupFn),      // CleanupFn
4291       ForwardCompat,                            // ForwardCompat
4292       PointerToCatchableTypes                   // CatchableTypeArray
4293   };
4294   auto *GV = new llvm::GlobalVariable(
4295       CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
4296       llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
4297   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4298   GV->setSection(".xdata");
4299   if (GV->isWeakForLinker())
4300     GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
4301   return GV;
4302 }
4303 
4304 void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
4305   const Expr *SubExpr = E->getSubExpr();
4306   QualType ThrowType = SubExpr->getType();
4307   // The exception object lives on the stack and it's address is passed to the
4308   // runtime function.
4309   Address AI = CGF.CreateMemTemp(ThrowType);
4310   CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
4311                        /*IsInit=*/true);
4312 
4313   // The so-called ThrowInfo is used to describe how the exception object may be
4314   // caught.
4315   llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
4316 
4317   // Call into the runtime to throw the exception.
4318   llvm::Value *Args[] = {
4319     CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
4320     TI
4321   };
4322   CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
4323 }
4324 
4325 std::pair<llvm::Value *, const CXXRecordDecl *>
4326 MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
4327                                const CXXRecordDecl *RD) {
4328   std::tie(This, std::ignore, RD) =
4329       performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
4330   return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
4331 }
4332