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