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