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