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