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