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     // visibility and dll storage class 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     GI->Guard->setDLLStorageClass(GV->getDLLStorageClass());
1435   } else {
1436     assert(GI->Guard->getLinkage() == GV->getLinkage() &&
1437            "static local from the same function had different linkage");
1438   }
1439 
1440   // Pseudo code for the test:
1441   // if (!(GuardVar & MyGuardBit)) {
1442   //   GuardVar |= MyGuardBit;
1443   //   ... initialize the object ...;
1444   // }
1445 
1446   // Test our bit from the guard variable.
1447   llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1U << BitIndex);
1448   llvm::LoadInst *LI = Builder.CreateLoad(GI->Guard);
1449   llvm::Value *IsInitialized =
1450       Builder.CreateICmpNE(Builder.CreateAnd(LI, Bit), Zero);
1451   llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
1452   llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
1453   Builder.CreateCondBr(IsInitialized, EndBlock, InitBlock);
1454 
1455   // Set our bit in the guard variable and emit the initializer and add a global
1456   // destructor if appropriate.
1457   CGF.EmitBlock(InitBlock);
1458   Builder.CreateStore(Builder.CreateOr(LI, Bit), GI->Guard);
1459   CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
1460   Builder.CreateBr(EndBlock);
1461 
1462   // Continue.
1463   CGF.EmitBlock(EndBlock);
1464 }
1465 
1466 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
1467   // Null-ness for function memptrs only depends on the first field, which is
1468   // the function pointer.  The rest don't matter, so we can zero initialize.
1469   if (MPT->isMemberFunctionPointer())
1470     return true;
1471 
1472   // The virtual base adjustment field is always -1 for null, so if we have one
1473   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
1474   // valid field offset.
1475   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1476   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1477   return (!MSInheritanceAttr::hasVBTableOffsetField(Inheritance) &&
1478           RD->nullFieldOffsetIsZero());
1479 }
1480 
1481 llvm::Type *
1482 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
1483   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1484   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1485   llvm::SmallVector<llvm::Type *, 4> fields;
1486   if (MPT->isMemberFunctionPointer())
1487     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
1488   else
1489     fields.push_back(CGM.IntTy);  // FieldOffset
1490 
1491   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1492                                           Inheritance))
1493     fields.push_back(CGM.IntTy);
1494   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1495     fields.push_back(CGM.IntTy);
1496   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1497     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
1498 
1499   if (fields.size() == 1)
1500     return fields[0];
1501   return llvm::StructType::get(CGM.getLLVMContext(), fields);
1502 }
1503 
1504 void MicrosoftCXXABI::
1505 GetNullMemberPointerFields(const MemberPointerType *MPT,
1506                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
1507   assert(fields.empty());
1508   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1509   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1510   if (MPT->isMemberFunctionPointer()) {
1511     // FunctionPointerOrVirtualThunk
1512     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1513   } else {
1514     if (RD->nullFieldOffsetIsZero())
1515       fields.push_back(getZeroInt());  // FieldOffset
1516     else
1517       fields.push_back(getAllOnesInt());  // FieldOffset
1518   }
1519 
1520   if (MSInheritanceAttr::hasNVOffsetField(MPT->isMemberFunctionPointer(),
1521                                           Inheritance))
1522     fields.push_back(getZeroInt());
1523   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1524     fields.push_back(getZeroInt());
1525   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1526     fields.push_back(getAllOnesInt());
1527 }
1528 
1529 llvm::Constant *
1530 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
1531   llvm::SmallVector<llvm::Constant *, 4> fields;
1532   GetNullMemberPointerFields(MPT, fields);
1533   if (fields.size() == 1)
1534     return fields[0];
1535   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
1536   assert(Res->getType() == ConvertMemberPointerType(MPT));
1537   return Res;
1538 }
1539 
1540 llvm::Constant *
1541 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
1542                                        bool IsMemberFunction,
1543                                        const CXXRecordDecl *RD,
1544                                        CharUnits NonVirtualBaseAdjustment)
1545 {
1546   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1547 
1548   // Single inheritance class member pointer are represented as scalars instead
1549   // of aggregates.
1550   if (MSInheritanceAttr::hasOnlyOneField(IsMemberFunction, Inheritance))
1551     return FirstField;
1552 
1553   llvm::SmallVector<llvm::Constant *, 4> fields;
1554   fields.push_back(FirstField);
1555 
1556   if (MSInheritanceAttr::hasNVOffsetField(IsMemberFunction, Inheritance))
1557     fields.push_back(llvm::ConstantInt::get(
1558       CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
1559 
1560   if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance)) {
1561     CharUnits Offs = CharUnits::Zero();
1562     if (RD->getNumVBases())
1563       Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1564     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
1565   }
1566 
1567   // The rest of the fields are adjusted by conversions to a more derived class.
1568   if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1569     fields.push_back(getZeroInt());
1570 
1571   return llvm::ConstantStruct::getAnon(fields);
1572 }
1573 
1574 llvm::Constant *
1575 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
1576                                        CharUnits offset) {
1577   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1578   llvm::Constant *FirstField =
1579     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
1580   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
1581                                CharUnits::Zero());
1582 }
1583 
1584 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
1585   return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
1586 }
1587 
1588 llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
1589                                                    QualType MPType) {
1590   const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
1591   const ValueDecl *MPD = MP.getMemberPointerDecl();
1592   if (!MPD)
1593     return EmitNullMemberPointer(MPT);
1594 
1595   CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
1596 
1597   // FIXME PR15713: Support virtual inheritance paths.
1598 
1599   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
1600     return BuildMemberPointer(MPT->getMostRecentCXXRecordDecl(), MD,
1601                               ThisAdjustment);
1602 
1603   CharUnits FieldOffset =
1604     getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
1605   return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
1606 }
1607 
1608 llvm::Constant *
1609 MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
1610                                     const CXXMethodDecl *MD,
1611                                     CharUnits NonVirtualBaseAdjustment) {
1612   assert(MD->isInstance() && "Member function must not be static!");
1613   MD = MD->getCanonicalDecl();
1614   RD = RD->getMostRecentDecl();
1615   CodeGenTypes &Types = CGM.getTypes();
1616 
1617   llvm::Constant *FirstField;
1618   if (!MD->isVirtual()) {
1619     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
1620     llvm::Type *Ty;
1621     // Check whether the function has a computable LLVM signature.
1622     if (Types.isFuncTypeConvertible(FPT)) {
1623       // The function has a computable LLVM signature; use the correct type.
1624       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
1625     } else {
1626       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
1627       // function type is incomplete.
1628       Ty = CGM.PtrDiffTy;
1629     }
1630     FirstField = CGM.GetAddrOfFunction(MD, Ty);
1631     FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
1632   } else {
1633     MicrosoftVTableContext::MethodVFTableLocation ML =
1634         CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
1635     if (MD->isVariadic()) {
1636       CGM.ErrorUnsupported(MD, "pointer to variadic virtual member function");
1637       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1638     } else if (!CGM.getTypes().isFuncTypeConvertible(
1639                     MD->getType()->castAs<FunctionType>())) {
1640       CGM.ErrorUnsupported(MD, "pointer to virtual member function with "
1641                                "incomplete return or parameter type");
1642       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1643     } else if (ML.VBase) {
1644       CGM.ErrorUnsupported(MD, "pointer to virtual member function overriding "
1645                                "member function in virtual base class");
1646       FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
1647     } else {
1648       llvm::Function *Thunk = EmitVirtualMemPtrThunk(MD, ML);
1649       FirstField = llvm::ConstantExpr::getBitCast(Thunk, CGM.VoidPtrTy);
1650       // Include the vfptr adjustment if the method is in a non-primary vftable.
1651       NonVirtualBaseAdjustment += ML.VFPtrOffset;
1652     }
1653   }
1654 
1655   // The rest of the fields are common with data member pointers.
1656   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
1657                                NonVirtualBaseAdjustment);
1658 }
1659 
1660 /// Member pointers are the same if they're either bitwise identical *or* both
1661 /// null.  Null-ness for function members is determined by the first field,
1662 /// while for data member pointers we must compare all fields.
1663 llvm::Value *
1664 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
1665                                              llvm::Value *L,
1666                                              llvm::Value *R,
1667                                              const MemberPointerType *MPT,
1668                                              bool Inequality) {
1669   CGBuilderTy &Builder = CGF.Builder;
1670 
1671   // Handle != comparisons by switching the sense of all boolean operations.
1672   llvm::ICmpInst::Predicate Eq;
1673   llvm::Instruction::BinaryOps And, Or;
1674   if (Inequality) {
1675     Eq = llvm::ICmpInst::ICMP_NE;
1676     And = llvm::Instruction::Or;
1677     Or = llvm::Instruction::And;
1678   } else {
1679     Eq = llvm::ICmpInst::ICMP_EQ;
1680     And = llvm::Instruction::And;
1681     Or = llvm::Instruction::Or;
1682   }
1683 
1684   // If this is a single field member pointer (single inheritance), this is a
1685   // single icmp.
1686   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1687   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1688   if (MSInheritanceAttr::hasOnlyOneField(MPT->isMemberFunctionPointer(),
1689                                          Inheritance))
1690     return Builder.CreateICmp(Eq, L, R);
1691 
1692   // Compare the first field.
1693   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
1694   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
1695   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
1696 
1697   // Compare everything other than the first field.
1698   llvm::Value *Res = nullptr;
1699   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
1700   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
1701     llvm::Value *LF = Builder.CreateExtractValue(L, I);
1702     llvm::Value *RF = Builder.CreateExtractValue(R, I);
1703     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
1704     if (Res)
1705       Res = Builder.CreateBinOp(And, Res, Cmp);
1706     else
1707       Res = Cmp;
1708   }
1709 
1710   // Check if the first field is 0 if this is a function pointer.
1711   if (MPT->isMemberFunctionPointer()) {
1712     // (l1 == r1 && ...) || l0 == 0
1713     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
1714     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
1715     Res = Builder.CreateBinOp(Or, Res, IsZero);
1716   }
1717 
1718   // Combine the comparison of the first field, which must always be true for
1719   // this comparison to succeeed.
1720   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
1721 }
1722 
1723 llvm::Value *
1724 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
1725                                             llvm::Value *MemPtr,
1726                                             const MemberPointerType *MPT) {
1727   CGBuilderTy &Builder = CGF.Builder;
1728   llvm::SmallVector<llvm::Constant *, 4> fields;
1729   // We only need one field for member functions.
1730   if (MPT->isMemberFunctionPointer())
1731     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
1732   else
1733     GetNullMemberPointerFields(MPT, fields);
1734   assert(!fields.empty());
1735   llvm::Value *FirstField = MemPtr;
1736   if (MemPtr->getType()->isStructTy())
1737     FirstField = Builder.CreateExtractValue(MemPtr, 0);
1738   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
1739 
1740   // For function member pointers, we only need to test the function pointer
1741   // field.  The other fields if any can be garbage.
1742   if (MPT->isMemberFunctionPointer())
1743     return Res;
1744 
1745   // Otherwise, emit a series of compares and combine the results.
1746   for (int I = 1, E = fields.size(); I < E; ++I) {
1747     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
1748     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
1749     Res = Builder.CreateOr(Res, Next, "memptr.tobool");
1750   }
1751   return Res;
1752 }
1753 
1754 bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
1755                                                   llvm::Constant *Val) {
1756   // Function pointers are null if the pointer in the first field is null.
1757   if (MPT->isMemberFunctionPointer()) {
1758     llvm::Constant *FirstField = Val->getType()->isStructTy() ?
1759       Val->getAggregateElement(0U) : Val;
1760     return FirstField->isNullValue();
1761   }
1762 
1763   // If it's not a function pointer and it's zero initializable, we can easily
1764   // check zero.
1765   if (isZeroInitializable(MPT) && Val->isNullValue())
1766     return true;
1767 
1768   // Otherwise, break down all the fields for comparison.  Hopefully these
1769   // little Constants are reused, while a big null struct might not be.
1770   llvm::SmallVector<llvm::Constant *, 4> Fields;
1771   GetNullMemberPointerFields(MPT, Fields);
1772   if (Fields.size() == 1) {
1773     assert(Val->getType()->isIntegerTy());
1774     return Val == Fields[0];
1775   }
1776 
1777   unsigned I, E;
1778   for (I = 0, E = Fields.size(); I != E; ++I) {
1779     if (Val->getAggregateElement(I) != Fields[I])
1780       break;
1781   }
1782   return I == E;
1783 }
1784 
1785 llvm::Value *
1786 MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
1787                                          llvm::Value *This,
1788                                          llvm::Value *VBPtrOffset,
1789                                          llvm::Value *VBTableOffset,
1790                                          llvm::Value **VBPtrOut) {
1791   CGBuilderTy &Builder = CGF.Builder;
1792   // Load the vbtable pointer from the vbptr in the instance.
1793   This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
1794   llvm::Value *VBPtr =
1795     Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
1796   if (VBPtrOut) *VBPtrOut = VBPtr;
1797   VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
1798   llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
1799 
1800   // Load an i32 offset from the vb-table.
1801   llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
1802   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
1803   return Builder.CreateLoad(VBaseOffs, "vbase_offs");
1804 }
1805 
1806 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
1807 // it.
1808 llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
1809     CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
1810     llvm::Value *Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
1811   CGBuilderTy &Builder = CGF.Builder;
1812   Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
1813   llvm::BasicBlock *OriginalBB = nullptr;
1814   llvm::BasicBlock *SkipAdjustBB = nullptr;
1815   llvm::BasicBlock *VBaseAdjustBB = nullptr;
1816 
1817   // In the unspecified inheritance model, there might not be a vbtable at all,
1818   // in which case we need to skip the virtual base lookup.  If there is a
1819   // vbtable, the first entry is a no-op entry that gives back the original
1820   // base, so look for a virtual base adjustment offset of zero.
1821   if (VBPtrOffset) {
1822     OriginalBB = Builder.GetInsertBlock();
1823     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1824     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1825     llvm::Value *IsVirtual =
1826       Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
1827                            "memptr.is_vbase");
1828     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1829     CGF.EmitBlock(VBaseAdjustBB);
1830   }
1831 
1832   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1833   // know the vbptr offset.
1834   if (!VBPtrOffset) {
1835     CharUnits offs = CharUnits::Zero();
1836     if (!RD->hasDefinition()) {
1837       DiagnosticsEngine &Diags = CGF.CGM.getDiags();
1838       unsigned DiagID = Diags.getCustomDiagID(
1839           DiagnosticsEngine::Error,
1840           "member pointer representation requires a "
1841           "complete class type for %0 to perform this expression");
1842       Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
1843     } else if (RD->getNumVBases())
1844       offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
1845     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1846   }
1847   llvm::Value *VBPtr = nullptr;
1848   llvm::Value *VBaseOffs =
1849     GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
1850   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1851 
1852   // Merge control flow with the case where we didn't have to adjust.
1853   if (VBaseAdjustBB) {
1854     Builder.CreateBr(SkipAdjustBB);
1855     CGF.EmitBlock(SkipAdjustBB);
1856     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1857     Phi->addIncoming(Base, OriginalBB);
1858     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1859     return Phi;
1860   }
1861   return AdjustedBase;
1862 }
1863 
1864 llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
1865     CodeGenFunction &CGF, const Expr *E, llvm::Value *Base, llvm::Value *MemPtr,
1866     const MemberPointerType *MPT) {
1867   assert(MPT->isMemberDataPointer());
1868   unsigned AS = Base->getType()->getPointerAddressSpace();
1869   llvm::Type *PType =
1870       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1871   CGBuilderTy &Builder = CGF.Builder;
1872   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1873   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
1874 
1875   // Extract the fields we need, regardless of model.  We'll apply them if we
1876   // have them.
1877   llvm::Value *FieldOffset = MemPtr;
1878   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
1879   llvm::Value *VBPtrOffset = nullptr;
1880   if (MemPtr->getType()->isStructTy()) {
1881     // We need to extract values.
1882     unsigned I = 0;
1883     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1884     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
1885       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1886     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
1887       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1888   }
1889 
1890   if (VirtualBaseAdjustmentOffset) {
1891     Base = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
1892                              VBPtrOffset);
1893   }
1894 
1895   // Cast to char*.
1896   Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
1897 
1898   // Apply the offset, which we assume is non-null.
1899   llvm::Value *Addr =
1900     Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
1901 
1902   // Cast the address to the appropriate pointer type, adopting the address
1903   // space of the base pointer.
1904   return Builder.CreateBitCast(Addr, PType);
1905 }
1906 
1907 static MSInheritanceAttr::Spelling
1908 getInheritanceFromMemptr(const MemberPointerType *MPT) {
1909   return MPT->getMostRecentCXXRecordDecl()->getMSInheritanceModel();
1910 }
1911 
1912 llvm::Value *
1913 MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1914                                              const CastExpr *E,
1915                                              llvm::Value *Src) {
1916   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1917          E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1918          E->getCastKind() == CK_ReinterpretMemberPointer);
1919 
1920   // Use constant emission if we can.
1921   if (isa<llvm::Constant>(Src))
1922     return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1923 
1924   // We may be adding or dropping fields from the member pointer, so we need
1925   // both types and the inheritance models of both records.
1926   const MemberPointerType *SrcTy =
1927     E->getSubExpr()->getType()->castAs<MemberPointerType>();
1928   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1929   bool IsFunc = SrcTy->isMemberFunctionPointer();
1930 
1931   // If the classes use the same null representation, reinterpret_cast is a nop.
1932   bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1933   if (IsReinterpret && IsFunc)
1934     return Src;
1935 
1936   CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
1937   CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
1938   if (IsReinterpret &&
1939       SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
1940     return Src;
1941 
1942   CGBuilderTy &Builder = CGF.Builder;
1943 
1944   // Branch past the conversion if Src is null.
1945   llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1946   llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1947 
1948   // C++ 5.2.10p9: The null member pointer value is converted to the null member
1949   //   pointer value of the destination type.
1950   if (IsReinterpret) {
1951     // For reinterpret casts, sema ensures that src and dst are both functions
1952     // or data and have the same size, which means the LLVM types should match.
1953     assert(Src->getType() == DstNull->getType());
1954     return Builder.CreateSelect(IsNotNull, Src, DstNull);
1955   }
1956 
1957   llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1958   llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1959   llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1960   Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1961   CGF.EmitBlock(ConvertBB);
1962 
1963   // Decompose src.
1964   llvm::Value *FirstField = Src;
1965   llvm::Value *NonVirtualBaseAdjustment = nullptr;
1966   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
1967   llvm::Value *VBPtrOffset = nullptr;
1968   MSInheritanceAttr::Spelling SrcInheritance = SrcRD->getMSInheritanceModel();
1969   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
1970     // We need to extract values.
1971     unsigned I = 0;
1972     FirstField = Builder.CreateExtractValue(Src, I++);
1973     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
1974       NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1975     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
1976       VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1977     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
1978       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1979   }
1980 
1981   // For data pointers, we adjust the field offset directly.  For functions, we
1982   // have a separate field.
1983   llvm::Constant *Adj = getMemberPointerAdjustment(E);
1984   if (Adj) {
1985     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1986     llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1987     bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1988     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1989       NVAdjustField = getZeroInt();
1990     if (isDerivedToBase)
1991       NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1992     else
1993       NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1994   }
1995 
1996   // FIXME PR15713: Support conversions through virtually derived classes.
1997 
1998   // Recompose dst from the null struct and the adjusted fields from src.
1999   MSInheritanceAttr::Spelling DstInheritance = DstRD->getMSInheritanceModel();
2000   llvm::Value *Dst;
2001   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance)) {
2002     Dst = FirstField;
2003   } else {
2004     Dst = llvm::UndefValue::get(DstNull->getType());
2005     unsigned Idx = 0;
2006     Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
2007     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2008       Dst = Builder.CreateInsertValue(
2009         Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
2010     if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2011       Dst = Builder.CreateInsertValue(
2012         Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
2013     if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2014       Dst = Builder.CreateInsertValue(
2015         Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
2016   }
2017   Builder.CreateBr(ContinueBB);
2018 
2019   // In the continuation, choose between DstNull and Dst.
2020   CGF.EmitBlock(ContinueBB);
2021   llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
2022   Phi->addIncoming(DstNull, OriginalBB);
2023   Phi->addIncoming(Dst, ConvertBB);
2024   return Phi;
2025 }
2026 
2027 llvm::Constant *
2028 MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
2029                                              llvm::Constant *Src) {
2030   const MemberPointerType *SrcTy =
2031     E->getSubExpr()->getType()->castAs<MemberPointerType>();
2032   const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
2033 
2034   // If src is null, emit a new null for dst.  We can't return src because dst
2035   // might have a new representation.
2036   if (MemberPointerConstantIsNull(SrcTy, Src))
2037     return EmitNullMemberPointer(DstTy);
2038 
2039   // We don't need to do anything for reinterpret_casts of non-null member
2040   // pointers.  We should only get here when the two type representations have
2041   // the same size.
2042   if (E->getCastKind() == CK_ReinterpretMemberPointer)
2043     return Src;
2044 
2045   MSInheritanceAttr::Spelling SrcInheritance = getInheritanceFromMemptr(SrcTy);
2046   MSInheritanceAttr::Spelling DstInheritance = getInheritanceFromMemptr(DstTy);
2047 
2048   // Decompose src.
2049   llvm::Constant *FirstField = Src;
2050   llvm::Constant *NonVirtualBaseAdjustment = nullptr;
2051   llvm::Constant *VirtualBaseAdjustmentOffset = nullptr;
2052   llvm::Constant *VBPtrOffset = nullptr;
2053   bool IsFunc = SrcTy->isMemberFunctionPointer();
2054   if (!MSInheritanceAttr::hasOnlyOneField(IsFunc, SrcInheritance)) {
2055     // We need to extract values.
2056     unsigned I = 0;
2057     FirstField = Src->getAggregateElement(I++);
2058     if (MSInheritanceAttr::hasNVOffsetField(IsFunc, SrcInheritance))
2059       NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
2060     if (MSInheritanceAttr::hasVBPtrOffsetField(SrcInheritance))
2061       VBPtrOffset = Src->getAggregateElement(I++);
2062     if (MSInheritanceAttr::hasVBTableOffsetField(SrcInheritance))
2063       VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
2064   }
2065 
2066   // For data pointers, we adjust the field offset directly.  For functions, we
2067   // have a separate field.
2068   llvm::Constant *Adj = getMemberPointerAdjustment(E);
2069   if (Adj) {
2070     Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
2071     llvm::Constant *&NVAdjustField =
2072       IsFunc ? NonVirtualBaseAdjustment : FirstField;
2073     bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
2074     if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
2075       NVAdjustField = getZeroInt();
2076     if (IsDerivedToBase)
2077       NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
2078     else
2079       NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
2080   }
2081 
2082   // FIXME PR15713: Support conversions through virtually derived classes.
2083 
2084   // Recompose dst from the null struct and the adjusted fields from src.
2085   if (MSInheritanceAttr::hasOnlyOneField(IsFunc, DstInheritance))
2086     return FirstField;
2087 
2088   llvm::SmallVector<llvm::Constant *, 4> Fields;
2089   Fields.push_back(FirstField);
2090   if (MSInheritanceAttr::hasNVOffsetField(IsFunc, DstInheritance))
2091     Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
2092   if (MSInheritanceAttr::hasVBPtrOffsetField(DstInheritance))
2093     Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
2094   if (MSInheritanceAttr::hasVBTableOffsetField(DstInheritance))
2095     Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
2096   return llvm::ConstantStruct::getAnon(Fields);
2097 }
2098 
2099 llvm::Value *MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
2100     CodeGenFunction &CGF, const Expr *E, llvm::Value *&This,
2101     llvm::Value *MemPtr, const MemberPointerType *MPT) {
2102   assert(MPT->isMemberFunctionPointer());
2103   const FunctionProtoType *FPT =
2104     MPT->getPointeeType()->castAs<FunctionProtoType>();
2105   const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
2106   llvm::FunctionType *FTy =
2107     CGM.getTypes().GetFunctionType(
2108       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
2109   CGBuilderTy &Builder = CGF.Builder;
2110 
2111   MSInheritanceAttr::Spelling Inheritance = RD->getMSInheritanceModel();
2112 
2113   // Extract the fields we need, regardless of model.  We'll apply them if we
2114   // have them.
2115   llvm::Value *FunctionPointer = MemPtr;
2116   llvm::Value *NonVirtualBaseAdjustment = nullptr;
2117   llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
2118   llvm::Value *VBPtrOffset = nullptr;
2119   if (MemPtr->getType()->isStructTy()) {
2120     // We need to extract values.
2121     unsigned I = 0;
2122     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
2123     if (MSInheritanceAttr::hasNVOffsetField(MPT, Inheritance))
2124       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
2125     if (MSInheritanceAttr::hasVBPtrOffsetField(Inheritance))
2126       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
2127     if (MSInheritanceAttr::hasVBTableOffsetField(Inheritance))
2128       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
2129   }
2130 
2131   if (VirtualBaseAdjustmentOffset) {
2132     This = AdjustVirtualBase(CGF, E, RD, This, VirtualBaseAdjustmentOffset,
2133                              VBPtrOffset);
2134   }
2135 
2136   if (NonVirtualBaseAdjustment) {
2137     // Apply the adjustment and cast back to the original struct type.
2138     llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
2139     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
2140     This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
2141   }
2142 
2143   return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
2144 }
2145 
2146 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
2147   return new MicrosoftCXXABI(CGM);
2148 }
2149