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