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