Home | History | Annotate | Download | only in CodeGen
      1 //===----- CGCXXABI.cpp - Interface to C++ ABIs ---------------------------===//
      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 an abstract class for C++ code generation. Concrete subclasses
     11 // of this implement code generation for specific C++ ABIs.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "CGCXXABI.h"
     16 #include "CGCleanup.h"
     17 
     18 using namespace clang;
     19 using namespace CodeGen;
     20 
     21 CGCXXABI::~CGCXXABI() { }
     22 
     23 void CGCXXABI::ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S) {
     24   DiagnosticsEngine &Diags = CGF.CGM.getDiags();
     25   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
     26                                           "cannot yet compile %0 in this ABI");
     27   Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()),
     28                DiagID)
     29     << S;
     30 }
     31 
     32 bool CGCXXABI::canCopyArgument(const CXXRecordDecl *RD) const {
     33   // If RD has a non-trivial move or copy constructor, we cannot copy the
     34   // argument.
     35   if (RD->hasNonTrivialCopyConstructor() || RD->hasNonTrivialMoveConstructor())
     36     return false;
     37 
     38   // If RD has a non-trivial destructor, we cannot copy the argument.
     39   if (RD->hasNonTrivialDestructor())
     40     return false;
     41 
     42   // We can only copy the argument if there exists at least one trivial,
     43   // non-deleted copy or move constructor.
     44   // FIXME: This assumes that all lazily declared copy and move constructors are
     45   // not deleted.  This assumption might not be true in some corner cases.
     46   bool CopyDeleted = false;
     47   bool MoveDeleted = false;
     48   for (const CXXConstructorDecl *CD : RD->ctors()) {
     49     if (CD->isCopyConstructor() || CD->isMoveConstructor()) {
     50       assert(CD->isTrivial());
     51       // We had at least one undeleted trivial copy or move ctor.  Return
     52       // directly.
     53       if (!CD->isDeleted())
     54         return true;
     55       if (CD->isCopyConstructor())
     56         CopyDeleted = true;
     57       else
     58         MoveDeleted = true;
     59     }
     60   }
     61 
     62   // If all trivial copy and move constructors are deleted, we cannot copy the
     63   // argument.
     64   return !(CopyDeleted && MoveDeleted);
     65 }
     66 
     67 llvm::Constant *CGCXXABI::GetBogusMemberPointer(QualType T) {
     68   return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T));
     69 }
     70 
     71 llvm::Type *
     72 CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
     73   return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
     74 }
     75 
     76 llvm::Value *CGCXXABI::EmitLoadOfMemberFunctionPointer(
     77     CodeGenFunction &CGF, const Expr *E, Address This,
     78     llvm::Value *&ThisPtrForCall,
     79     llvm::Value *MemPtr, const MemberPointerType *MPT) {
     80   ErrorUnsupportedABI(CGF, "calls through member pointers");
     81 
     82   ThisPtrForCall = This.getPointer();
     83   const FunctionProtoType *FPT =
     84     MPT->getPointeeType()->getAs<FunctionProtoType>();
     85   const CXXRecordDecl *RD =
     86     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
     87   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
     88       CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
     89   return llvm::Constant::getNullValue(FTy->getPointerTo());
     90 }
     91 
     92 llvm::Value *
     93 CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
     94                                        Address Base, llvm::Value *MemPtr,
     95                                        const MemberPointerType *MPT) {
     96   ErrorUnsupportedABI(CGF, "loads of member pointers");
     97   llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())
     98                          ->getPointerTo(Base.getAddressSpace());
     99   return llvm::Constant::getNullValue(Ty);
    100 }
    101 
    102 llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
    103                                                    const CastExpr *E,
    104                                                    llvm::Value *Src) {
    105   ErrorUnsupportedABI(CGF, "member function pointer conversions");
    106   return GetBogusMemberPointer(E->getType());
    107 }
    108 
    109 llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E,
    110                                                       llvm::Constant *Src) {
    111   return GetBogusMemberPointer(E->getType());
    112 }
    113 
    114 llvm::Value *
    115 CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
    116                                       llvm::Value *L,
    117                                       llvm::Value *R,
    118                                       const MemberPointerType *MPT,
    119                                       bool Inequality) {
    120   ErrorUnsupportedABI(CGF, "member function pointer comparison");
    121   return CGF.Builder.getFalse();
    122 }
    123 
    124 llvm::Value *
    125 CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
    126                                      llvm::Value *MemPtr,
    127                                      const MemberPointerType *MPT) {
    128   ErrorUnsupportedABI(CGF, "member function pointer null testing");
    129   return CGF.Builder.getFalse();
    130 }
    131 
    132 llvm::Constant *
    133 CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
    134   return GetBogusMemberPointer(QualType(MPT, 0));
    135 }
    136 
    137 llvm::Constant *CGCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
    138   return GetBogusMemberPointer(CGM.getContext().getMemberPointerType(
    139       MD->getType(), MD->getParent()->getTypeForDecl()));
    140 }
    141 
    142 llvm::Constant *CGCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
    143                                                 CharUnits offset) {
    144   return GetBogusMemberPointer(QualType(MPT, 0));
    145 }
    146 
    147 llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {
    148   return GetBogusMemberPointer(MPT);
    149 }
    150 
    151 bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
    152   // Fake answer.
    153   return true;
    154 }
    155 
    156 void CGCXXABI::buildThisParam(CodeGenFunction &CGF, FunctionArgList &params) {
    157   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
    158 
    159   // FIXME: I'm not entirely sure I like using a fake decl just for code
    160   // generation. Maybe we can come up with a better way?
    161   ImplicitParamDecl *ThisDecl
    162     = ImplicitParamDecl::Create(CGM.getContext(), nullptr, MD->getLocation(),
    163                                 &CGM.getContext().Idents.get("this"),
    164                                 MD->getThisType(CGM.getContext()));
    165   params.push_back(ThisDecl);
    166   CGF.CXXABIThisDecl = ThisDecl;
    167 
    168   // Compute the presumed alignment of 'this', which basically comes
    169   // down to whether we know it's a complete object or not.
    170   auto &Layout = CGF.getContext().getASTRecordLayout(MD->getParent());
    171   if (MD->getParent()->getNumVBases() == 0 || // avoid vcall in common case
    172       MD->getParent()->hasAttr<FinalAttr>() ||
    173       !isThisCompleteObject(CGF.CurGD)) {
    174     CGF.CXXABIThisAlignment = Layout.getAlignment();
    175   } else {
    176     CGF.CXXABIThisAlignment = Layout.getNonVirtualAlignment();
    177   }
    178 }
    179 
    180 void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) {
    181   /// Initialize the 'this' slot.
    182   assert(getThisDecl(CGF) && "no 'this' variable for function");
    183   CGF.CXXABIThisValue
    184     = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),
    185                              "this");
    186 }
    187 
    188 void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
    189                                    RValue RV, QualType ResultType) {
    190   CGF.EmitReturnOfRValue(RV, ResultType);
    191 }
    192 
    193 CharUnits CGCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {
    194   if (!requiresArrayCookie(expr))
    195     return CharUnits::Zero();
    196   return getArrayCookieSizeImpl(expr->getAllocatedType());
    197 }
    198 
    199 CharUnits CGCXXABI::getArrayCookieSizeImpl(QualType elementType) {
    200   // BOGUS
    201   return CharUnits::Zero();
    202 }
    203 
    204 Address CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
    205                                         Address NewPtr,
    206                                         llvm::Value *NumElements,
    207                                         const CXXNewExpr *expr,
    208                                         QualType ElementType) {
    209   // Should never be called.
    210   ErrorUnsupportedABI(CGF, "array cookie initialization");
    211   return Address::invalid();
    212 }
    213 
    214 bool CGCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
    215                                    QualType elementType) {
    216   // If the class's usual deallocation function takes two arguments,
    217   // it needs a cookie.
    218   if (expr->doesUsualArrayDeleteWantSize())
    219     return true;
    220 
    221   return elementType.isDestructedType();
    222 }
    223 
    224 bool CGCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
    225   // If the class's usual deallocation function takes two arguments,
    226   // it needs a cookie.
    227   if (expr->doesUsualArrayDeleteWantSize())
    228     return true;
    229 
    230   return expr->getAllocatedType().isDestructedType();
    231 }
    232 
    233 void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, Address ptr,
    234                                const CXXDeleteExpr *expr, QualType eltTy,
    235                                llvm::Value *&numElements,
    236                                llvm::Value *&allocPtr, CharUnits &cookieSize) {
    237   // Derive a char* in the same address space as the pointer.
    238   ptr = CGF.Builder.CreateElementBitCast(ptr, CGF.Int8Ty);
    239 
    240   // If we don't need an array cookie, bail out early.
    241   if (!requiresArrayCookie(expr, eltTy)) {
    242     allocPtr = ptr.getPointer();
    243     numElements = nullptr;
    244     cookieSize = CharUnits::Zero();
    245     return;
    246   }
    247 
    248   cookieSize = getArrayCookieSizeImpl(eltTy);
    249   Address allocAddr =
    250     CGF.Builder.CreateConstInBoundsByteGEP(ptr, -cookieSize);
    251   allocPtr = allocAddr.getPointer();
    252   numElements = readArrayCookieImpl(CGF, allocAddr, cookieSize);
    253 }
    254 
    255 llvm::Value *CGCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
    256                                            Address ptr,
    257                                            CharUnits cookieSize) {
    258   ErrorUnsupportedABI(CGF, "reading a new[] cookie");
    259   return llvm::ConstantInt::get(CGF.SizeTy, 0);
    260 }
    261 
    262 /// Returns the adjustment, in bytes, required for the given
    263 /// member-pointer operation.  Returns null if no adjustment is
    264 /// required.
    265 llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) {
    266   assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
    267          E->getCastKind() == CK_BaseToDerivedMemberPointer);
    268 
    269   QualType derivedType;
    270   if (E->getCastKind() == CK_DerivedToBaseMemberPointer)
    271     derivedType = E->getSubExpr()->getType();
    272   else
    273     derivedType = E->getType();
    274 
    275   const CXXRecordDecl *derivedClass =
    276     derivedType->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl();
    277 
    278   return CGM.GetNonVirtualBaseClassOffset(derivedClass,
    279                                           E->path_begin(),
    280                                           E->path_end());
    281 }
    282 
    283 CharUnits CGCXXABI::getMemberPointerPathAdjustment(const APValue &MP) {
    284   // TODO: Store base specifiers in APValue member pointer paths so we can
    285   // easily reuse CGM.GetNonVirtualBaseClassOffset().
    286   const ValueDecl *MPD = MP.getMemberPointerDecl();
    287   CharUnits ThisAdjustment = CharUnits::Zero();
    288   ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
    289   bool DerivedMember = MP.isMemberPointerToDerivedMember();
    290   const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
    291   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
    292     const CXXRecordDecl *Base = RD;
    293     const CXXRecordDecl *Derived = Path[I];
    294     if (DerivedMember)
    295       std::swap(Base, Derived);
    296     ThisAdjustment +=
    297       getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
    298     RD = Path[I];
    299   }
    300   if (DerivedMember)
    301     ThisAdjustment = -ThisAdjustment;
    302   return ThisAdjustment;
    303 }
    304 
    305 llvm::BasicBlock *
    306 CGCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
    307                                         const CXXRecordDecl *RD) {
    308   if (CGM.getTarget().getCXXABI().hasConstructorVariants())
    309     llvm_unreachable("shouldn't be called in this ABI");
    310 
    311   ErrorUnsupportedABI(CGF, "complete object detection in ctor");
    312   return nullptr;
    313 }
    314 
    315 bool CGCXXABI::NeedsVTTParameter(GlobalDecl GD) {
    316   return false;
    317 }
    318 
    319 llvm::CallInst *
    320 CGCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
    321                                               llvm::Value *Exn) {
    322   // Just call std::terminate and ignore the violating exception.
    323   return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
    324 }
    325 
    326 CatchTypeInfo CGCXXABI::getCatchAllTypeInfo() {
    327   return CatchTypeInfo{nullptr, 0};
    328 }
    329 
    330 std::vector<CharUnits> CGCXXABI::getVBPtrOffsets(const CXXRecordDecl *RD) {
    331   return std::vector<CharUnits>();
    332 }
    333