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 "CodeGenModule.h"
19#include "CGVTables.h"
20#include "MicrosoftVBTables.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/VTableBuilder.h"
24
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29
30class MicrosoftCXXABI : public CGCXXABI {
31public:
32  MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
33
34  bool HasThisReturn(GlobalDecl GD) const;
35
36  bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
37    // Structures that are not C++03 PODs are always indirect.
38    return !RD->isPOD();
39  }
40
41  RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
42    if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialDestructor())
43      return RAA_DirectInMemory;
44    return RAA_Default;
45  }
46
47  StringRef GetPureVirtualCallName() { return "_purecall"; }
48  // No known support for deleted functions in MSVC yet, so this choice is
49  // arbitrary.
50  StringRef GetDeletedVirtualCallName() { return "_purecall"; }
51
52  llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
53                                      llvm::Value *ptr,
54                                      QualType type);
55
56  llvm::Value *GetVirtualBaseClassOffset(CodeGenFunction &CGF,
57                                         llvm::Value *This,
58                                         const CXXRecordDecl *ClassDecl,
59                                         const CXXRecordDecl *BaseClassDecl);
60
61  void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
62                                 CXXCtorType Type,
63                                 CanQualType &ResTy,
64                                 SmallVectorImpl<CanQualType> &ArgTys);
65
66  llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
67                                                  const CXXRecordDecl *RD);
68
69  void EmitCXXConstructors(const CXXConstructorDecl *D);
70
71  // Background on MSVC destructors
72  // ==============================
73  //
74  // Both Itanium and MSVC ABIs have destructor variants.  The variant names
75  // roughly correspond in the following way:
76  //   Itanium       Microsoft
77  //   Base       -> no name, just ~Class
78  //   Complete   -> vbase destructor
79  //   Deleting   -> scalar deleting destructor
80  //                 vector deleting destructor
81  //
82  // The base and complete destructors are the same as in Itanium, although the
83  // complete destructor does not accept a VTT parameter when there are virtual
84  // bases.  A separate mechanism involving vtordisps is used to ensure that
85  // virtual methods of destroyed subobjects are not called.
86  //
87  // The deleting destructors accept an i32 bitfield as a second parameter.  Bit
88  // 1 indicates if the memory should be deleted.  Bit 2 indicates if the this
89  // pointer points to an array.  The scalar deleting destructor assumes that
90  // bit 2 is zero, and therefore does not contain a loop.
91  //
92  // For virtual destructors, only one entry is reserved in the vftable, and it
93  // always points to the vector deleting destructor.  The vector deleting
94  // destructor is the most general, so it can be used to destroy objects in
95  // place, delete single heap objects, or delete arrays.
96  //
97  // A TU defining a non-inline destructor is only guaranteed to emit a base
98  // destructor, and all of the other variants are emitted on an as-needed basis
99  // in COMDATs.  Because a non-base destructor can be emitted in a TU that
100  // lacks a definition for the destructor, non-base destructors must always
101  // delegate to or alias the base destructor.
102
103  void BuildDestructorSignature(const CXXDestructorDecl *Dtor,
104                                CXXDtorType Type,
105                                CanQualType &ResTy,
106                                SmallVectorImpl<CanQualType> &ArgTys);
107
108  /// Non-base dtors should be emitted as delegating thunks in this ABI.
109  bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
110                              CXXDtorType DT) const {
111    return DT != Dtor_Base;
112  }
113
114  void EmitCXXDestructors(const CXXDestructorDecl *D);
115
116  void BuildInstanceFunctionParams(CodeGenFunction &CGF,
117                                   QualType &ResTy,
118                                   FunctionArgList &Params);
119
120  void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
121
122  void EmitConstructorCall(CodeGenFunction &CGF,
123                           const CXXConstructorDecl *D, CXXCtorType Type,
124                           bool ForVirtualBase, bool Delegating,
125                           llvm::Value *This,
126                           CallExpr::const_arg_iterator ArgBeg,
127                           CallExpr::const_arg_iterator ArgEnd);
128
129  void EmitVirtualDestructorCall(CodeGenFunction &CGF,
130                                 const CXXDestructorDecl *Dtor,
131                                 CXXDtorType DtorType, SourceLocation CallLoc,
132                                 llvm::Value *This);
133
134  void EmitVirtualInheritanceTables(llvm::GlobalVariable::LinkageTypes Linkage,
135                                    const CXXRecordDecl *RD);
136
137  void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
138                       llvm::GlobalVariable *DeclPtr,
139                       bool PerformInit);
140
141  // ==== Notes on array cookies =========
142  //
143  // MSVC seems to only use cookies when the class has a destructor; a
144  // two-argument usual array deallocation function isn't sufficient.
145  //
146  // For example, this code prints "100" and "1":
147  //   struct A {
148  //     char x;
149  //     void *operator new[](size_t sz) {
150  //       printf("%u\n", sz);
151  //       return malloc(sz);
152  //     }
153  //     void operator delete[](void *p, size_t sz) {
154  //       printf("%u\n", sz);
155  //       free(p);
156  //     }
157  //   };
158  //   int main() {
159  //     A *p = new A[100];
160  //     delete[] p;
161  //   }
162  // Whereas it prints "104" and "104" if you give A a destructor.
163
164  bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
165  bool requiresArrayCookie(const CXXNewExpr *expr);
166  CharUnits getArrayCookieSizeImpl(QualType type);
167  llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
168                                     llvm::Value *NewPtr,
169                                     llvm::Value *NumElements,
170                                     const CXXNewExpr *expr,
171                                     QualType ElementType);
172  llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
173                                   llvm::Value *allocPtr,
174                                   CharUnits cookieSize);
175
176private:
177  llvm::Constant *getZeroInt() {
178    return llvm::ConstantInt::get(CGM.IntTy, 0);
179  }
180
181  llvm::Constant *getAllOnesInt() {
182    return  llvm::Constant::getAllOnesValue(CGM.IntTy);
183  }
184
185  llvm::Constant *getConstantOrZeroInt(llvm::Constant *C) {
186    return C ? C : getZeroInt();
187  }
188
189  llvm::Value *getValueOrZeroInt(llvm::Value *C) {
190    return C ? C : getZeroInt();
191  }
192
193  void
194  GetNullMemberPointerFields(const MemberPointerType *MPT,
195                             llvm::SmallVectorImpl<llvm::Constant *> &fields);
196
197  /// \brief Finds the offset from the base of RD to the vbptr it uses, even if
198  /// it is reusing a vbptr from a non-virtual base.  RD must have morally
199  /// virtual bases.
200  CharUnits GetVBPtrOffsetFromBases(const CXXRecordDecl *RD);
201
202  /// \brief Shared code for virtual base adjustment.  Returns the offset from
203  /// the vbptr to the virtual base.  Optionally returns the address of the
204  /// vbptr itself.
205  llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
206                                       llvm::Value *Base,
207                                       llvm::Value *VBPtrOffset,
208                                       llvm::Value *VBTableOffset,
209                                       llvm::Value **VBPtr = 0);
210
211  /// \brief Performs a full virtual base adjustment.  Used to dereference
212  /// pointers to members of virtual bases.
213  llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
214                                 llvm::Value *Base,
215                                 llvm::Value *VirtualBaseAdjustmentOffset,
216                                 llvm::Value *VBPtrOffset /* optional */);
217
218  /// \brief Emits a full member pointer with the fields common to data and
219  /// function member pointers.
220  llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
221                                        bool IsMemberFunction,
222                                        const CXXRecordDecl *RD,
223                                        CharUnits NonVirtualBaseAdjustment);
224
225  llvm::Constant *BuildMemberPointer(const CXXRecordDecl *RD,
226                                     const CXXMethodDecl *MD,
227                                     CharUnits NonVirtualBaseAdjustment);
228
229  bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
230                                   llvm::Constant *MP);
231
232  /// \brief - Initialize all vbptrs of 'this' with RD as the complete type.
233  void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
234
235  /// \brief Caching wrapper around VBTableBuilder::enumerateVBTables().
236  const VBTableVector &EnumerateVBTables(const CXXRecordDecl *RD);
237
238public:
239  virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
240
241  virtual bool isZeroInitializable(const MemberPointerType *MPT);
242
243  virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
244
245  virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
246                                                CharUnits offset);
247  virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
248  virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
249
250  virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
251                                                   llvm::Value *L,
252                                                   llvm::Value *R,
253                                                   const MemberPointerType *MPT,
254                                                   bool Inequality);
255
256  virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
257                                                  llvm::Value *MemPtr,
258                                                  const MemberPointerType *MPT);
259
260  virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
261                                                    llvm::Value *Base,
262                                                    llvm::Value *MemPtr,
263                                                  const MemberPointerType *MPT);
264
265  virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
266                                                   const CastExpr *E,
267                                                   llvm::Value *Src);
268
269  virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
270                                                      llvm::Constant *Src);
271
272  virtual llvm::Value *
273  EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
274                                  llvm::Value *&This,
275                                  llvm::Value *MemPtr,
276                                  const MemberPointerType *MPT);
277
278private:
279  /// VBTables - All the vbtables which have been referenced.
280  llvm::DenseMap<const CXXRecordDecl *, VBTableVector> VBTablesMap;
281};
282
283}
284
285llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
286                                                     llvm::Value *ptr,
287                                                     QualType type) {
288  // FIXME: implement
289  return ptr;
290}
291
292/// \brief Finds the first non-virtual base of RD that has virtual bases.  If RD
293/// doesn't have a vbptr, it will reuse the vbptr of the returned class.
294static const CXXRecordDecl *FindFirstNVBaseWithVBases(const CXXRecordDecl *RD) {
295  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
296       E = RD->bases_end(); I != E; ++I) {
297    const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
298    if (!I->isVirtual() && Base->getNumVBases() > 0)
299      return Base;
300  }
301  llvm_unreachable("RD must have an nv base with vbases");
302}
303
304CharUnits MicrosoftCXXABI::GetVBPtrOffsetFromBases(const CXXRecordDecl *RD) {
305  assert(RD->getNumVBases());
306  CharUnits Total = CharUnits::Zero();
307  while (RD) {
308    const ASTRecordLayout &RDLayout = getContext().getASTRecordLayout(RD);
309    CharUnits VBPtrOffset = RDLayout.getVBPtrOffset();
310    // -1 is the sentinel for no vbptr.
311    if (VBPtrOffset != CharUnits::fromQuantity(-1)) {
312      Total += VBPtrOffset;
313      break;
314    }
315    RD = FindFirstNVBaseWithVBases(RD);
316    Total += RDLayout.getBaseClassOffset(RD);
317  }
318  return Total;
319}
320
321llvm::Value *
322MicrosoftCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
323                                           llvm::Value *This,
324                                           const CXXRecordDecl *ClassDecl,
325                                           const CXXRecordDecl *BaseClassDecl) {
326  int64_t VBPtrChars = GetVBPtrOffsetFromBases(ClassDecl).getQuantity();
327  llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
328  CharUnits IntSize = getContext().getTypeSizeInChars(getContext().IntTy);
329  CharUnits VBTableChars = IntSize * GetVBTableIndex(ClassDecl, BaseClassDecl);
330  llvm::Value *VBTableOffset =
331    llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
332
333  llvm::Value *VBPtrToNewBase =
334    GetVBaseOffsetFromVBPtr(CGF, This, VBTableOffset, VBPtrOffset);
335  VBPtrToNewBase =
336    CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
337  return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
338}
339
340bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
341  return isa<CXXConstructorDecl>(GD.getDecl());
342}
343
344void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
345                                 CXXCtorType Type,
346                                 CanQualType &ResTy,
347                                 SmallVectorImpl<CanQualType> &ArgTys) {
348  // 'this' parameter and 'this' return are already in place
349
350  const CXXRecordDecl *Class = Ctor->getParent();
351  if (Class->getNumVBases()) {
352    // Constructors of classes with virtual bases take an implicit parameter.
353    ArgTys.push_back(CGM.getContext().IntTy);
354  }
355}
356
357llvm::BasicBlock *
358MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
359                                               const CXXRecordDecl *RD) {
360  llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
361  assert(IsMostDerivedClass &&
362         "ctor for a class with virtual bases must have an implicit parameter");
363  llvm::Value *IsCompleteObject =
364    CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
365
366  llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
367  llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
368  CGF.Builder.CreateCondBr(IsCompleteObject,
369                           CallVbaseCtorsBB, SkipVbaseCtorsBB);
370
371  CGF.EmitBlock(CallVbaseCtorsBB);
372
373  // Fill in the vbtable pointers here.
374  EmitVBPtrStores(CGF, RD);
375
376  // CGF will put the base ctor calls in this basic block for us later.
377
378  return SkipVbaseCtorsBB;
379}
380
381void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
382  // There's only one constructor type in this ABI.
383  CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
384}
385
386void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
387                                      const CXXRecordDecl *RD) {
388  llvm::Value *ThisInt8Ptr =
389    CGF.Builder.CreateBitCast(getThisValue(CGF), CGM.Int8PtrTy, "this.int8");
390
391  const VBTableVector &VBTables = EnumerateVBTables(RD);
392  for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
393       I != E; ++I) {
394    const ASTRecordLayout &SubobjectLayout =
395      CGM.getContext().getASTRecordLayout(I->VBPtrSubobject.getBase());
396    uint64_t Offs = (I->VBPtrSubobject.getBaseOffset() +
397                     SubobjectLayout.getVBPtrOffset()).getQuantity();
398    llvm::Value *VBPtr =
399        CGF.Builder.CreateConstInBoundsGEP1_64(ThisInt8Ptr, Offs);
400    VBPtr = CGF.Builder.CreateBitCast(VBPtr, I->GV->getType()->getPointerTo(0),
401                                      "vbptr." + I->ReusingBase->getName());
402    CGF.Builder.CreateStore(I->GV, VBPtr);
403  }
404}
405
406void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
407                                               CXXDtorType Type,
408                                               CanQualType &ResTy,
409                                        SmallVectorImpl<CanQualType> &ArgTys) {
410  // 'this' is already in place
411
412  // TODO: 'for base' flag
413
414  if (Type == Dtor_Deleting) {
415    // The scalar deleting destructor takes an implicit bool parameter.
416    ArgTys.push_back(CGM.getContext().BoolTy);
417  }
418}
419
420void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
421  // The TU defining a dtor is only guaranteed to emit a base destructor.  All
422  // other destructor variants are delegating thunks.
423  CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
424}
425
426static bool IsDeletingDtor(GlobalDecl GD) {
427  const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
428  if (isa<CXXDestructorDecl>(MD)) {
429    return GD.getDtorType() == Dtor_Deleting;
430  }
431  return false;
432}
433
434void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
435                                                  QualType &ResTy,
436                                                  FunctionArgList &Params) {
437  BuildThisParam(CGF, Params);
438
439  ASTContext &Context = getContext();
440  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
441  if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
442    ImplicitParamDecl *IsMostDerived
443      = ImplicitParamDecl::Create(Context, 0,
444                                  CGF.CurGD.getDecl()->getLocation(),
445                                  &Context.Idents.get("is_most_derived"),
446                                  Context.IntTy);
447    Params.push_back(IsMostDerived);
448    getStructorImplicitParamDecl(CGF) = IsMostDerived;
449  } else if (IsDeletingDtor(CGF.CurGD)) {
450    ImplicitParamDecl *ShouldDelete
451      = ImplicitParamDecl::Create(Context, 0,
452                                  CGF.CurGD.getDecl()->getLocation(),
453                                  &Context.Idents.get("should_call_delete"),
454                                  Context.BoolTy);
455    Params.push_back(ShouldDelete);
456    getStructorImplicitParamDecl(CGF) = ShouldDelete;
457  }
458}
459
460void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
461  EmitThisParam(CGF);
462
463  /// If this is a function that the ABI specifies returns 'this', initialize
464  /// the return slot to 'this' at the start of the function.
465  ///
466  /// Unlike the setting of return types, this is done within the ABI
467  /// implementation instead of by clients of CGCXXABI because:
468  /// 1) getThisValue is currently protected
469  /// 2) in theory, an ABI could implement 'this' returns some other way;
470  ///    HasThisReturn only specifies a contract, not the implementation
471  if (HasThisReturn(CGF.CurGD))
472    CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
473
474  const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
475  if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
476    assert(getStructorImplicitParamDecl(CGF) &&
477           "no implicit parameter for a constructor with virtual bases?");
478    getStructorImplicitParamValue(CGF)
479      = CGF.Builder.CreateLoad(
480          CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
481          "is_most_derived");
482  }
483
484  if (IsDeletingDtor(CGF.CurGD)) {
485    assert(getStructorImplicitParamDecl(CGF) &&
486           "no implicit parameter for a deleting destructor?");
487    getStructorImplicitParamValue(CGF)
488      = CGF.Builder.CreateLoad(
489          CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
490          "should_call_delete");
491  }
492}
493
494void MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
495                                          const CXXConstructorDecl *D,
496                                          CXXCtorType Type,
497                                          bool ForVirtualBase,
498                                          bool Delegating,
499                                          llvm::Value *This,
500                                          CallExpr::const_arg_iterator ArgBeg,
501                                          CallExpr::const_arg_iterator ArgEnd) {
502  assert(Type == Ctor_Complete || Type == Ctor_Base);
503  llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
504
505  llvm::Value *ImplicitParam = 0;
506  QualType ImplicitParamTy;
507  if (D->getParent()->getNumVBases()) {
508    ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
509    ImplicitParamTy = getContext().IntTy;
510  }
511
512  // FIXME: Provide a source location here.
513  CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
514                        ImplicitParam, ImplicitParamTy, ArgBeg, ArgEnd);
515}
516
517void MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
518                                                const CXXDestructorDecl *Dtor,
519                                                CXXDtorType DtorType,
520                                                SourceLocation CallLoc,
521                                                llvm::Value *This) {
522  assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
523
524  // We have only one destructor in the vftable but can get both behaviors
525  // by passing an implicit bool parameter.
526  const CGFunctionInfo *FInfo
527      = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
528  llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
529  llvm::Value *Callee
530      = CGF.BuildVirtualCall(GlobalDecl(Dtor, Dtor_Deleting), This, Ty);
531
532  ASTContext &Context = CGF.getContext();
533  llvm::Value *ImplicitParam
534    = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()),
535                             DtorType == Dtor_Deleting);
536
537  CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValueSlot(), This,
538                        ImplicitParam, Context.BoolTy, 0, 0);
539}
540
541const VBTableVector &
542MicrosoftCXXABI::EnumerateVBTables(const CXXRecordDecl *RD) {
543  // At this layer, we can key the cache off of a single class, which is much
544  // easier than caching at the GlobalVariable layer.
545  llvm::DenseMap<const CXXRecordDecl*, VBTableVector>::iterator I;
546  bool added;
547  llvm::tie(I, added) = VBTablesMap.insert(std::make_pair(RD, VBTableVector()));
548  VBTableVector &VBTables = I->second;
549  if (!added)
550    return VBTables;
551
552  VBTableBuilder(CGM, RD).enumerateVBTables(VBTables);
553
554  return VBTables;
555}
556
557void MicrosoftCXXABI::EmitVirtualInheritanceTables(
558    llvm::GlobalVariable::LinkageTypes Linkage, const CXXRecordDecl *RD) {
559  const VBTableVector &VBTables = EnumerateVBTables(RD);
560  for (VBTableVector::const_iterator I = VBTables.begin(), E = VBTables.end();
561       I != E; ++I) {
562    I->EmitVBTableDefinition(CGM, RD, Linkage);
563  }
564}
565
566bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
567                                   QualType elementType) {
568  // Microsoft seems to completely ignore the possibility of a
569  // two-argument usual deallocation function.
570  return elementType.isDestructedType();
571}
572
573bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
574  // Microsoft seems to completely ignore the possibility of a
575  // two-argument usual deallocation function.
576  return expr->getAllocatedType().isDestructedType();
577}
578
579CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
580  // The array cookie is always a size_t; we then pad that out to the
581  // alignment of the element type.
582  ASTContext &Ctx = getContext();
583  return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
584                  Ctx.getTypeAlignInChars(type));
585}
586
587llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
588                                                  llvm::Value *allocPtr,
589                                                  CharUnits cookieSize) {
590  unsigned AS = allocPtr->getType()->getPointerAddressSpace();
591  llvm::Value *numElementsPtr =
592    CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
593  return CGF.Builder.CreateLoad(numElementsPtr);
594}
595
596llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
597                                                    llvm::Value *newPtr,
598                                                    llvm::Value *numElements,
599                                                    const CXXNewExpr *expr,
600                                                    QualType elementType) {
601  assert(requiresArrayCookie(expr));
602
603  // The size of the cookie.
604  CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
605
606  // Compute an offset to the cookie.
607  llvm::Value *cookiePtr = newPtr;
608
609  // Write the number of elements into the appropriate slot.
610  unsigned AS = newPtr->getType()->getPointerAddressSpace();
611  llvm::Value *numElementsPtr
612    = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
613  CGF.Builder.CreateStore(numElements, numElementsPtr);
614
615  // Finally, compute a pointer to the actual data buffer by skipping
616  // over the cookie completely.
617  return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
618                                                cookieSize.getQuantity());
619}
620
621void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
622                                      llvm::GlobalVariable *DeclPtr,
623                                      bool PerformInit) {
624  // FIXME: this code was only tested for global initialization.
625  // Not sure whether we want thread-safe static local variables as VS
626  // doesn't make them thread-safe.
627
628  if (D.getTLSKind())
629    CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
630
631  // Emit the initializer and add a global destructor if appropriate.
632  CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
633}
634
635// Member pointer helpers.
636static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
637  return Inheritance == MSIM_Unspecified;
638}
639
640static bool hasOnlyOneField(bool IsMemberFunction,
641                            MSInheritanceModel Inheritance) {
642  return Inheritance <= MSIM_SinglePolymorphic ||
643      (!IsMemberFunction && Inheritance <= MSIM_MultiplePolymorphic);
644}
645
646// Only member pointers to functions need a this adjustment, since it can be
647// combined with the field offset for data pointers.
648static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
649                                             MSInheritanceModel Inheritance) {
650  return (IsMemberFunction && Inheritance >= MSIM_Multiple);
651}
652
653static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
654  return Inheritance >= MSIM_Virtual;
655}
656
657// Use zero for the field offset of a null data member pointer if we can
658// guarantee that zero is not a valid field offset, or if the member pointer has
659// multiple fields.  Polymorphic classes have a vfptr at offset zero, so we can
660// use zero for null.  If there are multiple fields, we can use zero even if it
661// is a valid field offset because null-ness testing will check the other
662// fields.
663static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
664  return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
665}
666
667bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
668  // Null-ness for function memptrs only depends on the first field, which is
669  // the function pointer.  The rest don't matter, so we can zero initialize.
670  if (MPT->isMemberFunctionPointer())
671    return true;
672
673  // The virtual base adjustment field is always -1 for null, so if we have one
674  // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
675  // valid field offset.
676  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
677  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
678  return (!hasVirtualBaseAdjustmentField(Inheritance) &&
679          nullFieldOffsetIsZero(Inheritance));
680}
681
682llvm::Type *
683MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
684  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
685  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
686  llvm::SmallVector<llvm::Type *, 4> fields;
687  if (MPT->isMemberFunctionPointer())
688    fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
689  else
690    fields.push_back(CGM.IntTy);  // FieldOffset
691
692  if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
693                                       Inheritance))
694    fields.push_back(CGM.IntTy);
695  if (hasVBPtrOffsetField(Inheritance))
696    fields.push_back(CGM.IntTy);
697  if (hasVirtualBaseAdjustmentField(Inheritance))
698    fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
699
700  if (fields.size() == 1)
701    return fields[0];
702  return llvm::StructType::get(CGM.getLLVMContext(), fields);
703}
704
705void MicrosoftCXXABI::
706GetNullMemberPointerFields(const MemberPointerType *MPT,
707                           llvm::SmallVectorImpl<llvm::Constant *> &fields) {
708  assert(fields.empty());
709  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
710  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
711  if (MPT->isMemberFunctionPointer()) {
712    // FunctionPointerOrVirtualThunk
713    fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
714  } else {
715    if (nullFieldOffsetIsZero(Inheritance))
716      fields.push_back(getZeroInt());  // FieldOffset
717    else
718      fields.push_back(getAllOnesInt());  // FieldOffset
719  }
720
721  if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
722                                       Inheritance))
723    fields.push_back(getZeroInt());
724  if (hasVBPtrOffsetField(Inheritance))
725    fields.push_back(getZeroInt());
726  if (hasVirtualBaseAdjustmentField(Inheritance))
727    fields.push_back(getAllOnesInt());
728}
729
730llvm::Constant *
731MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
732  llvm::SmallVector<llvm::Constant *, 4> fields;
733  GetNullMemberPointerFields(MPT, fields);
734  if (fields.size() == 1)
735    return fields[0];
736  llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
737  assert(Res->getType() == ConvertMemberPointerType(MPT));
738  return Res;
739}
740
741llvm::Constant *
742MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
743                                       bool IsMemberFunction,
744                                       const CXXRecordDecl *RD,
745                                       CharUnits NonVirtualBaseAdjustment)
746{
747  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
748
749  // Single inheritance class member pointer are represented as scalars instead
750  // of aggregates.
751  if (hasOnlyOneField(IsMemberFunction, Inheritance))
752    return FirstField;
753
754  llvm::SmallVector<llvm::Constant *, 4> fields;
755  fields.push_back(FirstField);
756
757  if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
758    fields.push_back(llvm::ConstantInt::get(
759      CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
760
761  if (hasVBPtrOffsetField(Inheritance)) {
762    fields.push_back(llvm::ConstantInt::get(
763      CGM.IntTy, GetVBPtrOffsetFromBases(RD).getQuantity()));
764  }
765
766  // The rest of the fields are adjusted by conversions to a more derived class.
767  if (hasVirtualBaseAdjustmentField(Inheritance))
768    fields.push_back(getZeroInt());
769
770  return llvm::ConstantStruct::getAnon(fields);
771}
772
773llvm::Constant *
774MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
775                                       CharUnits offset) {
776  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
777  llvm::Constant *FirstField =
778    llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
779  return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD,
780                               CharUnits::Zero());
781}
782
783llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
784  return BuildMemberPointer(MD->getParent(), MD, CharUnits::Zero());
785}
786
787llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
788                                                   QualType MPType) {
789  const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
790  const ValueDecl *MPD = MP.getMemberPointerDecl();
791  if (!MPD)
792    return EmitNullMemberPointer(MPT);
793
794  CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
795
796  // FIXME PR15713: Support virtual inheritance paths.
797
798  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
799    return BuildMemberPointer(MPT->getClass()->getAsCXXRecordDecl(),
800                              MD, ThisAdjustment);
801
802  CharUnits FieldOffset =
803    getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
804  return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
805}
806
807llvm::Constant *
808MicrosoftCXXABI::BuildMemberPointer(const CXXRecordDecl *RD,
809                                    const CXXMethodDecl *MD,
810                                    CharUnits NonVirtualBaseAdjustment) {
811  assert(MD->isInstance() && "Member function must not be static!");
812  MD = MD->getCanonicalDecl();
813  CodeGenTypes &Types = CGM.getTypes();
814
815  llvm::Constant *FirstField;
816  if (MD->isVirtual()) {
817    // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
818    // the right offset.
819    FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
820  } else {
821    const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
822    llvm::Type *Ty;
823    // Check whether the function has a computable LLVM signature.
824    if (Types.isFuncTypeConvertible(FPT)) {
825      // The function has a computable LLVM signature; use the correct type.
826      Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
827    } else {
828      // Use an arbitrary non-function type to tell GetAddrOfFunction that the
829      // function type is incomplete.
830      Ty = CGM.PtrDiffTy;
831    }
832    FirstField = CGM.GetAddrOfFunction(MD, Ty);
833    FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
834  }
835
836  // The rest of the fields are common with data member pointers.
837  return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD,
838                               NonVirtualBaseAdjustment);
839}
840
841/// Member pointers are the same if they're either bitwise identical *or* both
842/// null.  Null-ness for function members is determined by the first field,
843/// while for data member pointers we must compare all fields.
844llvm::Value *
845MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
846                                             llvm::Value *L,
847                                             llvm::Value *R,
848                                             const MemberPointerType *MPT,
849                                             bool Inequality) {
850  CGBuilderTy &Builder = CGF.Builder;
851
852  // Handle != comparisons by switching the sense of all boolean operations.
853  llvm::ICmpInst::Predicate Eq;
854  llvm::Instruction::BinaryOps And, Or;
855  if (Inequality) {
856    Eq = llvm::ICmpInst::ICMP_NE;
857    And = llvm::Instruction::Or;
858    Or = llvm::Instruction::And;
859  } else {
860    Eq = llvm::ICmpInst::ICMP_EQ;
861    And = llvm::Instruction::And;
862    Or = llvm::Instruction::Or;
863  }
864
865  // If this is a single field member pointer (single inheritance), this is a
866  // single icmp.
867  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
868  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
869  if (hasOnlyOneField(MPT->isMemberFunctionPointer(), Inheritance))
870    return Builder.CreateICmp(Eq, L, R);
871
872  // Compare the first field.
873  llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
874  llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
875  llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
876
877  // Compare everything other than the first field.
878  llvm::Value *Res = 0;
879  llvm::StructType *LType = cast<llvm::StructType>(L->getType());
880  for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
881    llvm::Value *LF = Builder.CreateExtractValue(L, I);
882    llvm::Value *RF = Builder.CreateExtractValue(R, I);
883    llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
884    if (Res)
885      Res = Builder.CreateBinOp(And, Res, Cmp);
886    else
887      Res = Cmp;
888  }
889
890  // Check if the first field is 0 if this is a function pointer.
891  if (MPT->isMemberFunctionPointer()) {
892    // (l1 == r1 && ...) || l0 == 0
893    llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
894    llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
895    Res = Builder.CreateBinOp(Or, Res, IsZero);
896  }
897
898  // Combine the comparison of the first field, which must always be true for
899  // this comparison to succeeed.
900  return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
901}
902
903llvm::Value *
904MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
905                                            llvm::Value *MemPtr,
906                                            const MemberPointerType *MPT) {
907  CGBuilderTy &Builder = CGF.Builder;
908  llvm::SmallVector<llvm::Constant *, 4> fields;
909  // We only need one field for member functions.
910  if (MPT->isMemberFunctionPointer())
911    fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
912  else
913    GetNullMemberPointerFields(MPT, fields);
914  assert(!fields.empty());
915  llvm::Value *FirstField = MemPtr;
916  if (MemPtr->getType()->isStructTy())
917    FirstField = Builder.CreateExtractValue(MemPtr, 0);
918  llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
919
920  // For function member pointers, we only need to test the function pointer
921  // field.  The other fields if any can be garbage.
922  if (MPT->isMemberFunctionPointer())
923    return Res;
924
925  // Otherwise, emit a series of compares and combine the results.
926  for (int I = 1, E = fields.size(); I < E; ++I) {
927    llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
928    llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
929    Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
930  }
931  return Res;
932}
933
934bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
935                                                  llvm::Constant *Val) {
936  // Function pointers are null if the pointer in the first field is null.
937  if (MPT->isMemberFunctionPointer()) {
938    llvm::Constant *FirstField = Val->getType()->isStructTy() ?
939      Val->getAggregateElement(0U) : Val;
940    return FirstField->isNullValue();
941  }
942
943  // If it's not a function pointer and it's zero initializable, we can easily
944  // check zero.
945  if (isZeroInitializable(MPT) && Val->isNullValue())
946    return true;
947
948  // Otherwise, break down all the fields for comparison.  Hopefully these
949  // little Constants are reused, while a big null struct might not be.
950  llvm::SmallVector<llvm::Constant *, 4> Fields;
951  GetNullMemberPointerFields(MPT, Fields);
952  if (Fields.size() == 1) {
953    assert(Val->getType()->isIntegerTy());
954    return Val == Fields[0];
955  }
956
957  unsigned I, E;
958  for (I = 0, E = Fields.size(); I != E; ++I) {
959    if (Val->getAggregateElement(I) != Fields[I])
960      break;
961  }
962  return I == E;
963}
964
965llvm::Value *
966MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
967                                         llvm::Value *This,
968                                         llvm::Value *VBTableOffset,
969                                         llvm::Value *VBPtrOffset,
970                                         llvm::Value **VBPtrOut) {
971  CGBuilderTy &Builder = CGF.Builder;
972  // Load the vbtable pointer from the vbptr in the instance.
973  This = Builder.CreateBitCast(This, CGM.Int8PtrTy);
974  llvm::Value *VBPtr =
975    Builder.CreateInBoundsGEP(This, VBPtrOffset, "vbptr");
976  if (VBPtrOut) *VBPtrOut = VBPtr;
977  VBPtr = Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
978  llvm::Value *VBTable = Builder.CreateLoad(VBPtr, "vbtable");
979
980  // Load an i32 offset from the vb-table.
981  llvm::Value *VBaseOffs = Builder.CreateInBoundsGEP(VBTable, VBTableOffset);
982  VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
983  return Builder.CreateLoad(VBaseOffs, "vbase_offs");
984}
985
986// Returns an adjusted base cast to i8*, since we do more address arithmetic on
987// it.
988llvm::Value *
989MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
990                                   const CXXRecordDecl *RD, llvm::Value *Base,
991                                   llvm::Value *VBTableOffset,
992                                   llvm::Value *VBPtrOffset) {
993  CGBuilderTy &Builder = CGF.Builder;
994  Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
995  llvm::BasicBlock *OriginalBB = 0;
996  llvm::BasicBlock *SkipAdjustBB = 0;
997  llvm::BasicBlock *VBaseAdjustBB = 0;
998
999  // In the unspecified inheritance model, there might not be a vbtable at all,
1000  // in which case we need to skip the virtual base lookup.  If there is a
1001  // vbtable, the first entry is a no-op entry that gives back the original
1002  // base, so look for a virtual base adjustment offset of zero.
1003  if (VBPtrOffset) {
1004    OriginalBB = Builder.GetInsertBlock();
1005    VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
1006    SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
1007    llvm::Value *IsVirtual =
1008      Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
1009                           "memptr.is_vbase");
1010    Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
1011    CGF.EmitBlock(VBaseAdjustBB);
1012  }
1013
1014  // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
1015  // know the vbptr offset.
1016  if (!VBPtrOffset) {
1017    CharUnits offs = CharUnits::Zero();
1018    if (RD->getNumVBases()) {
1019      offs = GetVBPtrOffsetFromBases(RD);
1020    }
1021    VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
1022  }
1023  llvm::Value *VBPtr = 0;
1024  llvm::Value *VBaseOffs =
1025    GetVBaseOffsetFromVBPtr(CGF, Base, VBTableOffset, VBPtrOffset, &VBPtr);
1026  llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
1027
1028  // Merge control flow with the case where we didn't have to adjust.
1029  if (VBaseAdjustBB) {
1030    Builder.CreateBr(SkipAdjustBB);
1031    CGF.EmitBlock(SkipAdjustBB);
1032    llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
1033    Phi->addIncoming(Base, OriginalBB);
1034    Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
1035    return Phi;
1036  }
1037  return AdjustedBase;
1038}
1039
1040llvm::Value *
1041MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
1042                                              llvm::Value *Base,
1043                                              llvm::Value *MemPtr,
1044                                              const MemberPointerType *MPT) {
1045  assert(MPT->isMemberDataPointer());
1046  unsigned AS = Base->getType()->getPointerAddressSpace();
1047  llvm::Type *PType =
1048      CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
1049  CGBuilderTy &Builder = CGF.Builder;
1050  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1051  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1052
1053  // Extract the fields we need, regardless of model.  We'll apply them if we
1054  // have them.
1055  llvm::Value *FieldOffset = MemPtr;
1056  llvm::Value *VirtualBaseAdjustmentOffset = 0;
1057  llvm::Value *VBPtrOffset = 0;
1058  if (MemPtr->getType()->isStructTy()) {
1059    // We need to extract values.
1060    unsigned I = 0;
1061    FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
1062    if (hasVBPtrOffsetField(Inheritance))
1063      VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1064    if (hasVirtualBaseAdjustmentField(Inheritance))
1065      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1066  }
1067
1068  if (VirtualBaseAdjustmentOffset) {
1069    Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
1070                             VBPtrOffset);
1071  }
1072  llvm::Value *Addr =
1073    Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
1074
1075  // Cast the address to the appropriate pointer type, adopting the address
1076  // space of the base pointer.
1077  return Builder.CreateBitCast(Addr, PType);
1078}
1079
1080static MSInheritanceModel
1081getInheritanceFromMemptr(const MemberPointerType *MPT) {
1082  return MPT->getClass()->getAsCXXRecordDecl()->getMSInheritanceModel();
1083}
1084
1085llvm::Value *
1086MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
1087                                             const CastExpr *E,
1088                                             llvm::Value *Src) {
1089  assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
1090         E->getCastKind() == CK_BaseToDerivedMemberPointer ||
1091         E->getCastKind() == CK_ReinterpretMemberPointer);
1092
1093  // Use constant emission if we can.
1094  if (isa<llvm::Constant>(Src))
1095    return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
1096
1097  // We may be adding or dropping fields from the member pointer, so we need
1098  // both types and the inheritance models of both records.
1099  const MemberPointerType *SrcTy =
1100    E->getSubExpr()->getType()->castAs<MemberPointerType>();
1101  const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1102  MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1103  MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1104  bool IsFunc = SrcTy->isMemberFunctionPointer();
1105
1106  // If the classes use the same null representation, reinterpret_cast is a nop.
1107  bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
1108  if (IsReinterpret && (IsFunc ||
1109                        nullFieldOffsetIsZero(SrcInheritance) ==
1110                        nullFieldOffsetIsZero(DstInheritance)))
1111    return Src;
1112
1113  CGBuilderTy &Builder = CGF.Builder;
1114
1115  // Branch past the conversion if Src is null.
1116  llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
1117  llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
1118
1119  // C++ 5.2.10p9: The null member pointer value is converted to the null member
1120  //   pointer value of the destination type.
1121  if (IsReinterpret) {
1122    // For reinterpret casts, sema ensures that src and dst are both functions
1123    // or data and have the same size, which means the LLVM types should match.
1124    assert(Src->getType() == DstNull->getType());
1125    return Builder.CreateSelect(IsNotNull, Src, DstNull);
1126  }
1127
1128  llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
1129  llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
1130  llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
1131  Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
1132  CGF.EmitBlock(ConvertBB);
1133
1134  // Decompose src.
1135  llvm::Value *FirstField = Src;
1136  llvm::Value *NonVirtualBaseAdjustment = 0;
1137  llvm::Value *VirtualBaseAdjustmentOffset = 0;
1138  llvm::Value *VBPtrOffset = 0;
1139  if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1140    // We need to extract values.
1141    unsigned I = 0;
1142    FirstField = Builder.CreateExtractValue(Src, I++);
1143    if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1144      NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
1145    if (hasVBPtrOffsetField(SrcInheritance))
1146      VBPtrOffset = Builder.CreateExtractValue(Src, I++);
1147    if (hasVirtualBaseAdjustmentField(SrcInheritance))
1148      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
1149  }
1150
1151  // For data pointers, we adjust the field offset directly.  For functions, we
1152  // have a separate field.
1153  llvm::Constant *Adj = getMemberPointerAdjustment(E);
1154  if (Adj) {
1155    Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1156    llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
1157    bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1158    if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1159      NVAdjustField = getZeroInt();
1160    if (isDerivedToBase)
1161      NVAdjustField = Builder.CreateNSWSub(NVAdjustField, Adj, "adj");
1162    else
1163      NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, Adj, "adj");
1164  }
1165
1166  // FIXME PR15713: Support conversions through virtually derived classes.
1167
1168  // Recompose dst from the null struct and the adjusted fields from src.
1169  llvm::Value *Dst;
1170  if (hasOnlyOneField(IsFunc, DstInheritance)) {
1171    Dst = FirstField;
1172  } else {
1173    Dst = llvm::UndefValue::get(DstNull->getType());
1174    unsigned Idx = 0;
1175    Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
1176    if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1177      Dst = Builder.CreateInsertValue(
1178        Dst, getValueOrZeroInt(NonVirtualBaseAdjustment), Idx++);
1179    if (hasVBPtrOffsetField(DstInheritance))
1180      Dst = Builder.CreateInsertValue(
1181        Dst, getValueOrZeroInt(VBPtrOffset), Idx++);
1182    if (hasVirtualBaseAdjustmentField(DstInheritance))
1183      Dst = Builder.CreateInsertValue(
1184        Dst, getValueOrZeroInt(VirtualBaseAdjustmentOffset), Idx++);
1185  }
1186  Builder.CreateBr(ContinueBB);
1187
1188  // In the continuation, choose between DstNull and Dst.
1189  CGF.EmitBlock(ContinueBB);
1190  llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
1191  Phi->addIncoming(DstNull, OriginalBB);
1192  Phi->addIncoming(Dst, ConvertBB);
1193  return Phi;
1194}
1195
1196llvm::Constant *
1197MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
1198                                             llvm::Constant *Src) {
1199  const MemberPointerType *SrcTy =
1200    E->getSubExpr()->getType()->castAs<MemberPointerType>();
1201  const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
1202
1203  // If src is null, emit a new null for dst.  We can't return src because dst
1204  // might have a new representation.
1205  if (MemberPointerConstantIsNull(SrcTy, Src))
1206    return EmitNullMemberPointer(DstTy);
1207
1208  // We don't need to do anything for reinterpret_casts of non-null member
1209  // pointers.  We should only get here when the two type representations have
1210  // the same size.
1211  if (E->getCastKind() == CK_ReinterpretMemberPointer)
1212    return Src;
1213
1214  MSInheritanceModel SrcInheritance = getInheritanceFromMemptr(SrcTy);
1215  MSInheritanceModel DstInheritance = getInheritanceFromMemptr(DstTy);
1216
1217  // Decompose src.
1218  llvm::Constant *FirstField = Src;
1219  llvm::Constant *NonVirtualBaseAdjustment = 0;
1220  llvm::Constant *VirtualBaseAdjustmentOffset = 0;
1221  llvm::Constant *VBPtrOffset = 0;
1222  bool IsFunc = SrcTy->isMemberFunctionPointer();
1223  if (!hasOnlyOneField(IsFunc, SrcInheritance)) {
1224    // We need to extract values.
1225    unsigned I = 0;
1226    FirstField = Src->getAggregateElement(I++);
1227    if (hasNonVirtualBaseAdjustmentField(IsFunc, SrcInheritance))
1228      NonVirtualBaseAdjustment = Src->getAggregateElement(I++);
1229    if (hasVBPtrOffsetField(SrcInheritance))
1230      VBPtrOffset = Src->getAggregateElement(I++);
1231    if (hasVirtualBaseAdjustmentField(SrcInheritance))
1232      VirtualBaseAdjustmentOffset = Src->getAggregateElement(I++);
1233  }
1234
1235  // For data pointers, we adjust the field offset directly.  For functions, we
1236  // have a separate field.
1237  llvm::Constant *Adj = getMemberPointerAdjustment(E);
1238  if (Adj) {
1239    Adj = llvm::ConstantExpr::getTruncOrBitCast(Adj, CGM.IntTy);
1240    llvm::Constant *&NVAdjustField =
1241      IsFunc ? NonVirtualBaseAdjustment : FirstField;
1242    bool IsDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
1243    if (!NVAdjustField)  // If this field didn't exist in src, it's zero.
1244      NVAdjustField = getZeroInt();
1245    if (IsDerivedToBase)
1246      NVAdjustField = llvm::ConstantExpr::getNSWSub(NVAdjustField, Adj);
1247    else
1248      NVAdjustField = llvm::ConstantExpr::getNSWAdd(NVAdjustField, Adj);
1249  }
1250
1251  // FIXME PR15713: Support conversions through virtually derived classes.
1252
1253  // Recompose dst from the null struct and the adjusted fields from src.
1254  if (hasOnlyOneField(IsFunc, DstInheritance))
1255    return FirstField;
1256
1257  llvm::SmallVector<llvm::Constant *, 4> Fields;
1258  Fields.push_back(FirstField);
1259  if (hasNonVirtualBaseAdjustmentField(IsFunc, DstInheritance))
1260    Fields.push_back(getConstantOrZeroInt(NonVirtualBaseAdjustment));
1261  if (hasVBPtrOffsetField(DstInheritance))
1262    Fields.push_back(getConstantOrZeroInt(VBPtrOffset));
1263  if (hasVirtualBaseAdjustmentField(DstInheritance))
1264    Fields.push_back(getConstantOrZeroInt(VirtualBaseAdjustmentOffset));
1265  return llvm::ConstantStruct::getAnon(Fields);
1266}
1267
1268llvm::Value *
1269MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
1270                                                 llvm::Value *&This,
1271                                                 llvm::Value *MemPtr,
1272                                                 const MemberPointerType *MPT) {
1273  assert(MPT->isMemberFunctionPointer());
1274  const FunctionProtoType *FPT =
1275    MPT->getPointeeType()->castAs<FunctionProtoType>();
1276  const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
1277  llvm::FunctionType *FTy =
1278    CGM.getTypes().GetFunctionType(
1279      CGM.getTypes().arrangeCXXMethodType(RD, FPT));
1280  CGBuilderTy &Builder = CGF.Builder;
1281
1282  MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
1283
1284  // Extract the fields we need, regardless of model.  We'll apply them if we
1285  // have them.
1286  llvm::Value *FunctionPointer = MemPtr;
1287  llvm::Value *NonVirtualBaseAdjustment = NULL;
1288  llvm::Value *VirtualBaseAdjustmentOffset = NULL;
1289  llvm::Value *VBPtrOffset = NULL;
1290  if (MemPtr->getType()->isStructTy()) {
1291    // We need to extract values.
1292    unsigned I = 0;
1293    FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
1294    if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
1295      NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
1296    if (hasVBPtrOffsetField(Inheritance))
1297      VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
1298    if (hasVirtualBaseAdjustmentField(Inheritance))
1299      VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
1300  }
1301
1302  if (VirtualBaseAdjustmentOffset) {
1303    This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
1304                             VBPtrOffset);
1305  }
1306
1307  if (NonVirtualBaseAdjustment) {
1308    // Apply the adjustment and cast back to the original struct type.
1309    llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
1310    Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
1311    This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
1312  }
1313
1314  return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
1315}
1316
1317CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
1318  return new MicrosoftCXXABI(CGM);
1319}
1320
1321