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