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 "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/VTableBuilder.h"
23 #include "llvm/ADT/StringSet.h"
24 
25 using namespace clang;
26 using namespace CodeGen;
27 
28 namespace {
29 
30 /// Holds all the vbtable globals for a given class.
31 struct VBTableGlobals {
32   const VPtrInfoVector *VBTables;
33   SmallVector<llvm::GlobalVariable *, 2> Globals;
34 };
35 
36 class MicrosoftCXXABI : public CGCXXABI {
37 public:
38   MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
39 
40   bool HasThisReturn(GlobalDecl GD) const override;
41 
42   bool classifyReturnType(CGFunctionInfo &FI) const override;
43 
44   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
45 
46   bool isSRetParameterAfterThis() const override { return true; }
47 
48   StringRef GetPureVirtualCallName() override { return "_purecall"; }
49   // No known support for deleted functions in MSVC yet, so this choice is
50   // arbitrary.
51   StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
52 
53   bool isInlineInitializedStaticDataMemberLinkOnce() override { return true; }
54 
55   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
56                                       llvm::Value *ptr,
57                                       QualType type) override;
58 
59   llvm::Value *
60   GetVirtualBaseClassOffset(CodeGenFunction &CGF, llvm::Value *This,
61                             const CXXRecordDecl *ClassDecl,
62                             const CXXRecordDecl *BaseClassDecl) override;
63 
64   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
65                                  CXXCtorType Type, CanQualType &ResTy,
66                                  SmallVectorImpl<CanQualType> &ArgTys) override;
67 
68   llvm::BasicBlock *
69   EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
70                                 const CXXRecordDecl *RD) override;
71 
72   void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
73                                               const CXXRecordDecl *RD) override;
74 
75   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
76 
77   // Background on MSVC destructors
78   // ==============================
79   //
80   // Both Itanium and MSVC ABIs have destructor variants.  The variant names
81   // roughly correspond in the following way:
82   //   Itanium       Microsoft
83   //   Base       -> no name, just ~Class
84   //   Complete   -> vbase destructor
85   //   Deleting   -> scalar deleting destructor
86   //                 vector deleting destructor
87   //
88   // The base and complete destructors are the same as in Itanium, although the
89   // complete destructor does not accept a VTT parameter when there are virtual
90   // bases.  A separate mechanism involving vtordisps is used to ensure that
91   // virtual methods of destroyed subobjects are not called.
92   //
93   // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
94   // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
95   // pointer points to an array.  The scalar deleting destructor assumes that
96   // bit 2 is zero, and therefore does not contain a loop.
97   //
98   // For virtual destructors, only one entry is reserved in the vftable, and it
99   // always points to the vector deleting destructor.  The vector deleting
100   // destructor is the most general, so it can be used to destroy objects in
101   // place, delete single heap objects, or delete arrays.
102   //
103   // A TU defining a non-inline destructor is only guaranteed to emit a base
104   // destructor, and all of the other variants are emitted on an as-needed basis
105   // in COMDATs.  Because a non-base destructor can be emitted in a TU that
106   // lacks a definition for the destructor, non-base destructors must always
107   // delegate to or alias the base destructor.
108 
109   void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
110                                 CXXDtorType Type,
111                                 CanQualType &ResTy,
112                                 SmallVectorImpl<CanQualType> &ArgTys) override;
113 
114   /// Non-base dtors should be emitted as delegating thunks in this ABI.
115   bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
116                               CXXDtorType DT) const override {
117     return DT != Dtor_Base;
118   }
119 
120   void EmitCXXDestructors(const CXXDestructorDecl *D) override;
121 
122   const CXXRecordDecl *
123   getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
124     MD = MD->getCanonicalDecl();
125     if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
126       MicrosoftVTableContext::MethodVFTableLocation ML =
127           CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
128       // The vbases might be ordered differently in the final overrider object
129       // and the complete object, so the "this" argument may sometimes point to
130       // memory that has no particular type (e.g. past the complete object).
131       // In this case, we just use a generic pointer type.
132       // FIXME: might want to have a more precise type in the non-virtual
133       // multiple inheritance case.
134       if (ML.VBase || !ML.VFPtrOffset.isZero())
135         return nullptr;
136     }
137     return MD->getParent();
138   }
139 
140   llvm::Value *
141   adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
142                                            llvm::Value *This,
143                                            bool VirtualCall) override;
144 
145   void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
146                                  FunctionArgList &Params) override;
147 
148   llvm::Value *adjustThisParameterInVirtualFunctionPrologue(
149       CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) override;
150 
151   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
152 
153   unsigned addImplicitConstructorArgs(CodeGenFunction &CGF,
154                                       const CXXConstructorDecl *D,
155                                       CXXCtorType Type, bool ForVirtualBase,
156                                       bool Delegating,
157                                       CallArgList &Args) override;
158 
159   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
160                           CXXDtorType Type, bool ForVirtualBase,
161                           bool Delegating, llvm::Value *This) override;
162 
163   void emitVTableDefinitions(CodeGenVTables &CGVT,
164                              const CXXRecordDecl *RD) override;
165 
166   llvm::Value *getVTableAddressPointInStructor(
167       CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
168       BaseSubobject Base, const CXXRecordDecl *NearestVBase,
169       bool &NeedsVirtualOffset) override;
170 
171   llvm::Constant *
172   getVTableAddressPointForConstExpr(BaseSubobject Base,
173                                     const CXXRecordDecl *VTableClass) override;
174 
175   llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
176                                         CharUnits VPtrOffset) override;
177 
178   llvm::Value *getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
179                                          llvm::Value *This,
180                                          llvm::Type *Ty) override;
181 
182   void EmitVirtualDestructorCall(CodeGenFunction &CGF,
183                                  const CXXDestructorDecl *Dtor,
184                                  CXXDtorType DtorType, SourceLocation CallLoc,
185                                  llvm::Value *This) override;
186 
187   void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
188                                         CallArgList &CallArgs) override {
189     assert(GD.getDtorType() == Dtor_Deleting &&
190            "Only deleting destructor thunks are available in this ABI");
191     CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
192                              CGM.getContext().IntTy);
193   }
194 
195   void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
196 
197   llvm::GlobalVariable *
198   getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
199                    llvm::GlobalVariable::LinkageTypes Linkage);
200 
201   void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
202                              llvm::GlobalVariable *GV) const;
203 
204   void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
205                        GlobalDecl GD, bool ReturnAdjustment) override {
206     // Never dllimport/dllexport thunks.
207     Thunk->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
208 
209     GVALinkage Linkage =
210         getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
211 
212     if (Linkage == GVA_Internal)
213       Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
214     else if (ReturnAdjustment)
215       Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
216     else
217       Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
218   }
219 
220   llvm::Value *performThisAdjustment(CodeGenFunction &CGF, llvm::Value *This,
221                                      const ThisAdjustment &TA) override;
222 
223   llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
224                                        const ReturnAdjustment &RA) override;
225 
226   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
227                        llvm::GlobalVariable *DeclPtr,
228                        bool PerformInit) override;
229 
230   // ==== Notes on array cookies =========
231   //
232   // MSVC seems to only use cookies when the class has a destructor; a
233   // two-argument usual array deallocation function isn't sufficient.
234   //
235   // For example, this code prints "100" and "1":
236   //   struct A {
237   //     char x;
238   //     void *operator new[](size_t sz) {
239   //       printf("%u\n", sz);
240   //       return malloc(sz);
241   //     }
242   //     void operator delete[](void *p, size_t sz) {
243   //       printf("%u\n", sz);
244   //       free(p);
245   //     }
246   //   };
247   //   int main() {
248   //     A *p = new A[100];
249   //     delete[] p;
250   //   }
251   // Whereas it prints "104" and "104" if you give A a destructor.
252 
253   bool requiresArrayCookie(const CXXDeleteExpr *expr,
254                            QualType elementType) override;
255   bool requiresArrayCookie(const CXXNewExpr *expr) override;
256   CharUnits getArrayCookieSizeImpl(QualType type) override;
257   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
258                                      llvm::Value *NewPtr,
259                                      llvm::Value *NumElements,
260                                      const CXXNewExpr *expr,
261                                      QualType ElementType) override;
262   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
263                                    llvm::Value *allocPtr,
264                                    CharUnits cookieSize) override;
265 
266 private:
267   MicrosoftMangleContext &getMangleContext() {
268     return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
269   }
270 
271   llvm::Constant *getZeroInt() {
272     return llvm::ConstantInt::get(CGM.IntTy, 0);
273   }
274 
275   llvm::Constant *getAllOnesInt() {
276     return  llvm::Constant::getAllOnesValue(CGM.IntTy);
277   }
278 
279   llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
280     return C ? C : getZeroInt();
281   }
282 
283   llvm::Value *getValueOrZeroInt(llvm::Value *C) {
284     return C ? C : getZeroInt();
285   }
286 
287   CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD);
288 
289   void
290   GetNullMemberPointerFields(const MemberPointerType *MPT,
291                              llvm::SmallVectorImpl<llvm::Constant *> &fields);
292 
293   /// \brief Shared code for virtual base adjustment.  Returns the offset from
294   /// the vbptr to the virtual base.  Optionally returns the address of the
295   /// vbptr itself.
296   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
297                                        llvm::Value *Base,
298                                        llvm::Value *VBPtrOffset,
299                                        llvm::Value *VBTableOffset,
300                                        llvm::Value **VBPtr = nullptr);
301 
302   llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
303                                        llvm::Value *Base,
304                                        int32_t VBPtrOffset,
305                                        int32_t VBTableOffset,
306                                        llvm::Value **VBPtr = nullptr) {
307     llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
308                 *VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
309     return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
310   }
311 
312   /// \brief Performs a full virtual base adjustment.  Used to dereference
313   /// pointers to members of virtual bases.
314   llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
315                                  const CXXRecordDecl *RD, llvm::Value *Base,
316                                  llvm::Value *VirtualBaseAdjustmentOffset,
317                                  llvm::Value *VBPtrOffset /* optional */);
318 
319   /// \brief Emits a full member pointer with the fields common to data and
320   /// function member pointers.
321   llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
322                                         bool IsMemberFunction,
323                                         const CXXRecordDecl *RD,
324                                         CharUnits NonVirtualBaseAdjustment);
325 
326   llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
327                                      const CXXMethodDecl *MD,
328                                      CharUnits NonVirtualBaseAdjustment);
329 
330   bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
331                                    llvm::Constant *MP);
332 
333   /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
334   void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
335 
336   /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
337   const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
338 
339   /// \brief Generate a thunk for calling a virtual member function MD.
340   llvm::Function *EmitVirtualMemPtrThunk(
341       const CXXMethodDecl *MD,
342       const MicrosoftVTableContext::MethodVFTableLocation &ML);
343 
344 public:
345   llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
346 
347   bool isZeroInitializable(const MemberPointerType *MPT) override;
348 
349   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
350 
351   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
352                                         CharUnits offset) override;
353   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD) override;
354   llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
355 
356   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
357                                            llvm::Value *L,
358                                            llvm::Value *R,
359                                            const MemberPointerType *MPT,
360                                            bool Inequality) override;
361 
362   llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
363                                           llvm::Value *MemPtr,
364                                           const MemberPointerType *MPT) override;
365 
366   llvm::Value *
367   EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
368                                llvm::Value *Base, llvm::Value *MemPtr,
369                                const MemberPointerType *MPT) override;
370 
371   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
372                                            const CastExpr *E,
373                                            llvm::Value *Src) override;
374 
375   llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
376                                               llvm::Constant *Src) override;
377 
378   llvm::Value *
379   EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
380                                   llvm::Value *&This, llvm::Value *MemPtr,
381                                   const MemberPointerType *MPT) override;
382 
383 private:
384   typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
385   typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VFTablesMapTy;
386   /// \brief All the vftables that have been referenced.
387   VFTablesMapTy VFTablesMap;
388 
389   /// \brief This set holds the record decls we've deferred vtable emission for.
390   llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
391 
392 
393   /// \brief All the vbtables which have been referenced.
394   llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
395 
396   /// Info on the global variable used to guard initialization of static locals.
397   /// The BitIndex field is only used for externally invisible declarations.
398   struct GuardInfo {
399     GuardInfo() : Guard(nullptr), BitIndex(0) {}
400     llvm::GlobalVariable *Guard;
401     unsigned BitIndex;
402   };
403 
404   /// Map from DeclContext to the current guard variable.  We assume that the
405   /// AST is visited in source code order.
406   llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
407 };
408 
409 }
410 
411 CGCXXABI::RecordArgABI
412 MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
413   switch (CGM.getTarget().getTriple().getArch()) {
414   default:
415     // FIXME: Implement for other architectures.
416     return RAA_Default;
417 
418   case llvm::Triple::x86:
419     // All record arguments are passed in memory on x86.  Decide whether to
420     // construct the object directly in argument memory, or to construct the
421     // argument elsewhere and copy the bytes during the call.
422 
423     // If C++ prohibits us from making a copy, construct the arguments directly
424     // into argument memory.
425     if (!canCopyArgument(RD))
426       return RAA_DirectInMemory;
427 
428     // Otherwise, construct the argument into a temporary and copy the bytes
429     // into the outgoing argument memory.
430     return RAA_Default;
431 
432   case llvm::Triple::x86_64:
433     // Win64 passes objects with non-trivial copy ctors indirectly.
434     if (RD->hasNonTrivialCopyConstructor())
435       return RAA_Indirect;
436 
437     // Win64 passes objects larger than 8 bytes indirectly.
438     if (getContext().getTypeSize(RD->getTypeForDecl()) > 64)
439       return RAA_Indirect;
440 
441     // We have a trivial copy constructor or no copy constructors, but we have
442     // to make sure it isn't deleted.
443     bool CopyDeleted = false;
444     for (const CXXConstructorDecl *CD : RD->ctors()) {
445       if (CD->isCopyConstructor()) {
446         assert(CD->isTrivial());
447         // We had at least one undeleted trivial copy ctor.  Return directly.
448         if (!CD->isDeleted())
449           return RAA_Default;
450         CopyDeleted = true;
451       }
452     }
453 
454     // The trivial copy constructor was deleted.  Return indirectly.
455     if (CopyDeleted)
456       return RAA_Indirect;
457 
458     // There were no copy ctors.  Return in RAX.
459     return RAA_Default;
460   }
461 
462   llvm_unreachable("invalid enum");
463 }
464 
465 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
466                                                      llvm::Value *ptr,
467                                                      QualType type) {
468   // FIXME: implement
469   return ptr;
470 }
471 
472 llvm::Value *
473 MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
474                                            llvm::Value *This,
475                                            const CXXRecordDecl *ClassDecl,
476                                            const CXXRecordDecl *BaseClassDecl) {
477   int64_t VBPtrChars =
478       getContext().getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
479   llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
480   CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
481   CharUnits VBTableChars =
482       IntSize *
483       CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
484   llvm::Value *VBTableOffset =
485     llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
486 
487   llvm::Value *VBPtrToNewBase =
488     GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
489   VBPtrToNewBase =
490     CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
491   return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
492 }
493 
494 bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
495   return isa<CXXConstructorDecl>(GD.getDecl());
496 }
497 
498 bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
499   const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
500   if (!RD)
501     return false;
502 
503   if (FI.isInstanceMethod()) {
504     // If it's an instance method, aggregates are always returned indirectly via
505     // the second parameter.
506     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
507     FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
508     return true;
509   } else if (!RD->isPOD()) {
510     // If it's a free function, non-POD types are returned indirectly.
511     FI.getReturnInfo() = ABIArgInfo::getIndirect(0, /*ByVal=*/false);
512     return true;
513   }
514 
515   // Otherwise, use the C ABI rules.
516   return false;
517 }
518 
519 void MicrosoftCXXABI::BuildConstructorSignature(
520     const CXXConstructorDecl *Ctor, CXXCtorType Type, CanQualType &ResTy,
521     SmallVectorImpl<CanQualType> &ArgTys) {
522 
523   // All parameters are already in place except is_most_derived, which goes
524   // after 'this' if it's variadic and last if it's not.
525 
526   const CXXRecordDecl *Class = Ctor->getParent();
527   const FunctionProtoType *FPT = Ctor->getType()->castAs<FunctionProtoType>();
528   if (Class->getNumVBases()) {
529     if (FPT->isVariadic())
530       ArgTys.insert(ArgTys.begin() + 1, CGM.getContext().IntTy);
531     else
532       ArgTys.push_back(CGM.getContext().IntTy);
533   }
534 }
535 
536 llvm::BasicBlock *
537 MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
538                                                const CXXRecordDecl *RD) {
539   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
540   assert(IsMostDerivedClass &&
541          "ctor for a class with virtual bases must have an implicit parameter");
542   llvm::Value *IsCompleteObject =
543     CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
544 
545   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
546   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
547   CGF.Builder.CreateCondBr(IsCompleteObject,
548                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
549 
550   CGF.EmitBlock(CallVbaseCtorsBB);
551 
552   // Fill in the vbtable pointers here.
553   EmitVBPtrStores(CGF, RD);
554 
555   // CGF will put the base ctor calls in this basic block for us later.
556 
557   return SkipVbaseCtorsBB;
558 }
559 
560 void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
561     CodeGenFunction &CGF, const CXXRecordDecl *RD) {
562   // In most cases, an override for a vbase virtual method can adjust
563   // the "this" parameter by applying a constant offset.
564   // However, this is not enough while a constructor or a destructor of some
565   // class X is being executed if all the following conditions are met:
566   //  - X has virtual bases, (1)
567   //  - X overrides a virtual method M of a vbase Y, (2)
568   //  - X itself is a vbase of the most derived class.
569   //
570   // If (1) and (2) are true, the vtorDisp for vbase Y is a hidden member of X
571   // which holds the extra amount of "this" adjustment we must do when we use
572   // the X vftables (i.e. during X ctor or dtor).
573   // Outside the ctors and dtors, the values of vtorDisps are zero.
574 
575   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
576   typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
577   const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
578   CGBuilderTy &Builder = CGF.Builder;
579 
580   unsigned AS =
581       cast<llvm::PointerType>(getThisValue(CGF)->getType())->getAddressSpace();
582   llvm::Value *Int8This = nullptr;  // Initialize lazily.
583 
584   for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
585         I != E; ++I) {
586     if (!I->second.hasVtorDisp())
587       continue;
588 
589     llvm::Value *VBaseOffset =
590         GetVirtualBaseClassOffset(CGF, getThisValue(CGF), RD, I->first);
591     // FIXME: it doesn't look right that we SExt in GetVirtualBaseClassOffset()
592     // just to Trunc back immediately.
593     VBaseOffset = Builder.CreateTruncOrBitCast(VBaseOffset, CGF.Int32Ty);
594     uint64_t ConstantVBaseOffset =
595         Layout.getVBaseClassOffset(I->first).getQuantity();
596 
597     // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
598     llvm::Value *VtorDispValue = Builder.CreateSub(
599         VBaseOffset, llvm::ConstantInt::get(CGM.Int32Ty, ConstantVBaseOffset),
600         "vtordisp.value");
601 
602     if (!Int8This)
603       Int8This = Builder.CreateBitCast(getThisValue(CGF),
604                                        CGF.Int8Ty->getPointerTo(AS));
605     llvm::Value *VtorDispPtr = Builder.CreateInBoundsGEP(Int8This, VBaseOffset);
606     // vtorDisp is always the 32-bits before the vbase in the class layout.
607     VtorDispPtr = Builder.CreateConstGEP1_32(VtorDispPtr, -4);
608     VtorDispPtr = Builder.CreateBitCast(
609         VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
610 
611     Builder.CreateStore(VtorDispValue, VtorDispPtr);
612   }
613 }
614 
615 void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
616   // There's only one constructor type in this ABI.
617   CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
618 }
619 
620 void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
621                                       const CXXRecordDecl *RD) {
622   llvm::Value *ThisInt8Ptr =
623     CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
624   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
625 
626   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
627   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
628     const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
629     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
630     const ASTRecordLayout &SubobjectLayout =
631         CGM.getContext().getASTRecordLayout(VBT->BaseWithVPtr);
632     CharUnits Offs = VBT->NonVirtualOffset;
633     Offs += SubobjectLayout.getVBPtrOffset();
634     if (VBT->getVBaseWithVPtr())
635       Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
636     llvm::Value *VBPtr =
637         CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs.getQuantity());
638     VBPtr = CGF.Builder.CreateBitCast(VBPtr, GV->getType()->getPointerTo(0),
639                                       "vbptr." + VBT->ReusingBase->getName());
640     CGF.Builder.CreateStore(GV, VBPtr);
641   }
642 }
643 
644 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
645                                                CXXDtorType Type,
646                                                CanQualType &ResTy,
647                                         SmallVectorImpl<CanQualType> &ArgTys) {
648   // 'this' is already in place
649 
650   // TODO: 'for base' flag
651 
652   if (Type == Dtor_Deleting) {
653     // The scalar deleting destructor takes an implicit int parameter.
654     ArgTys.push_back(CGM.getContext().IntTy);
655   }
656 }
657 
658 void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
659   // The TU defining a dtor is only guaranteed to emit a base destructor.  All
660   // other destructor variants are delegating thunks.
661   CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
662 }
663 
664 CharUnits
665 MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
666   GD = GD.getCanonicalDecl();
667   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
668 
669   GlobalDecl LookupGD = GD;
670   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
671     // Complete destructors take a pointer to the complete object as a
672     // parameter, thus don't need this adjustment.
673     if (GD.getDtorType() == Dtor_Complete)
674       return CharUnits();
675 
676     // There's no Dtor_Base in vftable but it shares the this adjustment with
677     // the deleting one, so look it up instead.
678     LookupGD = GlobalDecl(DD, Dtor_Deleting);
679   }
680 
681   MicrosoftVTableContext::MethodVFTableLocation ML =
682       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
683   CharUnits Adjustment = ML.VFPtrOffset;
684 
685   // Normal virtual instance methods need to adjust from the vfptr that first
686   // defined the virtual method to the virtual base subobject, but destructors
687   // do not.  The vector deleting destructor thunk applies this adjustment for
688   // us if necessary.
689   if (isa<CXXDestructorDecl>(MD))
690     Adjustment = CharUnits::Zero();
691 
692   if (ML.VBase) {
693     const ASTRecordLayout &DerivedLayout =
694         CGM.getContext().getASTRecordLayout(MD->getParent());
695     Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
696   }
697 
698   return Adjustment;
699 }
700 
701 llvm::Value *MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
702     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This, bool VirtualCall) {
703   if (!VirtualCall) {
704     // If the call of a virtual function is not virtual, we just have to
705     // compensate for the adjustment the virtual function does in its prologue.
706     CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
707     if (Adjustment.isZero())
708       return This;
709 
710     unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
711     llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
712     This = CGF.Builder.CreateBitCast(This, charPtrTy);
713     assert(Adjustment.isPositive());
714     return CGF.Builder.CreateConstGEP1_32(This, Adjustment.getQuantity());
715   }
716 
717   GD = GD.getCanonicalDecl();
718   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
719 
720   GlobalDecl LookupGD = GD;
721   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
722     // Complete dtors take a pointer to the complete object,
723     // thus don't need adjustment.
724     if (GD.getDtorType() == Dtor_Complete)
725       return This;
726 
727     // There's only Dtor_Deleting in vftable but it shares the this adjustment
728     // with the base one, so look up the deleting one instead.
729     LookupGD = GlobalDecl(DD, Dtor_Deleting);
730   }
731   MicrosoftVTableContext::MethodVFTableLocation ML =
732       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
733 
734   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
735   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS);
736   CharUnits StaticOffset = ML.VFPtrOffset;
737 
738   // Base destructors expect 'this' to point to the beginning of the base
739   // subobject, not the first vfptr that happens to contain the virtual dtor.
740   // However, we still need to apply the virtual base adjustment.
741   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
742     StaticOffset = CharUnits::Zero();
743 
744   if (ML.VBase) {
745     This = CGF.Builder.CreateBitCast(This, charPtrTy);
746     llvm::Value *VBaseOffset =
747         GetVirtualBaseClassOffset(CGF, This, MD->getParent(), ML.VBase);
748     This = CGF.Builder.CreateInBoundsGEP(This, VBaseOffset);
749   }
750   if (!StaticOffset.isZero()) {
751     assert(StaticOffset.isPositive());
752     This = CGF.Builder.CreateBitCast(This, charPtrTy);
753     if (ML.VBase) {
754       // Non-virtual adjustment might result in a pointer outside the allocated
755       // object, e.g. if the final overrider class is laid out after the virtual
756       // base that declares a method in the most derived class.
757       // FIXME: Update the code that emits this adjustment in thunks prologues.
758       This = CGF.Builder.CreateConstGEP1_32(This, StaticOffset.getQuantity());
759     } else {
760       This = CGF.Builder.CreateConstInBoundsGEP1_32(This,
761                                                     StaticOffset.getQuantity());
762     }
763   }
764   return This;
765 }
766 
767 static bool IsDeletingDtor(GlobalDecl GD) {
768   const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
769   if (isa<CXXDestructorDecl>(MD)) {
770     return GD.getDtorType() == Dtor_Deleting;
771   }
772   return false;
773 }
774 
775 void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
776                                                 QualType &ResTy,
777                                                 FunctionArgList &Params) {
778   ASTContext &Context = getContext();
779   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
780   assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
781   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
782     ImplicitParamDecl *IsMostDerived
783       = ImplicitParamDecl::Create(Context, nullptr,
784                                   CGF.CurGD.getDecl()->getLocation(),
785                                   &Context.Idents.get("is_most_derived"),
786                                   Context.IntTy);
787     // The 'most_derived' parameter goes second if the ctor is variadic and last
788     // if it's not.  Dtors can't be variadic.
789     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
790     if (FPT->isVariadic())
791       Params.insert(Params.begin() + 1, IsMostDerived);
792     else
793       Params.push_back(IsMostDerived);
794     getStructorImplicitParamDecl(CGF) = IsMostDerived;
795   } else if (IsDeletingDtor(CGF.CurGD)) {
796     ImplicitParamDecl *ShouldDelete
797       = ImplicitParamDecl::Create(Context, nullptr,
798                                   CGF.CurGD.getDecl()->getLocation(),
799                                   &Context.Idents.get("should_call_delete"),
800                                   Context.IntTy);
801     Params.push_back(ShouldDelete);
802     getStructorImplicitParamDecl(CGF) = ShouldDelete;
803   }
804 }
805 
806 llvm::Value *MicrosoftCXXABI::adjustThisParameterInVirtualFunctionPrologue(
807     CodeGenFunction &CGF, GlobalDecl GD, llvm::Value *This) {
808   // In this ABI, every virtual function takes a pointer to one of the
809   // subobjects that first defines it as the 'this' parameter, rather than a
810   // pointer to the final overrider subobject. Thus, we need to adjust it back
811   // to the final overrider subobject before use.
812   // See comments in the MicrosoftVFTableContext implementation for the details.
813   CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
814   if (Adjustment.isZero())
815     return This;
816 
817   unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
818   llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
819              *thisTy = This->getType();
820 
821   This = CGF.Builder.CreateBitCast(This, charPtrTy);
822   assert(Adjustment.isPositive());
823   This =
824       CGF.Builder.CreateConstInBoundsGEP1_32(This, -Adjustment.getQuantity());
825   return CGF.Builder.CreateBitCast(This, thisTy);
826 }
827 
828 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
829   EmitThisParam(CGF);
830 
831   /// If this is a function that the ABI specifies returns 'this', initialize
832   /// the return slot to 'this' at the start of the function.
833   ///
834   /// Unlike the setting of return types, this is done within the ABI
835   /// implementation instead of by clients of CGCXXABI because:
836   /// 1) getThisValue is currently protected
837   /// 2) in theory, an ABI could implement 'this' returns some other way;
838   ///    HasThisReturn only specifies a contract, not the implementation
839   if (HasThisReturn(CGF.CurGD))
840     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
841 
842   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
843   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
844     assert(getStructorImplicitParamDecl(CGF) &&
845            "no implicit parameter for a constructor with virtual bases?");
846     getStructorImplicitParamValue(CGF)
847       = CGF.Builder.CreateLoad(
848           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
849           "is_most_derived");
850   }
851 
852   if (IsDeletingDtor(CGF.CurGD)) {
853     assert(getStructorImplicitParamDecl(CGF) &&
854            "no implicit parameter for a deleting destructor?");
855     getStructorImplicitParamValue(CGF)
856       = CGF.Builder.CreateLoad(
857           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
858           "should_call_delete");
859   }
860 }
861 
862 unsigned MicrosoftCXXABI::addImplicitConstructorArgs(
863     CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
864     bool ForVirtualBase, bool Delegating, CallArgList &Args) {
865   assert(Type == Ctor_Complete || Type == Ctor_Base);
866 
867   // Check if we need a 'most_derived' parameter.
868   if (!D->getParent()->getNumVBases())
869     return 0;
870 
871   // Add the 'most_derived' argument second if we are variadic or last if not.
872   const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
873   llvm::Value *MostDerivedArg =
874       llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
875   RValue RV = RValue::get(MostDerivedArg);
876   if (MostDerivedArg) {
877     if (FPT->isVariadic())
878       Args.insert(Args.begin() + 1,
879                   CallArg(RV, getContext().IntTy, /*needscopy=*/false));
880     else
881       Args.add(RV, getContext().IntTy);
882   }
883 
884   return 1;  // Added one arg.
885 }
886 
887 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
888                                          const CXXDestructorDecl *DD,
889                                          CXXDtorType Type, bool ForVirtualBase,
890                                          bool Delegating, llvm::Value *This) {
891   llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
892 
893   if (DD->isVirtual()) {
894     assert(Type != CXXDtorType::Dtor_Deleting &&
895            "The deleting destructor should only be called via a virtual call");
896     This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
897                                                     This, false);
898   }
899 
900   // FIXME: Provide a source location here.
901   CGF.EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
902                         /*ImplicitParam=*/nullptr,
903                         /*ImplicitParamTy=*/QualType(), nullptr, nullptr);
904 }
905 
906 void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
907                                             const CXXRecordDecl *RD) {
908   MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
909   VPtrInfoVector VFPtrs = VFTContext.getVFPtrOffsets(RD);
910   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
911 
912   for (VPtrInfo *Info : VFPtrs) {
913     llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
914     if (VTable->hasInitializer())
915       continue;
916     if (getContext().getLangOpts().RTTI)
917       CGM.getMSCompleteObjectLocator(RD, Info);
918 
919     const VTableLayout &VTLayout =
920       VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
921     llvm::Constant *Init = CGVT.CreateVTableInitializer(
922         RD, VTLayout.vtable_component_begin(),
923         VTLayout.getNumVTableComponents(), VTLayout.vtable_thunk_begin(),
924         VTLayout.getNumVTableThunks());
925     VTable->setInitializer(Init);
926 
927     VTable->setLinkage(Linkage);
928 
929     CGM.setGlobalVisibility(VTable, RD);
930   }
931 }
932 
933 llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
934     CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
935     const CXXRecordDecl *NearestVBase, bool &NeedsVirtualOffset) {
936   NeedsVirtualOffset = (NearestVBase != nullptr);
937 
938   llvm::Value *VTableAddressPoint =
939       getAddrOfVTable(VTableClass, Base.getBaseOffset());
940   if (!VTableAddressPoint) {
941     assert(Base.getBase()->getNumVBases() &&
942            !CGM.getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
943   }
944   return VTableAddressPoint;
945 }
946 
947 static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
948                               const CXXRecordDecl *RD, const VPtrInfo *VFPtr,
949                               SmallString<256> &Name) {
950   llvm::raw_svector_ostream Out(Name);
951   MangleContext.mangleCXXVFTable(RD, VFPtr->MangledPath, Out);
952 }
953 
954 llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
955     BaseSubobject Base, const CXXRecordDecl *VTableClass) {
956   llvm::Constant *VTable = getAddrOfVTable(VTableClass, Base.getBaseOffset());
957   assert(VTable && "Couldn't find a vftable for the given base?");
958   return VTable;
959 }
960 
961 llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
962                                                        CharUnits VPtrOffset) {
963   // getAddrOfVTable may return 0 if asked to get an address of a vtable which
964   // shouldn't be used in the given record type. We want to cache this result in
965   // VFTablesMap, thus a simple zero check is not sufficient.
966   VFTableIdTy ID(RD, VPtrOffset);
967   VFTablesMapTy::iterator I;
968   bool Inserted;
969   std::tie(I, Inserted) = VFTablesMap.insert(std::make_pair(ID, nullptr));
970   if (!Inserted)
971     return I->second;
972 
973   llvm::GlobalVariable *&VTable = I->second;
974 
975   MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
976   const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
977 
978   if (DeferredVFTables.insert(RD)) {
979     // We haven't processed this record type before.
980     // Queue up this v-table for possible deferred emission.
981     CGM.addDeferredVTable(RD);
982 
983 #ifndef NDEBUG
984     // Create all the vftables at once in order to make sure each vftable has
985     // a unique mangled name.
986     llvm::StringSet<> ObservedMangledNames;
987     for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
988       SmallString<256> Name;
989       mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
990       if (!ObservedMangledNames.insert(Name.str()))
991         llvm_unreachable("Already saw this mangling before?");
992     }
993 #endif
994   }
995 
996   for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
997     if (VFPtrs[J]->FullOffsetInMDC != VPtrOffset)
998       continue;
999 
1000     llvm::ArrayType *ArrayType = llvm::ArrayType::get(
1001         CGM.Int8PtrTy,
1002         VTContext.getVFTableLayout(RD, VFPtrs[J]->FullOffsetInMDC)
1003             .getNumVTableComponents());
1004 
1005     SmallString<256> Name;
1006     mangleVFTableName(getMangleContext(), RD, VFPtrs[J], Name);
1007     VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
1008         Name.str(), ArrayType, llvm::GlobalValue::ExternalLinkage);
1009     VTable->setUnnamedAddr(true);
1010     if (RD->hasAttr<DLLImportAttr>())
1011       VTable->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1012     else if (RD->hasAttr<DLLExportAttr>())
1013       VTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1014     break;
1015   }
1016 
1017   return VTable;
1018 }
1019 
1020 llvm::Value *MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
1021                                                         GlobalDecl GD,
1022                                                         llvm::Value *This,
1023                                                         llvm::Type *Ty) {
1024   GD = GD.getCanonicalDecl();
1025   CGBuilderTy &Builder = CGF.Builder;
1026 
1027   Ty = Ty->getPointerTo()->getPointerTo();
1028   llvm::Value *VPtr =
1029       adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1030   llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty);
1031 
1032   MicrosoftVTableContext::MethodVFTableLocation ML =
1033       CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1034   llvm::Value *VFuncPtr =
1035       Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1036   return Builder.CreateLoad(VFuncPtr);
1037 }
1038 
1039 void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
1040                                                 const CXXDestructorDecl *Dtor,
1041                                                 CXXDtorType DtorType,
1042                                                 SourceLocation CallLoc,
1043                                                 llvm::Value *This) {
1044   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
1045 
1046   // We have only one destructor in the vftable but can get both behaviors
1047   // by passing an implicit int parameter.
1048   GlobalDecl GD(Dtor, Dtor_Deleting);
1049   const CGFunctionInfo *FInfo =
1050       &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
1051   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
1052   llvm::Value *Callee = getVirtualFunctionPointer(CGF, GD, This, Ty);
1053 
1054   ASTContext &Context = CGF.getContext();
1055   llvm::Value *ImplicitParam =
1056       llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
1057                              DtorType == Dtor_Deleting);
1058 
1059   This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
1060   CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
1061                         ImplicitParam, Context.IntTy, nullptr, nullptr);
1062 }
1063 
1064 const VBTableGlobals &
1065 MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
1066   // At this layer, we can key the cache off of a single class, which is much
1067   // easier than caching each vbtable individually.
1068   llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
1069   bool Added;
1070   std::tie(Entry, Added) =
1071       VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
1072   VBTableGlobals &VBGlobals = Entry->second;
1073   if (!Added)
1074     return VBGlobals;
1075 
1076   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1077   VBGlobals.VBTables = &Context.enumerateVBTables(RD);
1078 
1079   // Cache the globals for all vbtables so we don't have to recompute the
1080   // mangled names.
1081   llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
1082   for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
1083                                       E = VBGlobals.VBTables->end();
1084        I != E; ++I) {
1085     VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
1086   }
1087 
1088   return VBGlobals;
1089 }
1090 
1091 llvm::Function *MicrosoftCXXABI::EmitVirtualMemPtrThunk(
1092     const CXXMethodDecl *MD,
1093     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
1094   // Calculate the mangled name.
1095   SmallString<256> ThunkName;
1096   llvm::raw_svector_ostream Out(ThunkName);
1097   getMangleContext().mangleVirtualMemPtrThunk(MD, Out);
1098   Out.flush();
1099 
1100   // If the thunk has been generated previously, just return it.
1101   if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
1102     return cast<llvm::Function>(GV);
1103 
1104   // Create the llvm::Function.
1105   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(MD);
1106   llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
1107   llvm::Function *ThunkFn =
1108       llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
1109                              ThunkName.str(), &CGM.getModule());
1110   assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
1111 
1112   ThunkFn->setLinkage(MD->isExternallyVisible()
1113                           ? llvm::GlobalValue::LinkOnceODRLinkage
1114                           : llvm::GlobalValue::InternalLinkage);
1115 
1116   CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
1117   CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
1118 
1119   // Start codegen.
1120   CodeGenFunction CGF(CGM);
1121   CGF.StartThunk(ThunkFn, MD, FnInfo);
1122 
1123   // Load the vfptr and then callee from the vftable.  The callee should have
1124   // adjusted 'this' so that the vfptr is at offset zero.
1125   llvm::Value *This = CGF.LoadCXXThis();
1126   llvm::Value *VTable =
1127       CGF.GetVTablePtr(This, ThunkTy->getPointerTo()->getPointerTo());
1128   llvm::Value *VFuncPtr =
1129       CGF.Builder.CreateConstInBoundsGEP1_64(VTable, ML.Index, "vfn");
1130   llvm::Value *Callee = CGF.Builder.CreateLoad(VFuncPtr);
1131 
1132   unsigned CallingConv;
1133   CodeGen::AttributeListType AttributeList;
1134   CGM.ConstructAttributeList(FnInfo, MD, AttributeList, CallingConv, true);
1135   llvm::AttributeSet Attrs =
1136       llvm::AttributeSet::get(CGF.getLLVMContext(), AttributeList);
1137 
1138   // Do a musttail call with perfect argument forwarding.  Any inalloca argument
1139   // will be forwarded in place without any copy.
1140   SmallVector<llvm::Value *, 8> Args;
1141   for (llvm::Argument &A : ThunkFn->args())
1142     Args.push_back(&A);
1143   llvm::CallInst *Call = CGF.Builder.CreateCall(Callee, Args);
1144   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
1145   Call->setAttributes(Attrs);
1146   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1147 
1148   if (Call->getType()->isVoidTy())
1149     CGF.Builder.CreateRetVoid();
1150   else
1151     CGF.Builder.CreateRet(Call);
1152 
1153   // Finish the function to maintain CodeGenFunction invariants.
1154   // FIXME: Don't emit unreachable code.
1155   CGF.EmitBlock(CGF.createBasicBlock());
1156   CGF.FinishFunction();
1157 
1158   return ThunkFn;
1159 }
1160 
1161 void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
1162   const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
1163   for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
1164     const VPtrInfo *VBT = (*VBGlobals.VBTables)[I];
1165     llvm::GlobalVariable *GV = VBGlobals.Globals[I];
1166     emitVBTableDefinition(*VBT, RD, GV);
1167   }
1168 }
1169 
1170 llvm::GlobalVariable *
1171 MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
1172                                   llvm::GlobalVariable::LinkageTypes Linkage) {
1173   SmallString<256> OutName;
1174   llvm::raw_svector_ostream Out(OutName);
1175   MicrosoftMangleContext &Mangler =
1176       cast<MicrosoftMangleContext>(CGM.getCXXABI().getMangleContext());
1177   Mangler.mangleCXXVBTable(RD, VBT.MangledPath, Out);
1178   Out.flush();
1179   StringRef Name = OutName.str();
1180 
1181   llvm::ArrayType *VBTableType =
1182       llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ReusingBase->getNumVBases());
1183 
1184   assert(!CGM.getModule().getNamedGlobal(Name) &&
1185          "vbtable with this name already exists: mangling bug?");
1186   llvm::GlobalVariable *GV =
1187       CGM.CreateOrReplaceCXXRuntimeVariable(Name, VBTableType, Linkage);
1188   GV->setUnnamedAddr(true);
1189 
1190   if (RD->hasAttr<DLLImportAttr>())
1191     GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1192   else if (RD->hasAttr<DLLExportAttr>())
1193     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1194 
1195   return GV;
1196 }
1197 
1198 void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
1199                                             const CXXRecordDecl *RD,
1200                                             llvm::GlobalVariable *GV) const {
1201   const CXXRecordDecl *ReusingBase = VBT.ReusingBase;
1202 
1203   assert(RD->getNumVBases() && ReusingBase->getNumVBases() &&
1204          "should only emit vbtables for classes with vbtables");
1205 
1206   const ASTRecordLayout &BaseLayout =
1207       CGM.getContext().getASTRecordLayout(VBT.BaseWithVPtr);
1208   const ASTRecordLayout &DerivedLayout =
1209     CGM.getContext().getASTRecordLayout(RD);
1210 
1211   SmallVector<llvm::Constant *, 4> Offsets(1 + ReusingBase->getNumVBases(),
1212                                            nullptr);
1213 
1214   // The offset from ReusingBase's vbptr to itself always leads.
1215   CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
1216   Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
1217 
1218   MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
1219   for (const auto &I : ReusingBase->vbases()) {
1220     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
1221     CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
1222     assert(!Offset.isNegative());
1223 
1224     // Make it relative to the subobject vbptr.
1225     CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
1226     if (VBT.getVBaseWithVPtr())
1227       CompleteVBPtrOffset +=
1228           DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
1229     Offset -= CompleteVBPtrOffset;
1230 
1231     unsigned VBIndex = Context.getVBTableIndex(ReusingBase, VBase);
1232     assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
1233     Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
1234   }
1235 
1236   assert(Offsets.size() ==
1237          cast<llvm::ArrayType>(cast<llvm::PointerType>(GV->getType())
1238                                ->getElementType())->getNumElements());
1239   llvm::ArrayType *VBTableType =
1240     llvm::ArrayType::get(CGM.IntTy, Offsets.size());
1241   llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
1242   GV->setInitializer(Init);
1243 
1244   // Set the right visibility.
1245   CGM.setGlobalVisibility(GV, RD);
1246 }
1247 
1248 llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
1249                                                     llvm::Value *This,
1250                                                     const ThisAdjustment &TA) {
1251   if (TA.isEmpty())
1252     return This;
1253 
1254   llvm::Value *V = CGF.Builder.CreateBitCast(This, CGF.Int8PtrTy);
1255 
1256   if (!TA.Virtual.isEmpty()) {
1257     assert(TA.Virtual.Microsoft.VtordispOffset < 0);
1258     // Adjust the this argument based on the vtordisp value.
1259     llvm::Value *VtorDispPtr =
1260         CGF.Builder.CreateConstGEP1_32(V, TA.Virtual.Microsoft.VtordispOffset);
1261     VtorDispPtr =
1262         CGF.Builder.CreateBitCast(VtorDispPtr, CGF.Int32Ty->getPointerTo());
1263     llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
1264     V = CGF.Builder.CreateGEP(V, CGF.Builder.CreateNeg(VtorDisp));
1265 
1266     if (TA.Virtual.Microsoft.VBPtrOffset) {
1267       // If the final overrider is defined in a virtual base other than the one
1268       // that holds the vfptr, we have to use a vtordispex thunk which looks up
1269       // the vbtable of the derived class.
1270       assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
1271       assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
1272       llvm::Value *VBPtr;
1273       llvm::Value *VBaseOffset =
1274           GetVBaseOffsetFromVBPtr(CGF, V, -TA.Virtual.Microsoft.VBPtrOffset,
1275                                   TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
1276       V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1277     }
1278   }
1279 
1280   if (TA.NonVirtual) {
1281     // Non-virtual adjustment might result in a pointer outside the allocated
1282     // object, e.g. if the final overrider class is laid out after the virtual
1283     // base that declares a method in the most derived class.
1284     V = CGF.Builder.CreateConstGEP1_32(V, TA.NonVirtual);
1285   }
1286 
1287   // Don't need to bitcast back, the call CodeGen will handle this.
1288   return V;
1289 }
1290 
1291 llvm::Value *
1292 MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, llvm::Value *Ret,
1293                                          const ReturnAdjustment &RA) {
1294   if (RA.isEmpty())
1295     return Ret;
1296 
1297   llvm::Value *V = CGF.Builder.CreateBitCast(Ret, CGF.Int8PtrTy);
1298 
1299   if (RA.Virtual.Microsoft.VBIndex) {
1300     assert(RA.Virtual.Microsoft.VBIndex > 0);
1301     int32_t IntSize =
1302         getContext().getTypeSizeInChars(getContext().IntTy).getQuantity();
1303     llvm::Value *VBPtr;
1304     llvm::Value *VBaseOffset =
1305         GetVBaseOffsetFromVBPtr(CGF, V, RA.Virtual.Microsoft.VBPtrOffset,
1306                                 IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
1307     V = CGF.Builder.CreateInBoundsGEP(VBPtr, VBaseOffset);
1308   }
1309 
1310   if (RA.NonVirtual)
1311     V = CGF.Builder.CreateConstInBoundsGEP1_32(V, RA.NonVirtual);
1312 
1313   // Cast back to the original type.
1314   return CGF.Builder.CreateBitCast(V, Ret->getType());
1315 }
1316 
1317 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
1318                                    QualType elementType) {
1319   // Microsoft seems to completely ignore the possibility of a
1320   // two-argument usual deallocation function.
1321   return elementType.isDestructedType();
1322 }
1323 
1324 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
1325   // Microsoft seems to completely ignore the possibility of a
1326   // two-argument usual deallocation function.
1327   return expr->getAllocatedType().isDestructedType();
1328 }
1329 
1330 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
1331   // The array cookie is always a size_t; we then pad that out to the
1332   // alignment of the element type.
1333   ASTContext &Ctx = getContext();
1334   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
1335                   Ctx.getTypeAlignInChars(type));
1336 }
1337 
1338 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
1339                                                   llvm::Value *allocPtr,
1340                                                   CharUnits cookieSize) {
1341   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
1342   llvm::Value *numElementsPtr =
1343     CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
1344   return CGF.Builder.CreateLoad(numElementsPtr);
1345 }
1346 
1347 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
1348                                                     llvm::Value *newPtr,
1349                                                     llvm::Value *numElements,
1350                                                     const CXXNewExpr *expr,
1351                                                     QualType elementType) {
1352   assert(requiresArrayCookie(expr));
1353 
1354   // The size of the cookie.
1355   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
1356 
1357   // Compute an offset to the cookie.
1358   llvm::Value *cookiePtr = newPtr;
1359 
1360   // Write the number of elements into the appropriate slot.
1361   unsigned AS = newPtr->getType()->getPointerAddressSpace();
1362   llvm::Value *numElementsPtr
1363     = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
1364   CGF.Builder.CreateStore(numElements, numElementsPtr);
1365 
1366   // Finally, compute a pointer to the actual data buffer by skipping
1367   // over the cookie completely.
1368   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
1369                                                 cookieSize.getQuantity());
1370 }
1371 
1372 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
1373                                       llvm::GlobalVariable *GV,
1374                                       bool PerformInit) {
1375   // MSVC only uses guards for static locals.
1376   if (!D.isStaticLocal()) {
1377     assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
1378     // GlobalOpt is allowed to discard the initializer, so use linkonce_odr.
1379     CGF.CurFn->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
1380     CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1381     return;
1382   }
1383 
1384   // MSVC always uses an i32 bitfield to guard initialization, which is *not*
1385   // threadsafe.  Since the user may be linking in inline functions compiled by
1386   // cl.exe, there's no reason to provide a false sense of security by using
1387   // critical sections here.
1388 
1389   if (D.getTLSKind())
1390     CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
1391 
1392   CGBuilderTy &Builder = CGF.Builder;
1393   llvm::IntegerType *GuardTy = CGF.Int32Ty;
1394   llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
1395 
1396   // Get the guard variable for this function if we have one already.
1397   GuardInfo *GI = &GuardVariableMap[D.getDeclContext()];
1398 
1399   unsigned BitIndex;
1400   if (D.isStaticLocal() && D.isExternallyVisible()) {
1401     // Externally visible variables have to be numbered in Sema to properly
1402     // handle unreachable VarDecls.
1403     BitIndex = getContext().getStaticLocalNumber(&D);
1404     assert(BitIndex > 0);
1405     BitIndex--;
1406   } else {
1407     // Non-externally visible variables are numbered here in CodeGen.
1408     BitIndex = GI->BitIndex++;
1409   }
1410 
1411   if (BitIndex >= 32) {
1412     if (D.isExternallyVisible())
1413       ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
1414     BitIndex %= 32;
1415     GI->Guard = nullptr;
1416   }
1417 
1418   // Lazily create the i32 bitfield for this function.
1419   if (!GI->Guard) {
1420     // Mangle the name for the guard.
1421     SmallString<256> GuardName;
1422     {
1423       llvm::raw_svector_ostream Out(GuardName);
1424       getMangleContext().mangleStaticGuardVariable(&D, Out);
1425       Out.flush();
1426     }
1427 
1428     // Create the guard variable with a zero-initializer.  Just absorb linkage
1429     // and visibility from the guarded variable.
1430     GI->Guard =
1431         new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
1432                                  GV->getLinkage(), Zero, GuardName.str());
1433     GI->Guard->setVisibility(GV->getVisibility());
1434   } else {
1435     assert(GI->Guard->getLinkage() == GV->getLinkage() &&
1436            "static local from the same function had different linkage");
1437   }
1438 
1439   // Pseudo code for the test:
1440   // if (!(GuardVar & MyGuardBit)) {
1441   //   GuardVar |= MyGuardBit;
1442   //   ... initialize the object ...;
1443   // }
1444 
1445   // Test our bit from the guard variable.
1446   llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1447   llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
1448   llvm::Value *IsInitialized =
1449       Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1450   llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1451   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1452   Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1453 
1454   // Set our bit in the guard variable and emit the initializer and add a global
1455   // destructor if appropriate.
1456   CGF.EmitBlock(InitBlock);
1457   Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
1458   CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1459   Builder.CreateBr(EndBlock);
1460 
1461   // Continue.
1462   CGF.EmitBlock(EndBlock);
1463 }
1464 
1465 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1466   // Null-ness for function memptrs only depends on the first field, which is
1467   // the function pointer.  The rest don't matter, so we can zero initialize.
1468   if (MPT->isMemberFunctionPointer())
1469     return true;
1470 
1471   // The virtual base adjustment field is always -1 for null, so if we have one
1472   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
1473   // valid field offset.
1474   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1475   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1476   return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
1477           RD->nullFieldOffsetIsZero());
1478 }
1479 
1480 llvm::Type *
1481 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1482   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1483   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1484   llvm::SmallVector<llvm::Type *, 4> fields;
1485   if (MPT->isMemberFunctionPointer())
1486     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
1487   else
1488     fields.push_back(CGM.IntTy);  // FieldOffset
1489 
1490   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1491                                           Inheritance))
1492     fields.push_back(CGM.IntTy);
1493   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1494     fields.push_back(CGM.IntTy);
1495   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1496     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
1497 
1498   if (fields.size() == 1)
1499     return fields[0];
1500   return llvm::StructType::get(CGM.getLLVMContext(), fields);
1501 }
1502 
1503 void MicrosoftCXXABI::
1504 GetNullMemberPointerFields(const MemberPointerType *MPT,
1505                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1506   assert(fields.empty());
1507   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1508   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1509   if (MPT->isMemberFunctionPointer()) {
1510     // FunctionPointerOrVirtualThunk
1511     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1512   } else {
1513     if (RD->nullFieldOffsetIsZero())
1514       fields.push_back(getZeroInt());  // FieldOffset
1515     else
1516       fields.push_back(getAllOnesInt());  // FieldOffset
1517   }
1518 
1519   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1520                                           Inheritance))
1521     fields.push_back(getZeroInt());
1522   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1523     fields.push_back(getZeroInt());
1524   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1525     fields.push_back(getAllOnesInt());
1526 }
1527 
1528 llvm::Constant *
1529 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1530   llvm::SmallVector<llvm::Constant *, 4> fields;
1531   GetNullMemberPointerFields(MPT, fields);
1532   if (fields.size() == 1)
1533     return fields[0];
1534   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1535   assert(Res->getType() == ConvertMemberPointerType(MPT));
1536   return Res;
1537 }
1538 
1539 llvm::Constant *
1540 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1541                                        bool IsMemberFunction,
1542                                        const CXXRecordDecl *RD,
1543                                        CharUnits NonVirtualBaseAdjustment)
1544 {
1545   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1546 
1547   // Single inheritance class member pointer are represented as scalars instead
1548   // of aggregates.
1549   if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
1550     return FirstField;
1551 
1552   llvm::SmallVector<llvm::Constant *, 4> fields;
1553   fields.push_back(FirstField);
1554 
1555   if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
1556     fields.push_back(llvm::ConstantInt::get(
1557       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
1558 
1559   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
1560     CharUnits Offs = CharUnits::Zero();
1561     if (RD->getNumVBases())
1562       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1563     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
1564   }
1565 
1566   // The rest of the fields are adjusted by conversions to a more derived class.
1567   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1568     fields.push_back(getZeroInt());
1569 
1570   return llvm::ConstantStruct::getAnon(fields);
1571 }
1572 
1573 llvm::Constant *
1574 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1575                                        CharUnits offset) {
1576   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1577   llvm::Constant *FirstField =
1578     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
1579   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1580                                CharUnits::Zero());
1581 }
1582 
1583 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1584   return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1585 }
1586 
1587 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1588                                                    QualType MPType) {
1589   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1590   const ValueDecl *MPD = MP.getMemberPointerDecl();
1591   if (!MPD)
1592     return EmitNullMemberPointer(MPT);
1593 
1594   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1595 
1596   // FIXME PR15713: Support virtual inheritance paths.
1597 
1598   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1599     return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1600                               ThisAdjustment);
1601 
1602   CharUnits FieldOffset =
1603     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1604   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1605 }
1606 
1607 llvm::Constant *
1608 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1609                                     const CXXMethodDecl *MD,
1610                                     CharUnits NonVirtualBaseAdjustment) {
1611   assert(MD->isInstance() && "Member function must not be static!");
1612   MD = MD->getCanonicalDecl();
1613   RD = RD->getMostRecentDecl();
1614   CodeGenTypes &Types = CGM.getTypes();
1615 
1616   llvm::Constant *FirstField;
1617   if (!MD->isVirtual()) {
1618     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1619     llvm::Type *Ty;
1620     // Check whether the function has a computable LLVM signature.
1621     if (Types.isFuncTypeConvertible(FPT)) {
1622       // The function has a computable LLVM signature; use the correct type.
1623       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1624     } else {
1625       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1626       // function type is incomplete.
1627       Ty = CGM.PtrDiffTy;
1628     }
1629     FirstField = CGM.GetAddrOfFunction(MD, Ty);
1630     FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1631   } else {
1632     MicrosoftVTableContext::MethodVFTableLocation ML =
1633         CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1634     if (MD->isVariadic()) {
1635       CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1636       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1637     } else if (!CGM.getTypes().isFuncTypeConvertible(
1638                     MD->getType()->castAs<FunctionType>())) {
1639       CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1640                                "incomplete return or parameter type");
1641       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1642     } else if (ML.VBase) {
1643       CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1644                                "member function in virtual base class");
1645       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1646     } else {
1647       llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
1648       FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1649       // Include the vfptr adjustment if the method is in a non-primary vftable.
1650       NonVirtualBaseAdjustment += ML.VFPtrOffset;
1651     }
1652   }
1653 
1654   // The rest of the fields are common with data member pointers.
1655   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1656                                NonVirtualBaseAdjustment);
1657 }
1658 
1659 /// Member pointers are the same if they're either bitwise identical *or* both
1660 /// null.  Null-ness for function members is determined by the first field,
1661 /// while for data member pointers we must compare all fields.
1662 llvm::Value *
1663 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1664                                              llvm::Value *L,
1665                                              llvm::Value *R,
1666                                              const MemberPointerType *MPT,
1667                                              bool Inequality) {
1668   CGBuilderTy &Builder = CGF.Builder;
1669 
1670   // Handle != comparisons by switching the sense of all boolean operations.
1671   llvm::ICmpInst::Predicate Eq;
1672   llvm::Instruction::BinaryOps And, Or;
1673   if (Inequality) {
1674     Eq = llvm::ICmpInst::ICMP_NE;
1675     And = llvm::Instruction::Or;
1676     Or = llvm::Instruction::And;
1677   } else {
1678     Eq = llvm::ICmpInst::ICMP_EQ;
1679     And = llvm::Instruction::And;
1680     Or = llvm::Instruction::Or;
1681   }
1682 
1683   // If this is a single field member pointer (single inheritance), this is a
1684   // single icmp.
1685   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1686   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1687   if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
1688                                          Inheritance))
1689     return Builder.CreateICmp(Eq, L, R);
1690 
1691   // Compare the first field.
1692   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1693   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1694   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1695 
1696   // Compare everything other than the first field.
1697   llvm::Value *Res = nullptr;
1698   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1699   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1700     llvm::Value *LF = Builder.CreateExtractValue(L, I);
1701     llvm::Value *RF = Builder.CreateExtractValue(R, I);
1702     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1703     if (Res)
1704       Res = Builder.CreateBinOp(And, Res, Cmp);
1705     else
1706       Res = Cmp;
1707   }
1708 
1709   // Check if the first field is 0 if this is a function pointer.
1710   if (MPT->isMemberFunctionPointer()) {
1711     // (l1 == r1 && ...) || l0 == 0
1712     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1713     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1714     Res = Builder.CreateBinOp(Or, Res, IsZero);
1715   }
1716 
1717   // Combine the comparison of the first field, which must always be true for
1718   // this comparison to succeeed.
1719   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1720 }
1721 
1722 llvm::Value *
1723 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1724                                             llvm::Value *MemPtr,
1725                                             const MemberPointerType *MPT) {
1726   CGBuilderTy &Builder = CGF.Builder;
1727   llvm::SmallVector<llvm::Constant *, 4> fields;
1728   // We only need one field for member functions.
1729   if (MPT->isMemberFunctionPointer())
1730     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1731   else
1732     GetNullMemberPointerFields(MPT, fields);
1733   assert(!fields.empty());
1734   llvm::Value *FirstField = MemPtr;
1735   if (MemPtr->getType()->isStructTy())
1736     FirstField = Builder.CreateExtractValue(MemPtr, 0);
1737   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
1738 
1739   // For function member pointers, we only need to test the function pointer
1740   // field.  The other fields if any can be garbage.
1741   if (MPT->isMemberFunctionPointer())
1742     return Res;
1743 
1744   // Otherwise, emit a series of compares and combine the results.
1745   for (int I = 1, E = fields.size(); I < E; ++I) {
1746     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1747     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1748     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
1749   }
1750   return Res;
1751 }
1752 
1753 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1754                                                   llvm::Constant *Val) {
1755   // Function pointers are null if the pointer in the first field is null.
1756   if (MPT->isMemberFunctionPointer()) {
1757     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1758       Val->getAggregateElement(0U) : Val;
1759     return FirstField->isNullValue();
1760   }
1761 
1762   // If it's not a function pointer and it's zero initializable, we can easily
1763   // check zero.
1764   if (isZeroInitializable(MPT) && Val->isNullValue())
1765     return true;
1766 
1767   // Otherwise, break down all the fields for comparison.  Hopefully these
1768   // little Constants are reused, while a big null struct might not be.
1769   llvm::SmallVector<llvm::Constant *, 4> Fields;
1770   GetNullMemberPointerFields(MPT, Fields);
1771   if (Fields.size() == 1) {
1772     assert(Val->getType()->isIntegerTy());
1773     return Val == Fields[0];
1774   }
1775 
1776   unsigned I, E;
1777   for (I = 0, E = Fields.size(); I != E; ++I) {
1778     if (Val->getAggregateElement(I) != Fields[I])
1779       break;
1780   }
1781   return I == E;
1782 }
1783 
1784 llvm::Value *
1785 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1786                                          llvm::Value *This,
1787                                          llvm::Value *VBPtrOffset,
1788                                          llvm::Value *VBTableOffset,
1789                                          llvm::Value **VBPtrOut) {
1790   CGBuilderTy &Builder = CGF.Builder;
1791   // Load the vbtable pointer from the vbptr in the instance.
1792   This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1793   llvm::Value *VBPtr =
1794     Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1795   if (VBPtrOut) *VBPtrOut = VBPtr;
1796   VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1797   llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1798 
1799   // Load an i32 offset from the vb-table.
1800   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1801   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1802   return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1803 }
1804 
1805 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
1806 // it.
1807 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
1808     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
1809     llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
1810   CGBuilderTy &Builder = CGF.Builder;
1811   Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1812   llvm::BasicBlock *OriginalBB = nullptr;
1813   llvm::BasicBlock *SkipAdjustBB = nullptr;
1814   llvm::BasicBlock *VBaseAdjustBB = nullptr;
1815 
1816   // In the unspecified inheritance model, there might not be a vbtable at all,
1817   // in which case we need to skip the virtual base lookup.  If there is a
1818   // vbtable, the first entry is a no-op entry that gives back the original
1819   // base, so look for a virtual base adjustment offset of zero.
1820   if (VBPtrOffset) {
1821     OriginalBB = Builder.GetInsertBlock();
1822     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1823     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1824     llvm::Value *IsVirtual =
1825       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
1826                            "memptr.is_vbase");
1827     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1828     CGF.EmitBlock(VBaseAdjustBB);
1829   }
1830 
1831   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1832   // know the vbptr offset.
1833   if (!VBPtrOffset) {
1834     CharUnits offs = CharUnits::Zero();
1835     if (!RD->hasDefinition()) {
1836       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
1837       unsigned DiagID = Diags.getCustomDiagID(
1838           DiagnosticsEngine::Error,
1839           "member pointer representation requires a "
1840           "complete class type for %0 to perform this expression");
1841       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
1842     } else if (RD->getNumVBases())
1843       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1844     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1845   }
1846   llvm::Value *VBPtr = nullptr;
1847   llvm::Value *VBaseOffs =
1848     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
1849   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1850 
1851   // Merge control flow with the case where we didn't have to adjust.
1852   if (VBaseAdjustBB) {
1853     Builder.CreateBr(SkipAdjustBB);
1854     CGF.EmitBlock(SkipAdjustBB);
1855     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1856     Phi->addIncoming(Base, OriginalBB);
1857     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1858     return Phi;
1859   }
1860   return AdjustedBase;
1861 }
1862 
1863 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
1864     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
1865     const MemberPointerType *MPT) {
1866   assert(MPT->isMemberDataPointer());
1867   unsigned AS = Base->getType()->getPointerAddressSpace();
1868   llvm::Type *PType =
1869       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1870   CGBuilderTy &Builder = CGF.Builder;
1871   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1872   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1873 
1874   // Extract the fields we need, regardless of model.  We'll apply them if we
1875   // have them.
1876   llvm::Value *FieldOffset = MemPtr;
1877   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
1878   llvm::Value *VBPtrOffset = nullptr;
1879   if (MemPtr->getType()->isStructTy()) {
1880     // We need to extract values.
1881     unsigned I = 0;
1882     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1883     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1884       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1885     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1886       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1887   }
1888 
1889   if (VirtualBaseAdjustmentOffset) {
1890     Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
1891                              VBPtrOffset);
1892   }
1893 
1894   // Cast to char*.
1895   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1896 
1897   // Apply the offset, which we assume is non-null.
1898   llvm::Value *Addr =
1899     Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
1900 
1901   // Cast the address to the appropriate pointer type, adopting the address
1902   // space of the base pointer.
1903   return Builder.CreateBitCast(Addr, PType);
1904 }
1905 
1906 static MSInheritanceAttr::Spelling
1907 getInheritanceFromMemptr(const MemberPointerType *MPT) {
1908   return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
1909 }
1910 
1911 llvm::Value *
1912 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1913                                              const CastExpr *E,
1914                                              llvm::Value *Src) {
1915   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1916          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1917          E->getCastKind() == CK_ReinterpretMemberPointer);
1918 
1919   // Use constant emission if we can.
1920   if (isa<llvm::Constant>(Src))
1921     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1922 
1923   // We may be adding or dropping fields from the member pointer, so we need
1924   // both types and the inheritance models of both records.
1925   const MemberPointerType *SrcTy =
1926     E->getSubExpr()->getType()->castAs<MemberPointerType>();
1927   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1928   bool IsFunc = SrcTy->isMemberFunctionPointer();
1929 
1930   // If the classes use the same null representation, reinterpret_cast is a nop.
1931   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1932   if (IsReinterpret && IsFunc)
1933     return Src;
1934 
1935   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
1936   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
1937   if (IsReinterpret &&
1938       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
1939     return Src;
1940 
1941   CGBuilderTy &Builder = CGF.Builder;
1942 
1943   // Branch past the conversion if Src is null.
1944   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1945   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1946 
1947   // C++ 5.2.10p9: The null member pointer value is converted to the null member
1948   //   pointer value of the destination type.
1949   if (IsReinterpret) {
1950     // For reinterpret casts, sema ensures that src and dst are both functions
1951     // or data and have the same size, which means the LLVM types should match.
1952     assert(Src->getType() == DstNull->getType());
1953     return Builder.CreateSelect(IsNotNull, Src, DstNull);
1954   }
1955 
1956   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1957   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1958   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1959   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1960   CGF.EmitBlock(ConvertBB);
1961 
1962   // Decompose src.
1963   llvm::Value *FirstField = Src;
1964   llvm::Value *NonVirtualBaseAdjustment = nullptr;
1965   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
1966   llvm::Value *VBPtrOffset = nullptr;
1967   MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
1968   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
1969     // We need to extract values.
1970     unsigned I = 0;
1971     FirstField = Builder.CreateExtractValue(Src, I++);
1972     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
1973       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1974     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
1975       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1976     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
1977       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1978   }
1979 
1980   // For data pointers, we adjust the field offset directly.  For functions, we
1981   // have a separate field.
1982   llvm::Constant *Adj = getMemberPointerAdjustment(E);
1983   if (Adj) {
1984     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1985     llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1986     bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1987     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1988       NVAdjustField = getZeroInt();
1989     if (isDerivedToBase)
1990       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1991     else
1992       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1993   }
1994 
1995   // FIXME PR15713: Support conversions through virtually derived classes.
1996 
1997   // Recompose dst from the null struct and the adjusted fields from src.
1998   MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
1999   llvm::Value *Dst;
2000   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2001     Dst = FirstField;
2002   } else {
2003     Dst = llvm::UndefValue::get(DstNull->getType());
2004     unsigned Idx = 0;
2005     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2006     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2007       Dst = Builder.CreateInsertValue(
2008         Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2009     if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2010       Dst = Builder.CreateInsertValue(
2011         Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2012     if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2013       Dst = Builder.CreateInsertValue(
2014         Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2015   }
2016   Builder.CreateBr(ContinueBB);
2017 
2018   // In the continuation, choose between DstNull and Dst.
2019   CGF.EmitBlock(ContinueBB);
2020   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2021   Phi->addIncoming(DstNull, OriginalBB);
2022   Phi->addIncoming(Dst, ConvertBB);
2023   return Phi;
2024 }
2025 
2026 llvm::Constant *
2027 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2028                                              llvm::Constant *Src) {
2029   const MemberPointerType *SrcTy =
2030     E->getSubExpr()->getType()->castAs<MemberPointerType>();
2031   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2032 
2033   // If src is null, emit a new null for dst.  We can't return src because dst
2034   // might have a new representation.
2035   if (MemberPointerConstantIsNull(SrcTy, Src))
2036     return EmitNullMemberPointer(DstTy);
2037 
2038   // We don't need to do anything for reinterpret_casts of non-null member
2039   // pointers.  We should only get here when the two type representations have
2040   // the same size.
2041   if (E->getCastKind() == CK_ReinterpretMemberPointer)
2042     return Src;
2043 
2044   MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2045   MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2046 
2047   // Decompose src.
2048   llvm::Constant *FirstField = Src;
2049   llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2050   llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2051   llvm::Constant *VBPtrOffset = nullptr;
2052   bool IsFunc = SrcTy->isMemberFunctionPointer();
2053   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2054     // We need to extract values.
2055     unsigned I = 0;
2056     FirstField = Src->getAggregateElement(I++);
2057     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2058       NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2059     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2060       VBPtrOffset = Src->getAggregateElement(I++);
2061     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2062       VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2063   }
2064 
2065   // For data pointers, we adjust the field offset directly.  For functions, we
2066   // have a separate field.
2067   llvm::Constant *Adj = getMemberPointerAdjustment(E);
2068   if (Adj) {
2069     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2070     llvm::Constant *&NVAdjustField =
2071       IsFunc ? NonVirtualBaseAdjustment : FirstField;
2072     bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2073     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
2074       NVAdjustField = getZeroInt();
2075     if (IsDerivedToBase)
2076       NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2077     else
2078       NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2079   }
2080 
2081   // FIXME PR15713: Support conversions through virtually derived classes.
2082 
2083   // Recompose dst from the null struct and the adjusted fields from src.
2084   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2085     return FirstField;
2086 
2087   llvm::SmallVector<llvm::Constant *, 4> Fields;
2088   Fields.push_back(FirstField);
2089   if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2090     Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2091   if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2092     Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2093   if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2094     Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2095   return llvm::ConstantStruct::getAnon(Fields);
2096 }
2097 
2098 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2099     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2100     llvm::Value *MemPtr, const MemberPointerType *MPT) {
2101   assert(MPT->isMemberFunctionPointer());
2102   const FunctionProtoType *FPT =
2103     MPT->getPointeeType()->castAs<FunctionProtoType>();
2104   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2105   llvm::FunctionType *FTy =
2106     CGM.getTypes().GetFunctionType(
2107       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2108   CGBuilderTy &Builder = CGF.Builder;
2109 
2110   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2111 
2112   // Extract the fields we need, regardless of model.  We'll apply them if we
2113   // have them.
2114   llvm::Value *FunctionPointer = MemPtr;
2115   llvm::Value *NonVirtualBaseAdjustment = nullptr;
2116   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2117   llvm::Value *VBPtrOffset = nullptr;
2118   if (MemPtr->getType()->isStructTy()) {
2119     // We need to extract values.
2120     unsigned I = 0;
2121     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2122     if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2123       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2124     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2125       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2126     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2127       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2128   }
2129 
2130   if (VirtualBaseAdjustmentOffset) {
2131     This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2132                              VBPtrOffset);
2133   }
2134 
2135   if (NonVirtualBaseAdjustment) {
2136     // Apply the adjustment and cast back to the original struct type.
2137     llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2138     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2139     This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2140   }
2141 
2142   return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2143 }
2144 
2145 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2146   return new MicrosoftCXXABI(CGM);
2147 }
2148