Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/GlobalDCE.cpp
35294 views
//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This transform is designed to eliminate unreachable internal globals from the9// program. It uses an aggressive algorithm, searching out globals that are10// known to be alive. After it finds all of the globals which are needed, it11// deletes whatever is left over. This allows it to delete recursive chunks of12// the program which are unreachable.13//14//===----------------------------------------------------------------------===//1516#include "llvm/Transforms/IPO/GlobalDCE.h"17#include "llvm/ADT/SmallPtrSet.h"18#include "llvm/ADT/Statistic.h"19#include "llvm/Analysis/TypeMetadataUtils.h"20#include "llvm/IR/Instructions.h"21#include "llvm/IR/IntrinsicInst.h"22#include "llvm/IR/Module.h"23#include "llvm/Support/CommandLine.h"24#include "llvm/Transforms/IPO.h"25#include "llvm/Transforms/Utils/CtorUtils.h"26#include "llvm/Transforms/Utils/GlobalStatus.h"2728using namespace llvm;2930#define DEBUG_TYPE "globaldce"3132static cl::opt<bool>33ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true),34cl::desc("Enable virtual function elimination"));3536STATISTIC(NumAliases , "Number of global aliases removed");37STATISTIC(NumFunctions, "Number of functions removed");38STATISTIC(NumIFuncs, "Number of indirect functions removed");39STATISTIC(NumVariables, "Number of global variables removed");40STATISTIC(NumVFuncs, "Number of virtual functions removed");4142/// Returns true if F is effectively empty.43static bool isEmptyFunction(Function *F) {44// Skip external functions.45if (F->isDeclaration())46return false;47BasicBlock &Entry = F->getEntryBlock();48for (auto &I : Entry) {49if (I.isDebugOrPseudoInst())50continue;51if (auto *RI = dyn_cast<ReturnInst>(&I))52return !RI->getReturnValue();53break;54}55return false;56}5758/// Compute the set of GlobalValue that depends from V.59/// The recursion stops as soon as a GlobalValue is met.60void GlobalDCEPass::ComputeDependencies(Value *V,61SmallPtrSetImpl<GlobalValue *> &Deps) {62if (auto *I = dyn_cast<Instruction>(V)) {63Function *Parent = I->getParent()->getParent();64Deps.insert(Parent);65} else if (auto *GV = dyn_cast<GlobalValue>(V)) {66Deps.insert(GV);67} else if (auto *CE = dyn_cast<Constant>(V)) {68// Avoid walking the whole tree of a big ConstantExprs multiple times.69auto Where = ConstantDependenciesCache.find(CE);70if (Where != ConstantDependenciesCache.end()) {71auto const &K = Where->second;72Deps.insert(K.begin(), K.end());73} else {74SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];75for (User *CEUser : CE->users())76ComputeDependencies(CEUser, LocalDeps);77Deps.insert(LocalDeps.begin(), LocalDeps.end());78}79}80}8182void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {83SmallPtrSet<GlobalValue *, 8> Deps;84for (User *User : GV.users())85ComputeDependencies(User, Deps);86Deps.erase(&GV); // Remove self-reference.87for (GlobalValue *GVU : Deps) {88// If this is a dep from a vtable to a virtual function, and we have89// complete information about all virtual call sites which could call90// though this vtable, then skip it, because the call site information will91// be more precise.92if (VFESafeVTables.count(GVU) && isa<Function>(&GV)) {93LLVM_DEBUG(dbgs() << "Ignoring dep " << GVU->getName() << " -> "94<< GV.getName() << "\n");95continue;96}97GVDependencies[GVU].insert(&GV);98}99}100101/// Mark Global value as Live102void GlobalDCEPass::MarkLive(GlobalValue &GV,103SmallVectorImpl<GlobalValue *> *Updates) {104auto const Ret = AliveGlobals.insert(&GV);105if (!Ret.second)106return;107108if (Updates)109Updates->push_back(&GV);110if (Comdat *C = GV.getComdat()) {111for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {112MarkLive(*CM.second, Updates); // Recursion depth is only two because only113// globals in the same comdat are visited.114}115}116}117118void GlobalDCEPass::ScanVTables(Module &M) {119SmallVector<MDNode *, 2> Types;120LLVM_DEBUG(dbgs() << "Building type info -> vtable map\n");121122for (GlobalVariable &GV : M.globals()) {123Types.clear();124GV.getMetadata(LLVMContext::MD_type, Types);125if (GV.isDeclaration() || Types.empty())126continue;127128// Use the typeid metadata on the vtable to build a mapping from typeids to129// the list of (GV, offset) pairs which are the possible vtables for that130// typeid.131for (MDNode *Type : Types) {132Metadata *TypeID = Type->getOperand(1).get();133134uint64_t Offset =135cast<ConstantInt>(136cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())137->getZExtValue();138139TypeIdMap[TypeID].insert(std::make_pair(&GV, Offset));140}141142// If the type corresponding to the vtable is private to this translation143// unit, we know that we can see all virtual functions which might use it,144// so VFE is safe.145if (auto GO = dyn_cast<GlobalObject>(&GV)) {146GlobalObject::VCallVisibility TypeVis = GO->getVCallVisibility();147if (TypeVis == GlobalObject::VCallVisibilityTranslationUnit ||148(InLTOPostLink &&149TypeVis == GlobalObject::VCallVisibilityLinkageUnit)) {150LLVM_DEBUG(dbgs() << GV.getName() << " is safe for VFE\n");151VFESafeVTables.insert(&GV);152}153}154}155}156157void GlobalDCEPass::ScanVTableLoad(Function *Caller, Metadata *TypeId,158uint64_t CallOffset) {159for (const auto &VTableInfo : TypeIdMap[TypeId]) {160GlobalVariable *VTable = VTableInfo.first;161uint64_t VTableOffset = VTableInfo.second;162163Constant *Ptr =164getPointerAtOffset(VTable->getInitializer(), VTableOffset + CallOffset,165*Caller->getParent(), VTable);166if (!Ptr) {167LLVM_DEBUG(dbgs() << "can't find pointer in vtable!\n");168VFESafeVTables.erase(VTable);169continue;170}171172auto Callee = dyn_cast<Function>(Ptr->stripPointerCasts());173if (!Callee) {174LLVM_DEBUG(dbgs() << "vtable entry is not function pointer!\n");175VFESafeVTables.erase(VTable);176continue;177}178179LLVM_DEBUG(dbgs() << "vfunc dep " << Caller->getName() << " -> "180<< Callee->getName() << "\n");181GVDependencies[Caller].insert(Callee);182}183}184185void GlobalDCEPass::ScanTypeCheckedLoadIntrinsics(Module &M) {186LLVM_DEBUG(dbgs() << "Scanning type.checked.load intrinsics\n");187Function *TypeCheckedLoadFunc =188M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));189Function *TypeCheckedLoadRelativeFunc =190M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load_relative));191192auto scan = [&](Function *CheckedLoadFunc) {193if (!CheckedLoadFunc)194return;195196for (auto *U : CheckedLoadFunc->users()) {197auto CI = dyn_cast<CallInst>(U);198if (!CI)199continue;200201auto *Offset = dyn_cast<ConstantInt>(CI->getArgOperand(1));202Value *TypeIdValue = CI->getArgOperand(2);203auto *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();204205if (Offset) {206ScanVTableLoad(CI->getFunction(), TypeId, Offset->getZExtValue());207} else {208// type.checked.load with a non-constant offset, so assume every entry209// in every matching vtable is used.210for (const auto &VTableInfo : TypeIdMap[TypeId]) {211VFESafeVTables.erase(VTableInfo.first);212}213}214}215};216217scan(TypeCheckedLoadFunc);218scan(TypeCheckedLoadRelativeFunc);219}220221void GlobalDCEPass::AddVirtualFunctionDependencies(Module &M) {222if (!ClEnableVFE)223return;224225// If the Virtual Function Elim module flag is present and set to zero, then226// the vcall_visibility metadata was inserted for another optimization (WPD)227// and we may not have type checked loads on all accesses to the vtable.228// Don't attempt VFE in that case.229auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(230M.getModuleFlag("Virtual Function Elim"));231if (!Val || Val->isZero())232return;233234ScanVTables(M);235236if (VFESafeVTables.empty())237return;238239ScanTypeCheckedLoadIntrinsics(M);240241LLVM_DEBUG(242dbgs() << "VFE safe vtables:\n";243for (auto *VTable : VFESafeVTables)244dbgs() << " " << VTable->getName() << "\n";245);246}247248PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {249bool Changed = false;250251// The algorithm first computes the set L of global variables that are252// trivially live. Then it walks the initialization of these variables to253// compute the globals used to initialize them, which effectively builds a254// directed graph where nodes are global variables, and an edge from A to B255// means B is used to initialize A. Finally, it propagates the liveness256// information through the graph starting from the nodes in L. Nodes note257// marked as alive are discarded.258259// Remove empty functions from the global ctors list.260Changed |= optimizeGlobalCtorsList(261M, [](uint32_t, Function *F) { return isEmptyFunction(F); });262263// Collect the set of members for each comdat.264for (Function &F : M)265if (Comdat *C = F.getComdat())266ComdatMembers.insert(std::make_pair(C, &F));267for (GlobalVariable &GV : M.globals())268if (Comdat *C = GV.getComdat())269ComdatMembers.insert(std::make_pair(C, &GV));270for (GlobalAlias &GA : M.aliases())271if (Comdat *C = GA.getComdat())272ComdatMembers.insert(std::make_pair(C, &GA));273274// Add dependencies between virtual call sites and the virtual functions they275// might call, if we have that information.276AddVirtualFunctionDependencies(M);277278// Loop over the module, adding globals which are obviously necessary.279for (GlobalObject &GO : M.global_objects()) {280GO.removeDeadConstantUsers();281// Functions with external linkage are needed if they have a body.282// Externally visible & appending globals are needed, if they have an283// initializer.284if (!GO.isDeclaration())285if (!GO.isDiscardableIfUnused())286MarkLive(GO);287288UpdateGVDependencies(GO);289}290291// Compute direct dependencies of aliases.292for (GlobalAlias &GA : M.aliases()) {293GA.removeDeadConstantUsers();294// Externally visible aliases are needed.295if (!GA.isDiscardableIfUnused())296MarkLive(GA);297298UpdateGVDependencies(GA);299}300301// Compute direct dependencies of ifuncs.302for (GlobalIFunc &GIF : M.ifuncs()) {303GIF.removeDeadConstantUsers();304// Externally visible ifuncs are needed.305if (!GIF.isDiscardableIfUnused())306MarkLive(GIF);307308UpdateGVDependencies(GIF);309}310311// Propagate liveness from collected Global Values through the computed312// dependencies.313SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),314AliveGlobals.end()};315while (!NewLiveGVs.empty()) {316GlobalValue *LGV = NewLiveGVs.pop_back_val();317for (auto *GVD : GVDependencies[LGV])318MarkLive(*GVD, &NewLiveGVs);319}320321// Now that all globals which are needed are in the AliveGlobals set, we loop322// through the program, deleting those which are not alive.323//324325// The first pass is to drop initializers of global variables which are dead.326std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals327for (GlobalVariable &GV : M.globals())328if (!AliveGlobals.count(&GV)) {329DeadGlobalVars.push_back(&GV); // Keep track of dead globals330if (GV.hasInitializer()) {331Constant *Init = GV.getInitializer();332GV.setInitializer(nullptr);333if (isSafeToDestroyConstant(Init))334Init->destroyConstant();335}336}337338// The second pass drops the bodies of functions which are dead...339std::vector<Function *> DeadFunctions;340for (Function &F : M)341if (!AliveGlobals.count(&F)) {342DeadFunctions.push_back(&F); // Keep track of dead globals343if (!F.isDeclaration())344F.deleteBody();345}346347// The third pass drops targets of aliases which are dead...348std::vector<GlobalAlias*> DeadAliases;349for (GlobalAlias &GA : M.aliases())350if (!AliveGlobals.count(&GA)) {351DeadAliases.push_back(&GA);352GA.setAliasee(nullptr);353}354355// The fourth pass drops targets of ifuncs which are dead...356std::vector<GlobalIFunc*> DeadIFuncs;357for (GlobalIFunc &GIF : M.ifuncs())358if (!AliveGlobals.count(&GIF)) {359DeadIFuncs.push_back(&GIF);360GIF.setResolver(nullptr);361}362363// Now that all interferences have been dropped, delete the actual objects364// themselves.365auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {366GV->removeDeadConstantUsers();367GV->eraseFromParent();368Changed = true;369};370371NumFunctions += DeadFunctions.size();372for (Function *F : DeadFunctions) {373if (!F->use_empty()) {374// Virtual functions might still be referenced by one or more vtables,375// but if we've proven them to be unused then it's safe to replace the376// virtual function pointers with null, allowing us to remove the377// function itself.378++NumVFuncs;379380// Detect vfuncs that are referenced as "relative pointers" which are used381// in Swift vtables, i.e. entries in the form of:382//383// i32 trunc (i64 sub (i64 ptrtoint @f, i64 ptrtoint ...)) to i32)384//385// In this case, replace the whole "sub" expression with constant 0 to386// avoid leaving a weird sub(0, symbol) expression behind.387replaceRelativePointerUsersWithZero(F);388389F->replaceNonMetadataUsesWith(ConstantPointerNull::get(F->getType()));390}391EraseUnusedGlobalValue(F);392}393394NumVariables += DeadGlobalVars.size();395for (GlobalVariable *GV : DeadGlobalVars)396EraseUnusedGlobalValue(GV);397398NumAliases += DeadAliases.size();399for (GlobalAlias *GA : DeadAliases)400EraseUnusedGlobalValue(GA);401402NumIFuncs += DeadIFuncs.size();403for (GlobalIFunc *GIF : DeadIFuncs)404EraseUnusedGlobalValue(GIF);405406// Make sure that all memory is released407AliveGlobals.clear();408ConstantDependenciesCache.clear();409GVDependencies.clear();410ComdatMembers.clear();411TypeIdMap.clear();412VFESafeVTables.clear();413414if (Changed)415return PreservedAnalyses::none();416return PreservedAnalyses::all();417}418419void GlobalDCEPass::printPipeline(420raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {421static_cast<PassInfoMixin<GlobalDCEPass> *>(this)->printPipeline(422OS, MapClassName2PassName);423if (InLTOPostLink)424OS << "<vfe-linkage-unit-visibility>";425}426427428