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