17330f729Sjoerg //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This contains code dealing with C++ code generation.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg // We might split this into multiple files if it gets too unwieldy
147330f729Sjoerg
157330f729Sjoerg #include "CGCXXABI.h"
167330f729Sjoerg #include "CodeGenFunction.h"
17*e038c9c4Sjoerg #include "CodeGenModule.h"
187330f729Sjoerg #include "clang/AST/ASTContext.h"
19*e038c9c4Sjoerg #include "clang/AST/Attr.h"
207330f729Sjoerg #include "clang/AST/Decl.h"
217330f729Sjoerg #include "clang/AST/DeclCXX.h"
227330f729Sjoerg #include "clang/AST/DeclObjC.h"
237330f729Sjoerg #include "clang/AST/Mangle.h"
247330f729Sjoerg #include "clang/AST/RecordLayout.h"
257330f729Sjoerg #include "clang/AST/StmtCXX.h"
267330f729Sjoerg #include "clang/Basic/CodeGenOptions.h"
277330f729Sjoerg #include "llvm/ADT/StringExtras.h"
287330f729Sjoerg using namespace clang;
297330f729Sjoerg using namespace CodeGen;
307330f729Sjoerg
317330f729Sjoerg
327330f729Sjoerg /// Try to emit a base destructor as an alias to its primary
337330f729Sjoerg /// base-class destructor.
TryEmitBaseDestructorAsAlias(const CXXDestructorDecl * D)347330f729Sjoerg bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
357330f729Sjoerg if (!getCodeGenOpts().CXXCtorDtorAliases)
367330f729Sjoerg return true;
377330f729Sjoerg
387330f729Sjoerg // Producing an alias to a base class ctor/dtor can degrade debug quality
397330f729Sjoerg // as the debugger cannot tell them apart.
407330f729Sjoerg if (getCodeGenOpts().OptimizationLevel == 0)
417330f729Sjoerg return true;
427330f729Sjoerg
437330f729Sjoerg // If sanitizing memory to check for use-after-dtor, do not emit as
447330f729Sjoerg // an alias, unless this class owns no members.
457330f729Sjoerg if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
467330f729Sjoerg !D->getParent()->field_empty())
477330f729Sjoerg return true;
487330f729Sjoerg
497330f729Sjoerg // If the destructor doesn't have a trivial body, we have to emit it
507330f729Sjoerg // separately.
517330f729Sjoerg if (!D->hasTrivialBody())
527330f729Sjoerg return true;
537330f729Sjoerg
547330f729Sjoerg const CXXRecordDecl *Class = D->getParent();
557330f729Sjoerg
567330f729Sjoerg // We are going to instrument this destructor, so give up even if it is
577330f729Sjoerg // currently empty.
587330f729Sjoerg if (Class->mayInsertExtraPadding())
597330f729Sjoerg return true;
607330f729Sjoerg
617330f729Sjoerg // If we need to manipulate a VTT parameter, give up.
627330f729Sjoerg if (Class->getNumVBases()) {
637330f729Sjoerg // Extra Credit: passing extra parameters is perfectly safe
647330f729Sjoerg // in many calling conventions, so only bail out if the ctor's
657330f729Sjoerg // calling convention is nonstandard.
667330f729Sjoerg return true;
677330f729Sjoerg }
687330f729Sjoerg
697330f729Sjoerg // If any field has a non-trivial destructor, we have to emit the
707330f729Sjoerg // destructor separately.
717330f729Sjoerg for (const auto *I : Class->fields())
727330f729Sjoerg if (I->getType().isDestructedType())
737330f729Sjoerg return true;
747330f729Sjoerg
757330f729Sjoerg // Try to find a unique base class with a non-trivial destructor.
767330f729Sjoerg const CXXRecordDecl *UniqueBase = nullptr;
777330f729Sjoerg for (const auto &I : Class->bases()) {
787330f729Sjoerg
797330f729Sjoerg // We're in the base destructor, so skip virtual bases.
807330f729Sjoerg if (I.isVirtual()) continue;
817330f729Sjoerg
827330f729Sjoerg // Skip base classes with trivial destructors.
837330f729Sjoerg const auto *Base =
847330f729Sjoerg cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
857330f729Sjoerg if (Base->hasTrivialDestructor()) continue;
867330f729Sjoerg
877330f729Sjoerg // If we've already found a base class with a non-trivial
887330f729Sjoerg // destructor, give up.
897330f729Sjoerg if (UniqueBase) return true;
907330f729Sjoerg UniqueBase = Base;
917330f729Sjoerg }
927330f729Sjoerg
937330f729Sjoerg // If we didn't find any bases with a non-trivial destructor, then
947330f729Sjoerg // the base destructor is actually effectively trivial, which can
957330f729Sjoerg // happen if it was needlessly user-defined or if there are virtual
967330f729Sjoerg // bases with non-trivial destructors.
977330f729Sjoerg if (!UniqueBase)
987330f729Sjoerg return true;
997330f729Sjoerg
1007330f729Sjoerg // If the base is at a non-zero offset, give up.
1017330f729Sjoerg const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
1027330f729Sjoerg if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
1037330f729Sjoerg return true;
1047330f729Sjoerg
1057330f729Sjoerg // Give up if the calling conventions don't match. We could update the call,
1067330f729Sjoerg // but it is probably not worth it.
1077330f729Sjoerg const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
1087330f729Sjoerg if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
1097330f729Sjoerg D->getType()->castAs<FunctionType>()->getCallConv())
1107330f729Sjoerg return true;
1117330f729Sjoerg
1127330f729Sjoerg GlobalDecl AliasDecl(D, Dtor_Base);
1137330f729Sjoerg GlobalDecl TargetDecl(BaseD, Dtor_Base);
1147330f729Sjoerg
1157330f729Sjoerg // The alias will use the linkage of the referent. If we can't
1167330f729Sjoerg // support aliases with that linkage, fail.
1177330f729Sjoerg llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
1187330f729Sjoerg
1197330f729Sjoerg // We can't use an alias if the linkage is not valid for one.
1207330f729Sjoerg if (!llvm::GlobalAlias::isValidLinkage(Linkage))
1217330f729Sjoerg return true;
1227330f729Sjoerg
1237330f729Sjoerg llvm::GlobalValue::LinkageTypes TargetLinkage =
1247330f729Sjoerg getFunctionLinkage(TargetDecl);
1257330f729Sjoerg
1267330f729Sjoerg // Check if we have it already.
1277330f729Sjoerg StringRef MangledName = getMangledName(AliasDecl);
1287330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1297330f729Sjoerg if (Entry && !Entry->isDeclaration())
1307330f729Sjoerg return false;
1317330f729Sjoerg if (Replacements.count(MangledName))
1327330f729Sjoerg return false;
1337330f729Sjoerg
1347330f729Sjoerg // Derive the type for the alias.
1357330f729Sjoerg llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
1367330f729Sjoerg llvm::PointerType *AliasType = AliasValueType->getPointerTo();
1377330f729Sjoerg
1387330f729Sjoerg // Find the referent. Some aliases might require a bitcast, in
1397330f729Sjoerg // which case the caller is responsible for ensuring the soundness
1407330f729Sjoerg // of these semantics.
1417330f729Sjoerg auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
1427330f729Sjoerg llvm::Constant *Aliasee = Ref;
1437330f729Sjoerg if (Ref->getType() != AliasType)
1447330f729Sjoerg Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
1457330f729Sjoerg
1467330f729Sjoerg // Instead of creating as alias to a linkonce_odr, replace all of the uses
1477330f729Sjoerg // of the aliasee.
1487330f729Sjoerg if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
1497330f729Sjoerg !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
1507330f729Sjoerg TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
1517330f729Sjoerg // FIXME: An extern template instantiation will create functions with
1527330f729Sjoerg // linkage "AvailableExternally". In libc++, some classes also define
1537330f729Sjoerg // members with attribute "AlwaysInline" and expect no reference to
1547330f729Sjoerg // be generated. It is desirable to reenable this optimisation after
1557330f729Sjoerg // corresponding LLVM changes.
1567330f729Sjoerg addReplacement(MangledName, Aliasee);
1577330f729Sjoerg return false;
1587330f729Sjoerg }
1597330f729Sjoerg
1607330f729Sjoerg // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
1617330f729Sjoerg // template instantiation or a dllexported class, avoid forming it on COFF.
1627330f729Sjoerg // A COFF weak external alias cannot satisfy a normal undefined symbol
1637330f729Sjoerg // reference from another TU. The other TU must also mark the referenced
1647330f729Sjoerg // symbol as weak, which we cannot rely on.
1657330f729Sjoerg if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
1667330f729Sjoerg getTriple().isOSBinFormatCOFF()) {
1677330f729Sjoerg return true;
1687330f729Sjoerg }
1697330f729Sjoerg
1707330f729Sjoerg // If we don't have a definition for the destructor yet or the definition is
1717330f729Sjoerg // avaialable_externally, don't emit an alias. We can't emit aliases to
1727330f729Sjoerg // declarations; that's just not how aliases work.
1737330f729Sjoerg if (Ref->isDeclarationForLinker())
1747330f729Sjoerg return true;
1757330f729Sjoerg
1767330f729Sjoerg // Don't create an alias to a linker weak symbol. This avoids producing
1777330f729Sjoerg // different COMDATs in different TUs. Another option would be to
1787330f729Sjoerg // output the alias both for weak_odr and linkonce_odr, but that
1797330f729Sjoerg // requires explicit comdat support in the IL.
1807330f729Sjoerg if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
1817330f729Sjoerg return true;
1827330f729Sjoerg
1837330f729Sjoerg // Create the alias with no name.
1847330f729Sjoerg auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
1857330f729Sjoerg Aliasee, &getModule());
1867330f729Sjoerg
1877330f729Sjoerg // Destructors are always unnamed_addr.
1887330f729Sjoerg Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1897330f729Sjoerg
1907330f729Sjoerg // Switch any previous uses to the alias.
1917330f729Sjoerg if (Entry) {
1927330f729Sjoerg assert(Entry->getType() == AliasType &&
1937330f729Sjoerg "declaration exists with different type");
1947330f729Sjoerg Alias->takeName(Entry);
1957330f729Sjoerg Entry->replaceAllUsesWith(Alias);
1967330f729Sjoerg Entry->eraseFromParent();
1977330f729Sjoerg } else {
1987330f729Sjoerg Alias->setName(MangledName);
1997330f729Sjoerg }
2007330f729Sjoerg
2017330f729Sjoerg // Finally, set up the alias with its proper name and attributes.
2027330f729Sjoerg SetCommonAttributes(AliasDecl, Alias);
2037330f729Sjoerg
2047330f729Sjoerg return false;
2057330f729Sjoerg }
2067330f729Sjoerg
codegenCXXStructor(GlobalDecl GD)2077330f729Sjoerg llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
2087330f729Sjoerg const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
2097330f729Sjoerg auto *Fn = cast<llvm::Function>(
2107330f729Sjoerg getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
2117330f729Sjoerg /*DontDefer=*/true, ForDefinition));
2127330f729Sjoerg
2137330f729Sjoerg setFunctionLinkage(GD, Fn);
2147330f729Sjoerg
2157330f729Sjoerg CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
2167330f729Sjoerg setNonAliasAttributes(GD, Fn);
2177330f729Sjoerg SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
2187330f729Sjoerg return Fn;
2197330f729Sjoerg }
2207330f729Sjoerg
getAddrAndTypeOfCXXStructor(GlobalDecl GD,const CGFunctionInfo * FnInfo,llvm::FunctionType * FnType,bool DontDefer,ForDefinition_t IsForDefinition)2217330f729Sjoerg llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
2227330f729Sjoerg GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
2237330f729Sjoerg bool DontDefer, ForDefinition_t IsForDefinition) {
2247330f729Sjoerg auto *MD = cast<CXXMethodDecl>(GD.getDecl());
2257330f729Sjoerg
2267330f729Sjoerg if (isa<CXXDestructorDecl>(MD)) {
2277330f729Sjoerg // Always alias equivalent complete destructors to base destructors in the
2287330f729Sjoerg // MS ABI.
2297330f729Sjoerg if (getTarget().getCXXABI().isMicrosoft() &&
2307330f729Sjoerg GD.getDtorType() == Dtor_Complete &&
2317330f729Sjoerg MD->getParent()->getNumVBases() == 0)
2327330f729Sjoerg GD = GD.getWithDtorType(Dtor_Base);
2337330f729Sjoerg }
2347330f729Sjoerg
2357330f729Sjoerg if (!FnType) {
2367330f729Sjoerg if (!FnInfo)
2377330f729Sjoerg FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
2387330f729Sjoerg FnType = getTypes().GetFunctionType(*FnInfo);
2397330f729Sjoerg }
2407330f729Sjoerg
2417330f729Sjoerg llvm::Constant *Ptr = GetOrCreateLLVMFunction(
2427330f729Sjoerg getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
2437330f729Sjoerg /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
2447330f729Sjoerg return {FnType, Ptr};
2457330f729Sjoerg }
2467330f729Sjoerg
BuildAppleKextVirtualCall(CodeGenFunction & CGF,GlobalDecl GD,llvm::Type * Ty,const CXXRecordDecl * RD)2477330f729Sjoerg static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
2487330f729Sjoerg GlobalDecl GD,
2497330f729Sjoerg llvm::Type *Ty,
2507330f729Sjoerg const CXXRecordDecl *RD) {
2517330f729Sjoerg assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
2527330f729Sjoerg "No kext in Microsoft ABI");
2537330f729Sjoerg CodeGenModule &CGM = CGF.CGM;
2547330f729Sjoerg llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
255*e038c9c4Sjoerg Ty = Ty->getPointerTo();
256*e038c9c4Sjoerg VTable = CGF.Builder.CreateBitCast(VTable, Ty->getPointerTo());
2577330f729Sjoerg assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
2587330f729Sjoerg uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
2597330f729Sjoerg const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
2607330f729Sjoerg VTableLayout::AddressPointLocation AddressPoint =
2617330f729Sjoerg VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
2627330f729Sjoerg VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
2637330f729Sjoerg AddressPoint.AddressPointIndex;
2647330f729Sjoerg llvm::Value *VFuncPtr =
2657330f729Sjoerg CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
266*e038c9c4Sjoerg llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
267*e038c9c4Sjoerg Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
2687330f729Sjoerg CGCallee Callee(GD, VFunc);
2697330f729Sjoerg return Callee;
2707330f729Sjoerg }
2717330f729Sjoerg
2727330f729Sjoerg /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
2737330f729Sjoerg /// indirect call to virtual functions. It makes the call through indexing
2747330f729Sjoerg /// into the vtable.
2757330f729Sjoerg CGCallee
BuildAppleKextVirtualCall(const CXXMethodDecl * MD,NestedNameSpecifier * Qual,llvm::Type * Ty)2767330f729Sjoerg CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
2777330f729Sjoerg NestedNameSpecifier *Qual,
2787330f729Sjoerg llvm::Type *Ty) {
2797330f729Sjoerg assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
2807330f729Sjoerg "BuildAppleKextVirtualCall - bad Qual kind");
2817330f729Sjoerg
2827330f729Sjoerg const Type *QTy = Qual->getAsType();
2837330f729Sjoerg QualType T = QualType(QTy, 0);
2847330f729Sjoerg const RecordType *RT = T->getAs<RecordType>();
2857330f729Sjoerg assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
2867330f729Sjoerg const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
2877330f729Sjoerg
2887330f729Sjoerg if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
2897330f729Sjoerg return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
2907330f729Sjoerg
2917330f729Sjoerg return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
2927330f729Sjoerg }
2937330f729Sjoerg
2947330f729Sjoerg /// BuildVirtualCall - This routine makes indirect vtable call for
2957330f729Sjoerg /// call to virtual destructors. It returns 0 if it could not do it.
2967330f729Sjoerg CGCallee
BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl * DD,CXXDtorType Type,const CXXRecordDecl * RD)2977330f729Sjoerg CodeGenFunction::BuildAppleKextVirtualDestructorCall(
2987330f729Sjoerg const CXXDestructorDecl *DD,
2997330f729Sjoerg CXXDtorType Type,
3007330f729Sjoerg const CXXRecordDecl *RD) {
3017330f729Sjoerg assert(DD->isVirtual() && Type != Dtor_Base);
3027330f729Sjoerg // Compute the function type we're calling.
3037330f729Sjoerg const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
3047330f729Sjoerg GlobalDecl(DD, Dtor_Complete));
3057330f729Sjoerg llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
3067330f729Sjoerg return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
3077330f729Sjoerg }
308