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