357 lines · cpp
1//===----- CGCXXABI.cpp - Interface to C++ ABIs ---------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This provides an abstract class for C++ code generation. Concrete subclasses10// of this implement code generation for specific C++ ABIs.11//12//===----------------------------------------------------------------------===//13 14#include "CGCXXABI.h"15#include "CGCleanup.h"16#include "clang/AST/Attr.h"17 18using namespace clang;19using namespace CodeGen;20 21CGCXXABI::~CGCXXABI() { }22 23Address CGCXXABI::getThisAddress(CodeGenFunction &CGF) {24 return CGF.makeNaturalAddressForPointer(25 CGF.CXXABIThisValue, CGF.CXXABIThisDecl->getType()->getPointeeType(),26 CGF.CXXABIThisAlignment);27}28 29void CGCXXABI::ErrorUnsupportedABI(CodeGenFunction &CGF, StringRef S) {30 DiagnosticsEngine &Diags = CGF.CGM.getDiags();31 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,32 "cannot yet compile %0 in this ABI");33 Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()),34 DiagID)35 << S;36}37 38llvm::Constant *CGCXXABI::GetBogusMemberPointer(QualType T) {39 return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T));40}41 42llvm::Type *43CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {44 return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());45}46 47CGCallee CGCXXABI::EmitLoadOfMemberFunctionPointer(48 CodeGenFunction &CGF, const Expr *E, Address This,49 llvm::Value *&ThisPtrForCall,50 llvm::Value *MemPtr, const MemberPointerType *MPT) {51 ErrorUnsupportedABI(CGF, "calls through member pointers");52 53 const auto *RD = MPT->getMostRecentCXXRecordDecl();54 ThisPtrForCall =55 CGF.getAsNaturalPointerTo(This, CGF.getContext().getCanonicalTagType(RD));56 const FunctionProtoType *FPT =57 MPT->getPointeeType()->getAs<FunctionProtoType>();58 llvm::Constant *FnPtr = llvm::Constant::getNullValue(59 llvm::PointerType::getUnqual(CGM.getLLVMContext()));60 return CGCallee::forDirect(FnPtr, FPT);61}62 63llvm::Value *CGCXXABI::EmitMemberDataPointerAddress(64 CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,65 const MemberPointerType *MPT, bool IsInBounds) {66 ErrorUnsupportedABI(CGF, "loads of member pointers");67 llvm::Type *Ty =68 llvm::PointerType::get(CGF.getLLVMContext(), Base.getAddressSpace());69 return llvm::Constant::getNullValue(Ty);70}71 72llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,73 const CastExpr *E,74 llvm::Value *Src) {75 ErrorUnsupportedABI(CGF, "member function pointer conversions");76 return GetBogusMemberPointer(E->getType());77}78 79llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E,80 llvm::Constant *Src) {81 return GetBogusMemberPointer(E->getType());82}83 84llvm::Value *85CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,86 llvm::Value *L,87 llvm::Value *R,88 const MemberPointerType *MPT,89 bool Inequality) {90 ErrorUnsupportedABI(CGF, "member function pointer comparison");91 return CGF.Builder.getFalse();92}93 94llvm::Value *95CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,96 llvm::Value *MemPtr,97 const MemberPointerType *MPT) {98 ErrorUnsupportedABI(CGF, "member function pointer null testing");99 return CGF.Builder.getFalse();100}101 102llvm::Constant *103CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {104 return GetBogusMemberPointer(QualType(MPT, 0));105}106 107llvm::Constant *CGCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {108 return GetBogusMemberPointer(CGM.getContext().getMemberPointerType(109 MD->getType(), /*Qualifier=*/std::nullopt, MD->getParent()));110}111 112llvm::Constant *CGCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,113 CharUnits offset) {114 return GetBogusMemberPointer(QualType(MPT, 0));115}116 117llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {118 return GetBogusMemberPointer(MPT);119}120 121bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) {122 // Fake answer.123 return true;124}125 126void CGCXXABI::buildThisParam(CodeGenFunction &CGF, FunctionArgList ¶ms) {127 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());128 129 // FIXME: I'm not entirely sure I like using a fake decl just for code130 // generation. Maybe we can come up with a better way?131 auto *ThisDecl =132 ImplicitParamDecl::Create(CGM.getContext(), nullptr, MD->getLocation(),133 &CGM.getContext().Idents.get("this"),134 MD->getThisType(), ImplicitParamKind::CXXThis);135 params.push_back(ThisDecl);136 CGF.CXXABIThisDecl = ThisDecl;137 138 // Compute the presumed alignment of 'this', which basically comes139 // down to whether we know it's a complete object or not.140 auto &Layout = CGF.getContext().getASTRecordLayout(MD->getParent());141 if (MD->getParent()->getNumVBases() == 0 || // avoid vcall in common case142 MD->getParent()->isEffectivelyFinal() ||143 isThisCompleteObject(CGF.CurGD)) {144 CGF.CXXABIThisAlignment = Layout.getAlignment();145 } else {146 CGF.CXXABIThisAlignment = Layout.getNonVirtualAlignment();147 }148}149 150llvm::Value *CGCXXABI::loadIncomingCXXThis(CodeGenFunction &CGF) {151 return CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)),152 "this");153}154 155void CGCXXABI::setCXXABIThisValue(CodeGenFunction &CGF, llvm::Value *ThisPtr) {156 /// Initialize the 'this' slot.157 assert(getThisDecl(CGF) && "no 'this' variable for function");158 CGF.CXXABIThisValue = ThisPtr;159}160 161bool CGCXXABI::mayNeedDestruction(const VarDecl *VD) const {162 if (VD->needsDestruction(getContext()))163 return true;164 165 // If the variable has an incomplete class type (or array thereof), it166 // might need destruction.167 const Type *T = VD->getType()->getBaseElementTypeUnsafe();168 return T->isRecordType() && T->isIncompleteType();169}170 171bool CGCXXABI::isEmittedWithConstantInitializer(172 const VarDecl *VD, bool InspectInitForWeakDef) const {173 VD = VD->getMostRecentDecl();174 if (VD->hasAttr<ConstInitAttr>())175 return true;176 177 // All later checks examine the initializer specified on the variable. If178 // the variable is weak, such examination would not be correct.179 if (!InspectInitForWeakDef && (VD->isWeak() || VD->hasAttr<SelectAnyAttr>()))180 return false;181 182 const VarDecl *InitDecl = VD->getInitializingDeclaration();183 if (!InitDecl)184 return false;185 186 // If there's no initializer to run, this is constant initialization.187 if (!InitDecl->hasInit())188 return true;189 190 // If we have the only definition, we don't need a thread wrapper if we191 // will emit the value as a constant.192 if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))193 return !mayNeedDestruction(VD) && InitDecl->evaluateValue();194 195 // Otherwise, we need a thread wrapper unless we know that every196 // translation unit will emit the value as a constant. We rely on the197 // variable being constant-initialized in every translation unit if it's198 // constant-initialized in any translation unit, which isn't actually199 // guaranteed by the standard but is necessary for sanity.200 return InitDecl->hasConstantInitialization();201}202 203void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,204 RValue RV, QualType ResultType) {205 assert(!CGF.hasAggregateEvaluationKind(ResultType) &&206 "cannot handle aggregates");207 CGF.EmitReturnOfRValue(RV, ResultType);208}209 210CharUnits CGCXXABI::GetArrayCookieSize(const CXXNewExpr *expr) {211 if (!requiresArrayCookie(expr))212 return CharUnits::Zero();213 return getArrayCookieSizeImpl(expr->getAllocatedType());214}215 216CharUnits CGCXXABI::getArrayCookieSizeImpl(QualType elementType) {217 // BOGUS218 return CharUnits::Zero();219}220 221Address CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,222 Address NewPtr,223 llvm::Value *NumElements,224 const CXXNewExpr *expr,225 QualType ElementType) {226 // Should never be called.227 ErrorUnsupportedABI(CGF, "array cookie initialization");228 return Address::invalid();229}230 231bool CGCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,232 QualType elementType) {233 // If the class's usual deallocation function takes two arguments,234 // it needs a cookie.235 if (expr->doesUsualArrayDeleteWantSize())236 return true;237 238 return elementType.isDestructedType();239}240 241bool CGCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {242 // If the class's usual deallocation function takes two arguments,243 // it needs a cookie.244 if (expr->doesUsualArrayDeleteWantSize())245 return true;246 247 return expr->getAllocatedType().isDestructedType();248}249 250void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, Address ptr,251 const CXXDeleteExpr *expr, QualType eltTy,252 llvm::Value *&numElements,253 llvm::Value *&allocPtr, CharUnits &cookieSize) {254 // Derive a char* in the same address space as the pointer.255 ptr = ptr.withElementType(CGF.Int8Ty);256 257 // If we don't need an array cookie, bail out early.258 if (!requiresArrayCookie(expr, eltTy)) {259 allocPtr = ptr.emitRawPointer(CGF);260 numElements = nullptr;261 cookieSize = CharUnits::Zero();262 return;263 }264 265 cookieSize = getArrayCookieSizeImpl(eltTy);266 Address allocAddr = CGF.Builder.CreateConstInBoundsByteGEP(ptr, -cookieSize);267 allocPtr = allocAddr.emitRawPointer(CGF);268 numElements = readArrayCookieImpl(CGF, allocAddr, cookieSize);269}270 271llvm::Value *CGCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,272 Address ptr,273 CharUnits cookieSize) {274 ErrorUnsupportedABI(CGF, "reading a new[] cookie");275 return llvm::ConstantInt::get(CGF.SizeTy, 0);276}277 278/// Returns the adjustment, in bytes, required for the given279/// member-pointer operation. Returns null if no adjustment is280/// required.281llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) {282 assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||283 E->getCastKind() == CK_BaseToDerivedMemberPointer);284 285 QualType derivedType;286 if (E->getCastKind() == CK_DerivedToBaseMemberPointer)287 derivedType = E->getSubExpr()->getType();288 else289 derivedType = E->getType();290 291 const CXXRecordDecl *derivedClass =292 derivedType->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();293 294 return CGM.GetNonVirtualBaseClassOffset(derivedClass,295 E->path_begin(),296 E->path_end());297}298 299llvm::BasicBlock *300CGCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,301 const CXXRecordDecl *RD) {302 if (CGM.getTarget().getCXXABI().hasConstructorVariants())303 llvm_unreachable("shouldn't be called in this ABI");304 305 ErrorUnsupportedABI(CGF, "complete object detection in ctor");306 return nullptr;307}308 309void CGCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,310 const CXXDestructorDecl *Dtor,311 CXXDtorType DT) const {312 // Assume the base C++ ABI has no special rules for destructor variants.313 CGM.setDLLImportDLLExport(GV, Dtor);314}315 316llvm::GlobalValue::LinkageTypes CGCXXABI::getCXXDestructorLinkage(317 GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {318 // Delegate back to CGM by default.319 return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage);320}321 322bool CGCXXABI::NeedsVTTParameter(GlobalDecl GD) {323 return false;324}325 326llvm::CallInst *327CGCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,328 llvm::Value *Exn) {329 // Just call std::terminate and ignore the violating exception.330 return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());331}332 333CatchTypeInfo CGCXXABI::getCatchAllTypeInfo() {334 return CatchTypeInfo{nullptr, 0};335}336 337std::vector<CharUnits> CGCXXABI::getVBPtrOffsets(const CXXRecordDecl *RD) {338 return std::vector<CharUnits>();339}340 341CGCXXABI::AddedStructorArgCounts CGCXXABI::addImplicitConstructorArgs(342 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,343 bool ForVirtualBase, bool Delegating, CallArgList &Args) {344 AddedStructorArgs AddedArgs =345 getImplicitConstructorArgs(CGF, D, Type, ForVirtualBase, Delegating);346 for (size_t i = 0; i < AddedArgs.Prefix.size(); ++i) {347 Args.insert(Args.begin() + 1 + i,348 CallArg(RValue::get(AddedArgs.Prefix[i].Value),349 AddedArgs.Prefix[i].Type));350 }351 for (const auto &arg : AddedArgs.Suffix) {352 Args.add(RValue::get(arg.Value), arg.Type);353 }354 return AddedStructorArgCounts(AddedArgs.Prefix.size(),355 AddedArgs.Suffix.size());356}357