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