brintos

brintos / llvm-project-archived public Read only

0
0
Text · 11.7 KiB · 59aeff6 Raw
304 lines · cpp
1//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//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 contains code dealing with C++ code generation.10//11//===----------------------------------------------------------------------===//12 13// We might split this into multiple files if it gets too unwieldy14 15#include "CGCXXABI.h"16#include "CodeGenFunction.h"17#include "CodeGenModule.h"18#include "clang/AST/ASTContext.h"19#include "clang/AST/Attr.h"20#include "clang/AST/Decl.h"21#include "clang/AST/DeclCXX.h"22#include "clang/AST/DeclObjC.h"23#include "clang/AST/Mangle.h"24#include "clang/AST/RecordLayout.h"25#include "clang/Basic/CodeGenOptions.h"26using namespace clang;27using namespace CodeGen;28 29 30/// Try to emit a base destructor as an alias to its primary31/// base-class destructor.32bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {33  if (!getCodeGenOpts().CXXCtorDtorAliases)34    return true;35 36  // Producing an alias to a base class ctor/dtor can degrade debug quality37  // as the debugger cannot tell them apart.38  if (getCodeGenOpts().OptimizationLevel == 0)39    return true;40 41  // Disable this optimization for ARM64EC.  FIXME: This probably should work,42  // but getting the symbol table correct is complicated.43  if (getTarget().getTriple().isWindowsArm64EC())44    return true;45 46  // If sanitizing memory to check for use-after-dtor, do not emit as47  //  an alias, unless this class owns no members.48  if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&49      !D->getParent()->field_empty())50    return true;51 52  // If the destructor doesn't have a trivial body, we have to emit it53  // separately.54  if (!D->hasTrivialBody())55    return true;56 57  const CXXRecordDecl *Class = D->getParent();58 59  // We are going to instrument this destructor, so give up even if it is60  // currently empty.61  if (Class->mayInsertExtraPadding())62    return true;63 64  // If we need to manipulate a VTT parameter, give up.65  if (Class->getNumVBases()) {66    // Extra Credit:  passing extra parameters is perfectly safe67    // in many calling conventions, so only bail out if the ctor's68    // calling convention is nonstandard.69    return true;70  }71 72  // If any field has a non-trivial destructor, we have to emit the73  // destructor separately.74  for (const auto *I : Class->fields())75    if (I->getType().isDestructedType())76      return true;77 78  // Try to find a unique base class with a non-trivial destructor.79  const CXXRecordDecl *UniqueBase = nullptr;80  for (const auto &I : Class->bases()) {81 82    // We're in the base destructor, so skip virtual bases.83    if (I.isVirtual()) continue;84 85    // Skip base classes with trivial destructors.86    const auto *Base = I.getType()->castAsCXXRecordDecl();87    if (Base->hasTrivialDestructor()) continue;88 89    // If we've already found a base class with a non-trivial90    // destructor, give up.91    if (UniqueBase) return true;92    UniqueBase = Base;93  }94 95  // If we didn't find any bases with a non-trivial destructor, then96  // the base destructor is actually effectively trivial, which can97  // happen if it was needlessly user-defined or if there are virtual98  // bases with non-trivial destructors.99  if (!UniqueBase)100    return true;101 102  // If the base is at a non-zero offset, give up.103  const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);104  if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())105    return true;106 107  // Give up if the calling conventions don't match. We could update the call,108  // but it is probably not worth it.109  const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();110  if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=111      D->getType()->castAs<FunctionType>()->getCallConv())112    return true;113 114  GlobalDecl AliasDecl(D, Dtor_Base);115  GlobalDecl TargetDecl(BaseD, Dtor_Base);116 117  // The alias will use the linkage of the referent.  If we can't118  // support aliases with that linkage, fail.119  llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);120 121  // We can't use an alias if the linkage is not valid for one.122  if (!llvm::GlobalAlias::isValidLinkage(Linkage))123    return true;124 125  llvm::GlobalValue::LinkageTypes TargetLinkage =126      getFunctionLinkage(TargetDecl);127 128  // Check if we have it already.129  StringRef MangledName = getMangledName(AliasDecl);130  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);131  if (Entry && !Entry->isDeclaration())132    return false;133  if (Replacements.count(MangledName))134    return false;135 136  llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);137 138  // Find the referent.139  auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));140 141  // Instead of creating as alias to a linkonce_odr, replace all of the uses142  // of the aliasee.143  if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&144      !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&145        TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {146    // FIXME: An extern template instantiation will create functions with147    // linkage "AvailableExternally". In libc++, some classes also define148    // members with attribute "AlwaysInline" and expect no reference to149    // be generated. It is desirable to reenable this optimisation after150    // corresponding LLVM changes.151    addReplacement(MangledName, Aliasee);152    return false;153  }154 155  // If we have a weak, non-discardable alias (weak, weak_odr), like an extern156  // template instantiation or a dllexported class, avoid forming it on COFF.157  // A COFF weak external alias cannot satisfy a normal undefined symbol158  // reference from another TU. The other TU must also mark the referenced159  // symbol as weak, which we cannot rely on.160  if (llvm::GlobalValue::isWeakForLinker(Linkage) &&161      getTriple().isOSBinFormatCOFF()) {162    return true;163  }164 165  // If we don't have a definition for the destructor yet or the definition is166  // avaialable_externally, don't emit an alias.  We can't emit aliases to167  // declarations; that's just not how aliases work.168  if (Aliasee->isDeclarationForLinker())169    return true;170 171  // Don't create an alias to a linker weak symbol. This avoids producing172  // different COMDATs in different TUs. Another option would be to173  // output the alias both for weak_odr and linkonce_odr, but that174  // requires explicit comdat support in the IL.175  if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))176    return true;177 178  // Create the alias with no name.179  auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",180                                          Aliasee, &getModule());181 182  // Destructors are always unnamed_addr.183  Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);184 185  // Switch any previous uses to the alias.186  if (Entry) {187    assert(Entry->getValueType() == AliasValueType &&188           Entry->getAddressSpace() == Alias->getAddressSpace() &&189           "declaration exists with different type");190    Alias->takeName(Entry);191    Entry->replaceAllUsesWith(Alias);192    Entry->eraseFromParent();193  } else {194    Alias->setName(MangledName);195  }196 197  // Finally, set up the alias with its proper name and attributes.198  SetCommonAttributes(AliasDecl, Alias);199 200  return false;201}202 203llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {204  const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);205  auto *Fn = cast<llvm::Function>(206      getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,207                           /*DontDefer=*/true, ForDefinition));208 209  setFunctionLinkage(GD, Fn);210 211  CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);212  setNonAliasAttributes(GD, Fn);213  SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);214  return Fn;215}216 217llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(218    GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,219    bool DontDefer, ForDefinition_t IsForDefinition) {220  auto *MD = cast<CXXMethodDecl>(GD.getDecl());221 222  if (isa<CXXDestructorDecl>(MD)) {223    // Always alias equivalent complete destructors to base destructors in the224    // MS ABI.225    if (getTarget().getCXXABI().isMicrosoft() &&226        GD.getDtorType() == Dtor_Complete &&227        MD->getParent()->getNumVBases() == 0)228      GD = GD.getWithDtorType(Dtor_Base);229  }230 231  if (!FnType) {232    if (!FnInfo)233      FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);234    FnType = getTypes().GetFunctionType(*FnInfo);235  }236 237  llvm::Constant *Ptr = GetOrCreateLLVMFunction(238      getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,239      /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);240  return {FnType, Ptr};241}242 243static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,244                                          GlobalDecl GD,245                                          llvm::Type *Ty,246                                          const CXXRecordDecl *RD) {247  assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&248         "No kext in Microsoft ABI");249  CodeGenModule &CGM = CGF.CGM;250  llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());251  Ty = llvm::PointerType::getUnqual(CGM.getLLVMContext());252  assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");253  uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);254  const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);255  VTableLayout::AddressPointLocation AddressPoint =256      VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));257  VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +258                 AddressPoint.AddressPointIndex;259  llvm::Value *VFuncPtr =260    CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");261  llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(262      Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));263 264  CGPointerAuthInfo PointerAuth;265  if (auto &Schema =266          CGM.getCodeGenOpts().PointerAuth.CXXVirtualFunctionPointers) {267    GlobalDecl OrigMD =268        CGM.getItaniumVTableContext().findOriginalMethod(GD.getCanonicalDecl());269    PointerAuth = CGF.EmitPointerAuthInfo(Schema, VFuncPtr, OrigMD, QualType());270  }271 272  CGCallee Callee(GD, VFunc, PointerAuth);273  return Callee;274}275 276/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making277/// indirect call to virtual functions. It makes the call through indexing278/// into the vtable.279CGCallee CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,280                                                    NestedNameSpecifier Qual,281                                                    llvm::Type *Ty) {282  const CXXRecordDecl *RD = Qual.getAsRecordDecl();283  assert(RD && "BuildAppleKextVirtualCall - Qual must be record");284  if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))285    return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);286 287  return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);288}289 290/// BuildVirtualCall - This routine makes indirect vtable call for291/// call to virtual destructors. It returns 0 if it could not do it.292CGCallee293CodeGenFunction::BuildAppleKextVirtualDestructorCall(294                                            const CXXDestructorDecl *DD,295                                            CXXDtorType Type,296                                            const CXXRecordDecl *RD) {297  assert(DD->isVirtual() && Type != Dtor_Base);298  // Compute the function type we're calling.299  const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(300      GlobalDecl(DD, Dtor_Complete));301  llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);302  return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);303}304