xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/GlobalDCE.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This transform is designed to eliminate unreachable internal globals from the
100b57cec5SDimitry Andric // program.  It uses an aggressive algorithm, searching out globals that are
110b57cec5SDimitry Andric // known to be alive.  After it finds all of the globals which are needed, it
120b57cec5SDimitry Andric // deletes whatever is left over.  This allows it to delete recursive chunks of
130b57cec5SDimitry Andric // the program which are unreachable.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "llvm/Transforms/IPO/GlobalDCE.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
208bcb0991SDimitry Andric #include "llvm/Analysis/TypeMetadataUtils.h"
210b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
220b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
230b57cec5SDimitry Andric #include "llvm/IR/Module.h"
24480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
250b57cec5SDimitry Andric #include "llvm/Transforms/IPO.h"
260b57cec5SDimitry Andric #include "llvm/Transforms/Utils/CtorUtils.h"
270b57cec5SDimitry Andric #include "llvm/Transforms/Utils/GlobalStatus.h"
280b57cec5SDimitry Andric 
290b57cec5SDimitry Andric using namespace llvm;
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric #define DEBUG_TYPE "globaldce"
320b57cec5SDimitry Andric 
338bcb0991SDimitry Andric static cl::opt<bool>
3481ad6265SDimitry Andric     ClEnableVFE("enable-vfe", cl::Hidden, cl::init(true),
358bcb0991SDimitry Andric                 cl::desc("Enable virtual function elimination"));
368bcb0991SDimitry Andric 
370b57cec5SDimitry Andric STATISTIC(NumAliases  , "Number of global aliases removed");
380b57cec5SDimitry Andric STATISTIC(NumFunctions, "Number of functions removed");
390b57cec5SDimitry Andric STATISTIC(NumIFuncs,    "Number of indirect functions removed");
400b57cec5SDimitry Andric STATISTIC(NumVariables, "Number of global variables removed");
418bcb0991SDimitry Andric STATISTIC(NumVFuncs,    "Number of virtual functions removed");
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric /// Returns true if F is effectively empty.
isEmptyFunction(Function * F)440b57cec5SDimitry Andric static bool isEmptyFunction(Function *F) {
4581ad6265SDimitry Andric   // Skip external functions.
4681ad6265SDimitry Andric   if (F->isDeclaration())
4781ad6265SDimitry Andric     return false;
480b57cec5SDimitry Andric   BasicBlock &Entry = F->getEntryBlock();
490b57cec5SDimitry Andric   for (auto &I : Entry) {
50349cc55cSDimitry Andric     if (I.isDebugOrPseudoInst())
510b57cec5SDimitry Andric       continue;
520b57cec5SDimitry Andric     if (auto *RI = dyn_cast<ReturnInst>(&I))
530b57cec5SDimitry Andric       return !RI->getReturnValue();
540b57cec5SDimitry Andric     break;
550b57cec5SDimitry Andric   }
560b57cec5SDimitry Andric   return false;
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric /// Compute the set of GlobalValue that depends from V.
600b57cec5SDimitry Andric /// The recursion stops as soon as a GlobalValue is met.
ComputeDependencies(Value * V,SmallPtrSetImpl<GlobalValue * > & Deps)610b57cec5SDimitry Andric void GlobalDCEPass::ComputeDependencies(Value *V,
620b57cec5SDimitry Andric                                         SmallPtrSetImpl<GlobalValue *> &Deps) {
630b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(V)) {
640b57cec5SDimitry Andric     Function *Parent = I->getParent()->getParent();
650b57cec5SDimitry Andric     Deps.insert(Parent);
660b57cec5SDimitry Andric   } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
670b57cec5SDimitry Andric     Deps.insert(GV);
680b57cec5SDimitry Andric   } else if (auto *CE = dyn_cast<Constant>(V)) {
690b57cec5SDimitry Andric     // Avoid walking the whole tree of a big ConstantExprs multiple times.
700b57cec5SDimitry Andric     auto Where = ConstantDependenciesCache.find(CE);
710b57cec5SDimitry Andric     if (Where != ConstantDependenciesCache.end()) {
720b57cec5SDimitry Andric       auto const &K = Where->second;
730b57cec5SDimitry Andric       Deps.insert(K.begin(), K.end());
740b57cec5SDimitry Andric     } else {
750b57cec5SDimitry Andric       SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
760b57cec5SDimitry Andric       for (User *CEUser : CE->users())
770b57cec5SDimitry Andric         ComputeDependencies(CEUser, LocalDeps);
780b57cec5SDimitry Andric       Deps.insert(LocalDeps.begin(), LocalDeps.end());
790b57cec5SDimitry Andric     }
800b57cec5SDimitry Andric   }
810b57cec5SDimitry Andric }
820b57cec5SDimitry Andric 
UpdateGVDependencies(GlobalValue & GV)830b57cec5SDimitry Andric void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
840b57cec5SDimitry Andric   SmallPtrSet<GlobalValue *, 8> Deps;
850b57cec5SDimitry Andric   for (User *User : GV.users())
860b57cec5SDimitry Andric     ComputeDependencies(User, Deps);
870b57cec5SDimitry Andric   Deps.erase(&GV); // Remove self-reference.
880b57cec5SDimitry Andric   for (GlobalValue *GVU : Deps) {
898bcb0991SDimitry Andric     // If this is a dep from a vtable to a virtual function, and we have
908bcb0991SDimitry Andric     // complete information about all virtual call sites which could call
918bcb0991SDimitry Andric     // though this vtable, then skip it, because the call site information will
928bcb0991SDimitry Andric     // be more precise.
938bcb0991SDimitry Andric     if (VFESafeVTables.count(GVU) && isa<Function>(&GV)) {
948bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "Ignoring dep " << GVU->getName() << " -> "
958bcb0991SDimitry Andric                         << GV.getName() << "\n");
968bcb0991SDimitry Andric       continue;
978bcb0991SDimitry Andric     }
980b57cec5SDimitry Andric     GVDependencies[GVU].insert(&GV);
990b57cec5SDimitry Andric   }
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric /// Mark Global value as Live
MarkLive(GlobalValue & GV,SmallVectorImpl<GlobalValue * > * Updates)1030b57cec5SDimitry Andric void GlobalDCEPass::MarkLive(GlobalValue &GV,
1040b57cec5SDimitry Andric                              SmallVectorImpl<GlobalValue *> *Updates) {
1050b57cec5SDimitry Andric   auto const Ret = AliveGlobals.insert(&GV);
1060b57cec5SDimitry Andric   if (!Ret.second)
1070b57cec5SDimitry Andric     return;
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   if (Updates)
1100b57cec5SDimitry Andric     Updates->push_back(&GV);
1110b57cec5SDimitry Andric   if (Comdat *C = GV.getComdat()) {
1128bcb0991SDimitry Andric     for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
1130b57cec5SDimitry Andric       MarkLive(*CM.second, Updates); // Recursion depth is only two because only
1140b57cec5SDimitry Andric                                      // globals in the same comdat are visited.
1150b57cec5SDimitry Andric     }
1160b57cec5SDimitry Andric   }
1178bcb0991SDimitry Andric }
1188bcb0991SDimitry Andric 
ScanVTables(Module & M)1198bcb0991SDimitry Andric void GlobalDCEPass::ScanVTables(Module &M) {
1208bcb0991SDimitry Andric   SmallVector<MDNode *, 2> Types;
1218bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Building type info -> vtable map\n");
1228bcb0991SDimitry Andric 
1238bcb0991SDimitry Andric   for (GlobalVariable &GV : M.globals()) {
1248bcb0991SDimitry Andric     Types.clear();
1258bcb0991SDimitry Andric     GV.getMetadata(LLVMContext::MD_type, Types);
1268bcb0991SDimitry Andric     if (GV.isDeclaration() || Types.empty())
1278bcb0991SDimitry Andric       continue;
1288bcb0991SDimitry Andric 
1298bcb0991SDimitry Andric     // Use the typeid metadata on the vtable to build a mapping from typeids to
1308bcb0991SDimitry Andric     // the list of (GV, offset) pairs which are the possible vtables for that
1318bcb0991SDimitry Andric     // typeid.
1328bcb0991SDimitry Andric     for (MDNode *Type : Types) {
1338bcb0991SDimitry Andric       Metadata *TypeID = Type->getOperand(1).get();
1348bcb0991SDimitry Andric 
1358bcb0991SDimitry Andric       uint64_t Offset =
1368bcb0991SDimitry Andric           cast<ConstantInt>(
1378bcb0991SDimitry Andric               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
1388bcb0991SDimitry Andric               ->getZExtValue();
1398bcb0991SDimitry Andric 
1408bcb0991SDimitry Andric       TypeIdMap[TypeID].insert(std::make_pair(&GV, Offset));
1418bcb0991SDimitry Andric     }
1428bcb0991SDimitry Andric 
1438bcb0991SDimitry Andric     // If the type corresponding to the vtable is private to this translation
1448bcb0991SDimitry Andric     // unit, we know that we can see all virtual functions which might use it,
1458bcb0991SDimitry Andric     // so VFE is safe.
1468bcb0991SDimitry Andric     if (auto GO = dyn_cast<GlobalObject>(&GV)) {
1478bcb0991SDimitry Andric       GlobalObject::VCallVisibility TypeVis = GO->getVCallVisibility();
1488bcb0991SDimitry Andric       if (TypeVis == GlobalObject::VCallVisibilityTranslationUnit ||
149*06c3fb27SDimitry Andric           (InLTOPostLink &&
1508bcb0991SDimitry Andric            TypeVis == GlobalObject::VCallVisibilityLinkageUnit)) {
1518bcb0991SDimitry Andric         LLVM_DEBUG(dbgs() << GV.getName() << " is safe for VFE\n");
1528bcb0991SDimitry Andric         VFESafeVTables.insert(&GV);
1538bcb0991SDimitry Andric       }
1548bcb0991SDimitry Andric     }
1558bcb0991SDimitry Andric   }
1568bcb0991SDimitry Andric }
1578bcb0991SDimitry Andric 
ScanVTableLoad(Function * Caller,Metadata * TypeId,uint64_t CallOffset)1588bcb0991SDimitry Andric void GlobalDCEPass::ScanVTableLoad(Function *Caller, Metadata *TypeId,
1598bcb0991SDimitry Andric                                    uint64_t CallOffset) {
160bdd1243dSDimitry Andric   for (const auto &VTableInfo : TypeIdMap[TypeId]) {
1618bcb0991SDimitry Andric     GlobalVariable *VTable = VTableInfo.first;
1628bcb0991SDimitry Andric     uint64_t VTableOffset = VTableInfo.second;
1638bcb0991SDimitry Andric 
1648bcb0991SDimitry Andric     Constant *Ptr =
1658bcb0991SDimitry Andric         getPointerAtOffset(VTable->getInitializer(), VTableOffset + CallOffset,
166349cc55cSDimitry Andric                            *Caller->getParent(), VTable);
1678bcb0991SDimitry Andric     if (!Ptr) {
1688bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "can't find pointer in vtable!\n");
1698bcb0991SDimitry Andric       VFESafeVTables.erase(VTable);
17081ad6265SDimitry Andric       continue;
1718bcb0991SDimitry Andric     }
1728bcb0991SDimitry Andric 
1738bcb0991SDimitry Andric     auto Callee = dyn_cast<Function>(Ptr->stripPointerCasts());
1748bcb0991SDimitry Andric     if (!Callee) {
1758bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "vtable entry is not function pointer!\n");
1768bcb0991SDimitry Andric       VFESafeVTables.erase(VTable);
17781ad6265SDimitry Andric       continue;
1788bcb0991SDimitry Andric     }
1798bcb0991SDimitry Andric 
1808bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "vfunc dep " << Caller->getName() << " -> "
1818bcb0991SDimitry Andric                       << Callee->getName() << "\n");
1828bcb0991SDimitry Andric     GVDependencies[Caller].insert(Callee);
1838bcb0991SDimitry Andric   }
1848bcb0991SDimitry Andric }
1858bcb0991SDimitry Andric 
ScanTypeCheckedLoadIntrinsics(Module & M)1868bcb0991SDimitry Andric void GlobalDCEPass::ScanTypeCheckedLoadIntrinsics(Module &M) {
1878bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Scanning type.checked.load intrinsics\n");
1888bcb0991SDimitry Andric   Function *TypeCheckedLoadFunc =
1898bcb0991SDimitry Andric       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
190*06c3fb27SDimitry Andric   Function *TypeCheckedLoadRelativeFunc =
191*06c3fb27SDimitry Andric       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load_relative));
1928bcb0991SDimitry Andric 
193*06c3fb27SDimitry Andric   auto scan = [&](Function *CheckedLoadFunc) {
194*06c3fb27SDimitry Andric     if (!CheckedLoadFunc)
1958bcb0991SDimitry Andric       return;
1968bcb0991SDimitry Andric 
197*06c3fb27SDimitry Andric     for (auto *U : CheckedLoadFunc->users()) {
1988bcb0991SDimitry Andric       auto CI = dyn_cast<CallInst>(U);
1998bcb0991SDimitry Andric       if (!CI)
2008bcb0991SDimitry Andric         continue;
2018bcb0991SDimitry Andric 
2028bcb0991SDimitry Andric       auto *Offset = dyn_cast<ConstantInt>(CI->getArgOperand(1));
2038bcb0991SDimitry Andric       Value *TypeIdValue = CI->getArgOperand(2);
2048bcb0991SDimitry Andric       auto *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
2058bcb0991SDimitry Andric 
2068bcb0991SDimitry Andric       if (Offset) {
2078bcb0991SDimitry Andric         ScanVTableLoad(CI->getFunction(), TypeId, Offset->getZExtValue());
2088bcb0991SDimitry Andric       } else {
209*06c3fb27SDimitry Andric         // type.checked.load with a non-constant offset, so assume every entry
210*06c3fb27SDimitry Andric         // in every matching vtable is used.
211bdd1243dSDimitry Andric         for (const auto &VTableInfo : TypeIdMap[TypeId]) {
2128bcb0991SDimitry Andric           VFESafeVTables.erase(VTableInfo.first);
2138bcb0991SDimitry Andric         }
2148bcb0991SDimitry Andric       }
2158bcb0991SDimitry Andric     }
216*06c3fb27SDimitry Andric   };
217*06c3fb27SDimitry Andric 
218*06c3fb27SDimitry Andric   scan(TypeCheckedLoadFunc);
219*06c3fb27SDimitry Andric   scan(TypeCheckedLoadRelativeFunc);
2208bcb0991SDimitry Andric }
2218bcb0991SDimitry Andric 
AddVirtualFunctionDependencies(Module & M)2228bcb0991SDimitry Andric void GlobalDCEPass::AddVirtualFunctionDependencies(Module &M) {
2238bcb0991SDimitry Andric   if (!ClEnableVFE)
2248bcb0991SDimitry Andric     return;
2258bcb0991SDimitry Andric 
2265ffd83dbSDimitry Andric   // If the Virtual Function Elim module flag is present and set to zero, then
2275ffd83dbSDimitry Andric   // the vcall_visibility metadata was inserted for another optimization (WPD)
2285ffd83dbSDimitry Andric   // and we may not have type checked loads on all accesses to the vtable.
2295ffd83dbSDimitry Andric   // Don't attempt VFE in that case.
2305ffd83dbSDimitry Andric   auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
2315ffd83dbSDimitry Andric       M.getModuleFlag("Virtual Function Elim"));
232*06c3fb27SDimitry Andric   if (!Val || Val->isZero())
2335ffd83dbSDimitry Andric     return;
2345ffd83dbSDimitry Andric 
2358bcb0991SDimitry Andric   ScanVTables(M);
2368bcb0991SDimitry Andric 
2378bcb0991SDimitry Andric   if (VFESafeVTables.empty())
2388bcb0991SDimitry Andric     return;
2398bcb0991SDimitry Andric 
2408bcb0991SDimitry Andric   ScanTypeCheckedLoadIntrinsics(M);
2418bcb0991SDimitry Andric 
2428bcb0991SDimitry Andric   LLVM_DEBUG(
2438bcb0991SDimitry Andric     dbgs() << "VFE safe vtables:\n";
2448bcb0991SDimitry Andric     for (auto *VTable : VFESafeVTables)
2458bcb0991SDimitry Andric       dbgs() << "  " << VTable->getName() << "\n";
2468bcb0991SDimitry Andric   );
2478bcb0991SDimitry Andric }
2480b57cec5SDimitry Andric 
run(Module & M,ModuleAnalysisManager & MAM)2490b57cec5SDimitry Andric PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
2500b57cec5SDimitry Andric   bool Changed = false;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   // The algorithm first computes the set L of global variables that are
2530b57cec5SDimitry Andric   // trivially live.  Then it walks the initialization of these variables to
2540b57cec5SDimitry Andric   // compute the globals used to initialize them, which effectively builds a
2550b57cec5SDimitry Andric   // directed graph where nodes are global variables, and an edge from A to B
2560b57cec5SDimitry Andric   // means B is used to initialize A.  Finally, it propagates the liveness
2570b57cec5SDimitry Andric   // information through the graph starting from the nodes in L. Nodes note
2580b57cec5SDimitry Andric   // marked as alive are discarded.
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   // Remove empty functions from the global ctors list.
26181ad6265SDimitry Andric   Changed |= optimizeGlobalCtorsList(
26281ad6265SDimitry Andric       M, [](uint32_t, Function *F) { return isEmptyFunction(F); });
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // Collect the set of members for each comdat.
2650b57cec5SDimitry Andric   for (Function &F : M)
2660b57cec5SDimitry Andric     if (Comdat *C = F.getComdat())
2670b57cec5SDimitry Andric       ComdatMembers.insert(std::make_pair(C, &F));
2680b57cec5SDimitry Andric   for (GlobalVariable &GV : M.globals())
2690b57cec5SDimitry Andric     if (Comdat *C = GV.getComdat())
2700b57cec5SDimitry Andric       ComdatMembers.insert(std::make_pair(C, &GV));
2710b57cec5SDimitry Andric   for (GlobalAlias &GA : M.aliases())
2720b57cec5SDimitry Andric     if (Comdat *C = GA.getComdat())
2730b57cec5SDimitry Andric       ComdatMembers.insert(std::make_pair(C, &GA));
2740b57cec5SDimitry Andric 
2758bcb0991SDimitry Andric   // Add dependencies between virtual call sites and the virtual functions they
2768bcb0991SDimitry Andric   // might call, if we have that information.
2778bcb0991SDimitry Andric   AddVirtualFunctionDependencies(M);
2788bcb0991SDimitry Andric 
2790b57cec5SDimitry Andric   // Loop over the module, adding globals which are obviously necessary.
2800b57cec5SDimitry Andric   for (GlobalObject &GO : M.global_objects()) {
28181ad6265SDimitry Andric     GO.removeDeadConstantUsers();
2820b57cec5SDimitry Andric     // Functions with external linkage are needed if they have a body.
2830b57cec5SDimitry Andric     // Externally visible & appending globals are needed, if they have an
2840b57cec5SDimitry Andric     // initializer.
2850b57cec5SDimitry Andric     if (!GO.isDeclaration())
2860b57cec5SDimitry Andric       if (!GO.isDiscardableIfUnused())
2870b57cec5SDimitry Andric         MarkLive(GO);
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     UpdateGVDependencies(GO);
2900b57cec5SDimitry Andric   }
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   // Compute direct dependencies of aliases.
2930b57cec5SDimitry Andric   for (GlobalAlias &GA : M.aliases()) {
29481ad6265SDimitry Andric     GA.removeDeadConstantUsers();
2950b57cec5SDimitry Andric     // Externally visible aliases are needed.
2960b57cec5SDimitry Andric     if (!GA.isDiscardableIfUnused())
2970b57cec5SDimitry Andric       MarkLive(GA);
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric     UpdateGVDependencies(GA);
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   // Compute direct dependencies of ifuncs.
3030b57cec5SDimitry Andric   for (GlobalIFunc &GIF : M.ifuncs()) {
30481ad6265SDimitry Andric     GIF.removeDeadConstantUsers();
3050b57cec5SDimitry Andric     // Externally visible ifuncs are needed.
3060b57cec5SDimitry Andric     if (!GIF.isDiscardableIfUnused())
3070b57cec5SDimitry Andric       MarkLive(GIF);
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric     UpdateGVDependencies(GIF);
3100b57cec5SDimitry Andric   }
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   // Propagate liveness from collected Global Values through the computed
3130b57cec5SDimitry Andric   // dependencies.
3140b57cec5SDimitry Andric   SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
3150b57cec5SDimitry Andric                                            AliveGlobals.end()};
3160b57cec5SDimitry Andric   while (!NewLiveGVs.empty()) {
3170b57cec5SDimitry Andric     GlobalValue *LGV = NewLiveGVs.pop_back_val();
3180b57cec5SDimitry Andric     for (auto *GVD : GVDependencies[LGV])
3190b57cec5SDimitry Andric       MarkLive(*GVD, &NewLiveGVs);
3200b57cec5SDimitry Andric   }
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   // Now that all globals which are needed are in the AliveGlobals set, we loop
3230b57cec5SDimitry Andric   // through the program, deleting those which are not alive.
3240b57cec5SDimitry Andric   //
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   // The first pass is to drop initializers of global variables which are dead.
3270b57cec5SDimitry Andric   std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
3280b57cec5SDimitry Andric   for (GlobalVariable &GV : M.globals())
3290b57cec5SDimitry Andric     if (!AliveGlobals.count(&GV)) {
3300b57cec5SDimitry Andric       DeadGlobalVars.push_back(&GV);         // Keep track of dead globals
3310b57cec5SDimitry Andric       if (GV.hasInitializer()) {
3320b57cec5SDimitry Andric         Constant *Init = GV.getInitializer();
3330b57cec5SDimitry Andric         GV.setInitializer(nullptr);
3340b57cec5SDimitry Andric         if (isSafeToDestroyConstant(Init))
3350b57cec5SDimitry Andric           Init->destroyConstant();
3360b57cec5SDimitry Andric       }
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   // The second pass drops the bodies of functions which are dead...
3400b57cec5SDimitry Andric   std::vector<Function *> DeadFunctions;
3410b57cec5SDimitry Andric   for (Function &F : M)
3420b57cec5SDimitry Andric     if (!AliveGlobals.count(&F)) {
3430b57cec5SDimitry Andric       DeadFunctions.push_back(&F);         // Keep track of dead globals
3440b57cec5SDimitry Andric       if (!F.isDeclaration())
3450b57cec5SDimitry Andric         F.deleteBody();
3460b57cec5SDimitry Andric     }
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric   // The third pass drops targets of aliases which are dead...
3490b57cec5SDimitry Andric   std::vector<GlobalAlias*> DeadAliases;
3500b57cec5SDimitry Andric   for (GlobalAlias &GA : M.aliases())
3510b57cec5SDimitry Andric     if (!AliveGlobals.count(&GA)) {
3520b57cec5SDimitry Andric       DeadAliases.push_back(&GA);
3530b57cec5SDimitry Andric       GA.setAliasee(nullptr);
3540b57cec5SDimitry Andric     }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   // The fourth pass drops targets of ifuncs which are dead...
3570b57cec5SDimitry Andric   std::vector<GlobalIFunc*> DeadIFuncs;
3580b57cec5SDimitry Andric   for (GlobalIFunc &GIF : M.ifuncs())
3590b57cec5SDimitry Andric     if (!AliveGlobals.count(&GIF)) {
3600b57cec5SDimitry Andric       DeadIFuncs.push_back(&GIF);
3610b57cec5SDimitry Andric       GIF.setResolver(nullptr);
3620b57cec5SDimitry Andric     }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   // Now that all interferences have been dropped, delete the actual objects
3650b57cec5SDimitry Andric   // themselves.
3660b57cec5SDimitry Andric   auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
36781ad6265SDimitry Andric     GV->removeDeadConstantUsers();
3680b57cec5SDimitry Andric     GV->eraseFromParent();
3690b57cec5SDimitry Andric     Changed = true;
3700b57cec5SDimitry Andric   };
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric   NumFunctions += DeadFunctions.size();
3738bcb0991SDimitry Andric   for (Function *F : DeadFunctions) {
3748bcb0991SDimitry Andric     if (!F->use_empty()) {
3758bcb0991SDimitry Andric       // Virtual functions might still be referenced by one or more vtables,
3768bcb0991SDimitry Andric       // but if we've proven them to be unused then it's safe to replace the
3778bcb0991SDimitry Andric       // virtual function pointers with null, allowing us to remove the
3788bcb0991SDimitry Andric       // function itself.
3798bcb0991SDimitry Andric       ++NumVFuncs;
380349cc55cSDimitry Andric 
381349cc55cSDimitry Andric       // Detect vfuncs that are referenced as "relative pointers" which are used
382349cc55cSDimitry Andric       // in Swift vtables, i.e. entries in the form of:
383349cc55cSDimitry Andric       //
384349cc55cSDimitry Andric       //   i32 trunc (i64 sub (i64 ptrtoint @f, i64 ptrtoint ...)) to i32)
385349cc55cSDimitry Andric       //
386349cc55cSDimitry Andric       // In this case, replace the whole "sub" expression with constant 0 to
387349cc55cSDimitry Andric       // avoid leaving a weird sub(0, symbol) expression behind.
388349cc55cSDimitry Andric       replaceRelativePointerUsersWithZero(F);
389349cc55cSDimitry Andric 
3908bcb0991SDimitry Andric       F->replaceNonMetadataUsesWith(ConstantPointerNull::get(F->getType()));
3918bcb0991SDimitry Andric     }
3920b57cec5SDimitry Andric     EraseUnusedGlobalValue(F);
3938bcb0991SDimitry Andric   }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   NumVariables += DeadGlobalVars.size();
3960b57cec5SDimitry Andric   for (GlobalVariable *GV : DeadGlobalVars)
3970b57cec5SDimitry Andric     EraseUnusedGlobalValue(GV);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   NumAliases += DeadAliases.size();
4000b57cec5SDimitry Andric   for (GlobalAlias *GA : DeadAliases)
4010b57cec5SDimitry Andric     EraseUnusedGlobalValue(GA);
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   NumIFuncs += DeadIFuncs.size();
4040b57cec5SDimitry Andric   for (GlobalIFunc *GIF : DeadIFuncs)
4050b57cec5SDimitry Andric     EraseUnusedGlobalValue(GIF);
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   // Make sure that all memory is released
4080b57cec5SDimitry Andric   AliveGlobals.clear();
4090b57cec5SDimitry Andric   ConstantDependenciesCache.clear();
4100b57cec5SDimitry Andric   GVDependencies.clear();
4110b57cec5SDimitry Andric   ComdatMembers.clear();
4128bcb0991SDimitry Andric   TypeIdMap.clear();
4138bcb0991SDimitry Andric   VFESafeVTables.clear();
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   if (Changed)
4160b57cec5SDimitry Andric     return PreservedAnalyses::none();
4170b57cec5SDimitry Andric   return PreservedAnalyses::all();
4180b57cec5SDimitry Andric }
419*06c3fb27SDimitry Andric 
printPipeline(raw_ostream & OS,function_ref<StringRef (StringRef)> MapClassName2PassName)420*06c3fb27SDimitry Andric void GlobalDCEPass::printPipeline(
421*06c3fb27SDimitry Andric     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
422*06c3fb27SDimitry Andric   static_cast<PassInfoMixin<GlobalDCEPass> *>(this)->printPipeline(
423*06c3fb27SDimitry Andric       OS, MapClassName2PassName);
424*06c3fb27SDimitry Andric   if (InLTOPostLink)
425*06c3fb27SDimitry Andric     OS << "<vfe-linkage-unit-visibility>";
426*06c3fb27SDimitry Andric }
427