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