]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/llvm/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.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 "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21
22 using namespace clang;
23 using namespace CodeGen;
24
25 namespace {
26
27 class MicrosoftCXXABI : public CGCXXABI {
28 public:
29   MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
30
31   bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
32     // Structures that are not C++03 PODs are always indirect.
33     return !RD->isPOD();
34   }
35
36   RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
37     if (RD->hasNonTrivialCopyConstructor())
38       return RAA_DirectInMemory;
39     return RAA_Default;
40   }
41
42   StringRef GetPureVirtualCallName() { return "_purecall"; }
43   // No known support for deleted functions in MSVC yet, so this choice is
44   // arbitrary.
45   StringRef GetDeletedVirtualCallName() { return "_purecall"; }
46
47   llvm::Value *adjustToCompleteObject(CodeGenFunction &CGF,
48                                       llvm::Value *ptr,
49                                       QualType type);
50
51   void BuildConstructorSignature(const CXXConstructorDecl *Ctor,
52                                  CXXCtorType Type,
53                                  CanQualType &ResTy,
54                                  SmallVectorImpl<CanQualType> &ArgTys);
55
56   llvm::BasicBlock *EmitCtorCompleteObjectHandler(CodeGenFunction &CGF);
57
58   void BuildDestructorSignature(const CXXDestructorDecl *Ctor,
59                                 CXXDtorType Type,
60                                 CanQualType &ResTy,
61                                 SmallVectorImpl<CanQualType> &ArgTys);
62
63   void BuildInstanceFunctionParams(CodeGenFunction &CGF,
64                                    QualType &ResTy,
65                                    FunctionArgList &Params);
66
67   void EmitInstanceFunctionProlog(CodeGenFunction &CGF);
68
69   llvm::Value *EmitConstructorCall(CodeGenFunction &CGF,
70                            const CXXConstructorDecl *D,
71                            CXXCtorType Type, bool ForVirtualBase,
72                            bool Delegating,
73                            llvm::Value *This,
74                            CallExpr::const_arg_iterator ArgBeg,
75                            CallExpr::const_arg_iterator ArgEnd);
76
77   RValue EmitVirtualDestructorCall(CodeGenFunction &CGF,
78                                    const CXXDestructorDecl *Dtor,
79                                    CXXDtorType DtorType,
80                                    SourceLocation CallLoc,
81                                    ReturnValueSlot ReturnValue,
82                                    llvm::Value *This);
83
84   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
85                        llvm::GlobalVariable *DeclPtr,
86                        bool PerformInit);
87
88   // ==== Notes on array cookies =========
89   //
90   // MSVC seems to only use cookies when the class has a destructor; a
91   // two-argument usual array deallocation function isn't sufficient.
92   //
93   // For example, this code prints "100" and "1":
94   //   struct A {
95   //     char x;
96   //     void *operator new[](size_t sz) {
97   //       printf("%u\n", sz);
98   //       return malloc(sz);
99   //     }
100   //     void operator delete[](void *p, size_t sz) {
101   //       printf("%u\n", sz);
102   //       free(p);
103   //     }
104   //   };
105   //   int main() {
106   //     A *p = new A[100];
107   //     delete[] p;
108   //   }
109   // Whereas it prints "104" and "104" if you give A a destructor.
110
111   bool requiresArrayCookie(const CXXDeleteExpr *expr, QualType elementType);
112   bool requiresArrayCookie(const CXXNewExpr *expr);
113   CharUnits getArrayCookieSizeImpl(QualType type);
114   llvm::Value *InitializeArrayCookie(CodeGenFunction &CGF,
115                                      llvm::Value *NewPtr,
116                                      llvm::Value *NumElements,
117                                      const CXXNewExpr *expr,
118                                      QualType ElementType);
119   llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
120                                    llvm::Value *allocPtr,
121                                    CharUnits cookieSize);
122   static bool needThisReturn(GlobalDecl GD);
123
124 private:
125   llvm::Constant *getZeroInt() {
126     return llvm::ConstantInt::get(CGM.IntTy, 0);
127   }
128
129   llvm::Constant *getAllOnesInt() {
130     return  llvm::Constant::getAllOnesValue(CGM.IntTy);
131   }
132
133   void
134   GetNullMemberPointerFields(const MemberPointerType *MPT,
135                              llvm::SmallVectorImpl<llvm::Constant *> &fields);
136
137   llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
138                                  llvm::Value *Base,
139                                  llvm::Value *VirtualBaseAdjustmentOffset,
140                                  llvm::Value *VBPtrOffset /* optional */);
141
142   /// \brief Emits a full member pointer with the fields common to data and
143   /// function member pointers.
144   llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
145                                         bool IsMemberFunction,
146                                         const CXXRecordDecl *RD);
147
148 public:
149   virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
150
151   virtual bool isZeroInitializable(const MemberPointerType *MPT);
152
153   virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
154
155   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
156                                                 CharUnits offset);
157   virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
158   virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
159
160   virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
161                                                    llvm::Value *L,
162                                                    llvm::Value *R,
163                                                    const MemberPointerType *MPT,
164                                                    bool Inequality);
165
166   virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
167                                                   llvm::Value *MemPtr,
168                                                   const MemberPointerType *MPT);
169
170   virtual llvm::Value *EmitMemberDataPointerAddress(CodeGenFunction &CGF,
171                                                     llvm::Value *Base,
172                                                     llvm::Value *MemPtr,
173                                                   const MemberPointerType *MPT);
174
175   virtual llvm::Value *
176   EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
177                                   llvm::Value *&This,
178                                   llvm::Value *MemPtr,
179                                   const MemberPointerType *MPT);
180
181 };
182
183 }
184
185 llvm::Value *MicrosoftCXXABI::adjustToCompleteObject(CodeGenFunction &CGF,
186                                                      llvm::Value *ptr,
187                                                      QualType type) {
188   // FIXME: implement
189   return ptr;
190 }
191
192 bool MicrosoftCXXABI::needThisReturn(GlobalDecl GD) {
193   const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
194   return isa<CXXConstructorDecl>(MD);
195 }
196
197 void MicrosoftCXXABI::BuildConstructorSignature(const CXXConstructorDecl *Ctor,
198                                  CXXCtorType Type,
199                                  CanQualType &ResTy,
200                                  SmallVectorImpl<CanQualType> &ArgTys) {
201   // 'this' is already in place
202
203   // Ctor returns this ptr
204   ResTy = ArgTys[0];
205
206   const CXXRecordDecl *Class = Ctor->getParent();
207   if (Class->getNumVBases()) {
208     // Constructors of classes with virtual bases take an implicit parameter.
209     ArgTys.push_back(CGM.getContext().IntTy);
210   }
211 }
212
213 llvm::BasicBlock *MicrosoftCXXABI::EmitCtorCompleteObjectHandler(
214                                                          CodeGenFunction &CGF) {
215   llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
216   assert(IsMostDerivedClass &&
217          "ctor for a class with virtual bases must have an implicit parameter");
218   llvm::Value *IsCompleteObject
219     = CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
220
221   llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
222   llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
223   CGF.Builder.CreateCondBr(IsCompleteObject,
224                            CallVbaseCtorsBB, SkipVbaseCtorsBB);
225
226   CGF.EmitBlock(CallVbaseCtorsBB);
227   // FIXME: emit vbtables somewhere around here.
228
229   // CGF will put the base ctor calls in this basic block for us later.
230
231   return SkipVbaseCtorsBB;
232 }
233
234 void MicrosoftCXXABI::BuildDestructorSignature(const CXXDestructorDecl *Dtor,
235                                                CXXDtorType Type,
236                                                CanQualType &ResTy,
237                                         SmallVectorImpl<CanQualType> &ArgTys) {
238   // 'this' is already in place
239   // TODO: 'for base' flag
240
241   if (Type == Dtor_Deleting) {
242     // The scalar deleting destructor takes an implicit bool parameter.
243     ArgTys.push_back(CGM.getContext().BoolTy);
244   }
245 }
246
247 static bool IsDeletingDtor(GlobalDecl GD) {
248   const CXXMethodDecl* MD = cast<CXXMethodDecl>(GD.getDecl());
249   if (isa<CXXDestructorDecl>(MD)) {
250     return GD.getDtorType() == Dtor_Deleting;
251   }
252   return false;
253 }
254
255 void MicrosoftCXXABI::BuildInstanceFunctionParams(CodeGenFunction &CGF,
256                                                   QualType &ResTy,
257                                                   FunctionArgList &Params) {
258   BuildThisParam(CGF, Params);
259   if (needThisReturn(CGF.CurGD)) {
260     ResTy = Params[0]->getType();
261   }
262
263   ASTContext &Context = getContext();
264   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
265   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
266     ImplicitParamDecl *IsMostDerived
267       = ImplicitParamDecl::Create(Context, 0,
268                                   CGF.CurGD.getDecl()->getLocation(),
269                                   &Context.Idents.get("is_most_derived"),
270                                   Context.IntTy);
271     Params.push_back(IsMostDerived);
272     getStructorImplicitParamDecl(CGF) = IsMostDerived;
273   } else if (IsDeletingDtor(CGF.CurGD)) {
274     ImplicitParamDecl *ShouldDelete
275       = ImplicitParamDecl::Create(Context, 0,
276                                   CGF.CurGD.getDecl()->getLocation(),
277                                   &Context.Idents.get("should_call_delete"),
278                                   Context.BoolTy);
279     Params.push_back(ShouldDelete);
280     getStructorImplicitParamDecl(CGF) = ShouldDelete;
281   }
282 }
283
284 void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
285   EmitThisParam(CGF);
286   if (needThisReturn(CGF.CurGD)) {
287     CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
288   }
289
290   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
291   if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
292     assert(getStructorImplicitParamDecl(CGF) &&
293            "no implicit parameter for a constructor with virtual bases?");
294     getStructorImplicitParamValue(CGF)
295       = CGF.Builder.CreateLoad(
296           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
297           "is_most_derived");
298   }
299
300   if (IsDeletingDtor(CGF.CurGD)) {
301     assert(getStructorImplicitParamDecl(CGF) &&
302            "no implicit parameter for a deleting destructor?");
303     getStructorImplicitParamValue(CGF)
304       = CGF.Builder.CreateLoad(
305           CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
306           "should_call_delete");
307   }
308 }
309
310 llvm::Value *MicrosoftCXXABI::EmitConstructorCall(CodeGenFunction &CGF,
311                                           const CXXConstructorDecl *D,
312                                           CXXCtorType Type, bool ForVirtualBase,
313                                           bool Delegating,
314                                           llvm::Value *This,
315                                           CallExpr::const_arg_iterator ArgBeg,
316                                           CallExpr::const_arg_iterator ArgEnd) {
317   assert(Type == Ctor_Complete || Type == Ctor_Base);
318   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Ctor_Complete);
319
320   llvm::Value *ImplicitParam = 0;
321   QualType ImplicitParamTy;
322   if (D->getParent()->getNumVBases()) {
323     ImplicitParam = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
324     ImplicitParamTy = getContext().IntTy;
325   }
326
327   // FIXME: Provide a source location here.
328   CGF.EmitCXXMemberCall(D, SourceLocation(), Callee, ReturnValueSlot(), This,
329                         ImplicitParam, ImplicitParamTy,
330                         ArgBeg, ArgEnd);
331   return Callee;
332 }
333
334 RValue MicrosoftCXXABI::EmitVirtualDestructorCall(CodeGenFunction &CGF,
335                                                   const CXXDestructorDecl *Dtor,
336                                                   CXXDtorType DtorType,
337                                                   SourceLocation CallLoc,
338                                                   ReturnValueSlot ReturnValue,
339                                                   llvm::Value *This) {
340   assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
341
342   // We have only one destructor in the vftable but can get both behaviors
343   // by passing an implicit bool parameter.
344   const CGFunctionInfo *FInfo
345       = &CGM.getTypes().arrangeCXXDestructor(Dtor, Dtor_Deleting);
346   llvm::Type *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
347   llvm::Value *Callee = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, This, Ty);
348
349   ASTContext &Context = CGF.getContext();
350   llvm::Value *ImplicitParam
351     = llvm::ConstantInt::get(llvm::IntegerType::getInt1Ty(CGF.getLLVMContext()),
352                              DtorType == Dtor_Deleting);
353
354   return CGF.EmitCXXMemberCall(Dtor, CallLoc, Callee, ReturnValue, This,
355                                ImplicitParam, Context.BoolTy, 0, 0);
356 }
357
358 bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
359                                    QualType elementType) {
360   // Microsoft seems to completely ignore the possibility of a
361   // two-argument usual deallocation function.
362   return elementType.isDestructedType();
363 }
364
365 bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
366   // Microsoft seems to completely ignore the possibility of a
367   // two-argument usual deallocation function.
368   return expr->getAllocatedType().isDestructedType();
369 }
370
371 CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
372   // The array cookie is always a size_t; we then pad that out to the
373   // alignment of the element type.
374   ASTContext &Ctx = getContext();
375   return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
376                   Ctx.getTypeAlignInChars(type));
377 }
378
379 llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
380                                                   llvm::Value *allocPtr,
381                                                   CharUnits cookieSize) {
382   unsigned AS = allocPtr->getType()->getPointerAddressSpace();
383   llvm::Value *numElementsPtr =
384     CGF.Builder.CreateBitCast(allocPtr, CGF.SizeTy->getPointerTo(AS));
385   return CGF.Builder.CreateLoad(numElementsPtr);
386 }
387
388 llvm::Value* MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
389                                                     llvm::Value *newPtr,
390                                                     llvm::Value *numElements,
391                                                     const CXXNewExpr *expr,
392                                                     QualType elementType) {
393   assert(requiresArrayCookie(expr));
394
395   // The size of the cookie.
396   CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
397
398   // Compute an offset to the cookie.
399   llvm::Value *cookiePtr = newPtr;
400
401   // Write the number of elements into the appropriate slot.
402   unsigned AS = newPtr->getType()->getPointerAddressSpace();
403   llvm::Value *numElementsPtr
404     = CGF.Builder.CreateBitCast(cookiePtr, CGF.SizeTy->getPointerTo(AS));
405   CGF.Builder.CreateStore(numElements, numElementsPtr);
406
407   // Finally, compute a pointer to the actual data buffer by skipping
408   // over the cookie completely.
409   return CGF.Builder.CreateConstInBoundsGEP1_64(newPtr,
410                                                 cookieSize.getQuantity());
411 }
412
413 void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
414                                       llvm::GlobalVariable *DeclPtr,
415                                       bool PerformInit) {
416   // FIXME: this code was only tested for global initialization.
417   // Not sure whether we want thread-safe static local variables as VS
418   // doesn't make them thread-safe.
419
420   if (D.getTLSKind())
421     CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
422
423   // Emit the initializer and add a global destructor if appropriate.
424   CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
425 }
426
427 // Member pointer helpers.
428 static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
429   return Inheritance == MSIM_Unspecified;
430 }
431
432 static bool hasOnlyOneField(MSInheritanceModel Inheritance) {
433   return Inheritance <= MSIM_SinglePolymorphic;
434 }
435
436 // Only member pointers to functions need a this adjustment, since it can be
437 // combined with the field offset for data pointers.
438 static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
439                                              MSInheritanceModel Inheritance) {
440   return (IsMemberFunction && Inheritance >= MSIM_Multiple);
441 }
442
443 static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
444   return Inheritance >= MSIM_Virtual;
445 }
446
447 // Use zero for the field offset of a null data member pointer if we can
448 // guarantee that zero is not a valid field offset, or if the member pointer has
449 // multiple fields.  Polymorphic classes have a vfptr at offset zero, so we can
450 // use zero for null.  If there are multiple fields, we can use zero even if it
451 // is a valid field offset because null-ness testing will check the other
452 // fields.
453 static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
454   return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
455 }
456
457 bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
458   // Null-ness for function memptrs only depends on the first field, which is
459   // the function pointer.  The rest don't matter, so we can zero initialize.
460   if (MPT->isMemberFunctionPointer())
461     return true;
462
463   // The virtual base adjustment field is always -1 for null, so if we have one
464   // we can't zero initialize.  The field offset is sometimes also -1 if 0 is a
465   // valid field offset.
466   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
467   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
468   return (!hasVirtualBaseAdjustmentField(Inheritance) &&
469           nullFieldOffsetIsZero(Inheritance));
470 }
471
472 llvm::Type *
473 MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
474   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
475   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
476   llvm::SmallVector<llvm::Type *, 4> fields;
477   if (MPT->isMemberFunctionPointer())
478     fields.push_back(CGM.VoidPtrTy);  // FunctionPointerOrVirtualThunk
479   else
480     fields.push_back(CGM.IntTy);  // FieldOffset
481
482   if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
483                                        Inheritance))
484     fields.push_back(CGM.IntTy);
485   if (hasVBPtrOffsetField(Inheritance))
486     fields.push_back(CGM.IntTy);
487   if (hasVirtualBaseAdjustmentField(Inheritance))
488     fields.push_back(CGM.IntTy);  // VirtualBaseAdjustmentOffset
489
490   if (fields.size() == 1)
491     return fields[0];
492   return llvm::StructType::get(CGM.getLLVMContext(), fields);
493 }
494
495 void MicrosoftCXXABI::
496 GetNullMemberPointerFields(const MemberPointerType *MPT,
497                            llvm::SmallVectorImpl<llvm::Constant *> &fields) {
498   assert(fields.empty());
499   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
500   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
501   if (MPT->isMemberFunctionPointer()) {
502     // FunctionPointerOrVirtualThunk
503     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
504   } else {
505     if (nullFieldOffsetIsZero(Inheritance))
506       fields.push_back(getZeroInt());  // FieldOffset
507     else
508       fields.push_back(getAllOnesInt());  // FieldOffset
509   }
510
511   if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
512                                        Inheritance))
513     fields.push_back(getZeroInt());
514   if (hasVBPtrOffsetField(Inheritance))
515     fields.push_back(getZeroInt());
516   if (hasVirtualBaseAdjustmentField(Inheritance))
517     fields.push_back(getAllOnesInt());
518 }
519
520 llvm::Constant *
521 MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
522   llvm::SmallVector<llvm::Constant *, 4> fields;
523   GetNullMemberPointerFields(MPT, fields);
524   if (fields.size() == 1)
525     return fields[0];
526   llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
527   assert(Res->getType() == ConvertMemberPointerType(MPT));
528   return Res;
529 }
530
531 llvm::Constant *
532 MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
533                                        bool IsMemberFunction,
534                                        const CXXRecordDecl *RD)
535 {
536   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
537
538   // Single inheritance class member pointer are represented as scalars instead
539   // of aggregates.
540   if (hasOnlyOneField(Inheritance))
541     return FirstField;
542
543   llvm::SmallVector<llvm::Constant *, 4> fields;
544   fields.push_back(FirstField);
545
546   if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
547     fields.push_back(getZeroInt());
548
549   if (hasVBPtrOffsetField(Inheritance)) {
550     int64_t VBPtrOffset =
551       getContext().getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
552     if (VBPtrOffset == -1)
553       VBPtrOffset = 0;
554     fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset));
555   }
556
557   // The rest of the fields are adjusted by conversions to a more derived class.
558   if (hasVirtualBaseAdjustmentField(Inheritance))
559     fields.push_back(getZeroInt());
560
561   return llvm::ConstantStruct::getAnon(fields);
562 }
563
564 llvm::Constant *
565 MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
566                                        CharUnits offset) {
567   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
568   llvm::Constant *FirstField =
569     llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
570   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD);
571 }
572
573 llvm::Constant *
574 MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
575   assert(MD->isInstance() && "Member function must not be static!");
576   MD = MD->getCanonicalDecl();
577   const CXXRecordDecl *RD = MD->getParent();
578   CodeGenTypes &Types = CGM.getTypes();
579
580   llvm::Constant *FirstField;
581   if (MD->isVirtual()) {
582     // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
583     // the right offset.
584     FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
585   } else {
586     const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
587     llvm::Type *Ty;
588     // Check whether the function has a computable LLVM signature.
589     if (Types.isFuncTypeConvertible(FPT)) {
590       // The function has a computable LLVM signature; use the correct type.
591       Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
592     } else {
593       // Use an arbitrary non-function type to tell GetAddrOfFunction that the
594       // function type is incomplete.
595       Ty = CGM.PtrDiffTy;
596     }
597     FirstField = CGM.GetAddrOfFunction(MD, Ty);
598     FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
599   }
600
601   // The rest of the fields are common with data member pointers.
602   return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD);
603 }
604
605 llvm::Constant *
606 MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {
607   // FIXME PR15875: Implement member pointer conversions for Constants.
608   const CXXRecordDecl *RD = MPT->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl();
609   return EmitFullMemberPointer(llvm::Constant::getNullValue(CGM.VoidPtrTy),
610                                /*IsMemberFunction=*/true, RD);
611 }
612
613 /// Member pointers are the same if they're either bitwise identical *or* both
614 /// null.  Null-ness for function members is determined by the first field,
615 /// while for data member pointers we must compare all fields.
616 llvm::Value *
617 MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
618                                              llvm::Value *L,
619                                              llvm::Value *R,
620                                              const MemberPointerType *MPT,
621                                              bool Inequality) {
622   CGBuilderTy &Builder = CGF.Builder;
623
624   // Handle != comparisons by switching the sense of all boolean operations.
625   llvm::ICmpInst::Predicate Eq;
626   llvm::Instruction::BinaryOps And, Or;
627   if (Inequality) {
628     Eq = llvm::ICmpInst::ICMP_NE;
629     And = llvm::Instruction::Or;
630     Or = llvm::Instruction::And;
631   } else {
632     Eq = llvm::ICmpInst::ICMP_EQ;
633     And = llvm::Instruction::And;
634     Or = llvm::Instruction::Or;
635   }
636
637   // If this is a single field member pointer (single inheritance), this is a
638   // single icmp.
639   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
640   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
641   if (hasOnlyOneField(Inheritance))
642     return Builder.CreateICmp(Eq, L, R);
643
644   // Compare the first field.
645   llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
646   llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
647   llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
648
649   // Compare everything other than the first field.
650   llvm::Value *Res = 0;
651   llvm::StructType *LType = cast<llvm::StructType>(L->getType());
652   for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
653     llvm::Value *LF = Builder.CreateExtractValue(L, I);
654     llvm::Value *RF = Builder.CreateExtractValue(R, I);
655     llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
656     if (Res)
657       Res = Builder.CreateBinOp(And, Res, Cmp);
658     else
659       Res = Cmp;
660   }
661
662   // Check if the first field is 0 if this is a function pointer.
663   if (MPT->isMemberFunctionPointer()) {
664     // (l1 == r1 && ...) || l0 == 0
665     llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
666     llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
667     Res = Builder.CreateBinOp(Or, Res, IsZero);
668   }
669
670   // Combine the comparison of the first field, which must always be true for
671   // this comparison to succeeed.
672   return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
673 }
674
675 llvm::Value *
676 MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
677                                             llvm::Value *MemPtr,
678                                             const MemberPointerType *MPT) {
679   CGBuilderTy &Builder = CGF.Builder;
680   llvm::SmallVector<llvm::Constant *, 4> fields;
681   // We only need one field for member functions.
682   if (MPT->isMemberFunctionPointer())
683     fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
684   else
685     GetNullMemberPointerFields(MPT, fields);
686   assert(!fields.empty());
687   llvm::Value *FirstField = MemPtr;
688   if (MemPtr->getType()->isStructTy())
689     FirstField = Builder.CreateExtractValue(MemPtr, 0);
690   llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
691
692   // For function member pointers, we only need to test the function pointer
693   // field.  The other fields if any can be garbage.
694   if (MPT->isMemberFunctionPointer())
695     return Res;
696
697   // Otherwise, emit a series of compares and combine the results.
698   for (int I = 1, E = fields.size(); I < E; ++I) {
699     llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
700     llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
701     Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
702   }
703   return Res;
704 }
705
706 // Returns an adjusted base cast to i8*, since we do more address arithmetic on
707 // it.
708 llvm::Value *
709 MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
710                                    const CXXRecordDecl *RD, llvm::Value *Base,
711                                    llvm::Value *VirtualBaseAdjustmentOffset,
712                                    llvm::Value *VBPtrOffset) {
713   CGBuilderTy &Builder = CGF.Builder;
714   Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
715   llvm::BasicBlock *OriginalBB = 0;
716   llvm::BasicBlock *SkipAdjustBB = 0;
717   llvm::BasicBlock *VBaseAdjustBB = 0;
718
719   // In the unspecified inheritance model, there might not be a vbtable at all,
720   // in which case we need to skip the virtual base lookup.  If there is a
721   // vbtable, the first entry is a no-op entry that gives back the original
722   // base, so look for a virtual base adjustment offset of zero.
723   if (VBPtrOffset) {
724     OriginalBB = Builder.GetInsertBlock();
725     VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
726     SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
727     llvm::Value *IsVirtual =
728       Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(),
729                            "memptr.is_vbase");
730     Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
731     CGF.EmitBlock(VBaseAdjustBB);
732   }
733
734   // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
735   // know the vbptr offset.
736   if (!VBPtrOffset) {
737     CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
738     VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
739   }
740   // Load the vbtable pointer from the vbtable offset in the instance.
741   llvm::Value *VBPtr =
742     Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr");
743   llvm::Value *VBTable =
744     Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
745   VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable");
746   // Load an i32 offset from the vb-table.
747   llvm::Value *VBaseOffs =
748     Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset);
749   VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
750   VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs");
751   // Add it to VBPtr.  GEP will sign extend the i32 value for us.
752   llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
753
754   // Merge control flow with the case where we didn't have to adjust.
755   if (VBaseAdjustBB) {
756     Builder.CreateBr(SkipAdjustBB);
757     CGF.EmitBlock(SkipAdjustBB);
758     llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
759     Phi->addIncoming(Base, OriginalBB);
760     Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
761     return Phi;
762   }
763   return AdjustedBase;
764 }
765
766 llvm::Value *
767 MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
768                                               llvm::Value *Base,
769                                               llvm::Value *MemPtr,
770                                               const MemberPointerType *MPT) {
771   assert(MPT->isMemberDataPointer());
772   unsigned AS = Base->getType()->getPointerAddressSpace();
773   llvm::Type *PType =
774       CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
775   CGBuilderTy &Builder = CGF.Builder;
776   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
777   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
778
779   // Extract the fields we need, regardless of model.  We'll apply them if we
780   // have them.
781   llvm::Value *FieldOffset = MemPtr;
782   llvm::Value *VirtualBaseAdjustmentOffset = 0;
783   llvm::Value *VBPtrOffset = 0;
784   if (MemPtr->getType()->isStructTy()) {
785     // We need to extract values.
786     unsigned I = 0;
787     FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
788     if (hasVBPtrOffsetField(Inheritance))
789       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
790     if (hasVirtualBaseAdjustmentField(Inheritance))
791       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
792   }
793
794   if (VirtualBaseAdjustmentOffset) {
795     Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
796                              VBPtrOffset);
797   }
798   llvm::Value *Addr =
799     Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
800
801   // Cast the address to the appropriate pointer type, adopting the address
802   // space of the base pointer.
803   return Builder.CreateBitCast(Addr, PType);
804 }
805
806 llvm::Value *
807 MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
808                                                  llvm::Value *&This,
809                                                  llvm::Value *MemPtr,
810                                                  const MemberPointerType *MPT) {
811   assert(MPT->isMemberFunctionPointer());
812   const FunctionProtoType *FPT =
813     MPT->getPointeeType()->castAs<FunctionProtoType>();
814   const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
815   llvm::FunctionType *FTy =
816     CGM.getTypes().GetFunctionType(
817       CGM.getTypes().arrangeCXXMethodType(RD, FPT));
818   CGBuilderTy &Builder = CGF.Builder;
819
820   MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
821
822   // Extract the fields we need, regardless of model.  We'll apply them if we
823   // have them.
824   llvm::Value *FunctionPointer = MemPtr;
825   llvm::Value *NonVirtualBaseAdjustment = NULL;
826   llvm::Value *VirtualBaseAdjustmentOffset = NULL;
827   llvm::Value *VBPtrOffset = NULL;
828   if (MemPtr->getType()->isStructTy()) {
829     // We need to extract values.
830     unsigned I = 0;
831     FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
832     if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
833       NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
834     if (hasVBPtrOffsetField(Inheritance))
835       VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
836     if (hasVirtualBaseAdjustmentField(Inheritance))
837       VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
838   }
839
840   if (VirtualBaseAdjustmentOffset) {
841     This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
842                              VBPtrOffset);
843   }
844
845   if (NonVirtualBaseAdjustment) {
846     // Apply the adjustment and cast back to the original struct type.
847     llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
848     Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
849     This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
850   }
851
852   return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
853 }
854
855 CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
856   return new MicrosoftCXXABI(CGM);
857 }
858