1//===- ElimAvailExtern.cpp - DCE unreachable internal functions -----------===//
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-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This transform is designed to eliminate available external global
10// definitions from the program, turning them into declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/ElimAvailExtern.h"
15#include "IPOOptions.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/CtxProfAnalysis.h"
19#include "llvm/IR/Constant.h"
20#include "llvm/IR/DebugInfoMetadata.h"
21#include "llvm/IR/Function.h"
22#include "llvm/IR/GlobalValue.h"
23#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/MDBuilder.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Transforms/Utils/GlobalStatus.h"
27#include "llvm/Transforms/Utils/ModuleUtils.h"
28
29using namespace llvm;
30
31#define DEBUG_TYPE "elim-avail-extern"
32
33STATISTIC(NumRemovals, "Number of functions removed");
34STATISTIC(NumFunctionsConverted, "Number of functions converted");
35STATISTIC(NumGlobalVariablesConverted, "Number of global variables converted");
36STATISTIC(NumVariables, "Number of global variables removed");
37
38void deleteFunction(Function &F) {
39 // This will set the linkage to external
40 F.deleteBody();
41 ++NumRemovals;
42}
43
44static std::string getNewName(Module &M, const GlobalValue &GV) {
45 std::string Name = GV.getName().str() + ".__uniq";
46 std::string ModuleId = getUniqueModuleId(M: &M);
47 if (!ModuleId.empty())
48 Name += "." + ModuleId;
49 return Name;
50}
51
52/// Create a copy of the thinlto import, mark it local, and redirect direct
53/// calls to the copy. Only direct calls are replaced, so that e.g. indirect
54/// call function pointer tests would use the global identity of the function.
55///
56/// Currently, Value Profiling ("VP") MD_prof data isn't updated to refer to the
57/// clone's GUID (which will be different, because the name and linkage is
58/// different), under the assumption that the last consumer of this data is
59/// upstream the pipeline (e.g. ICP).
60static void convertToLocalCopy(Module &M, Function &F) {
61 assert(F.hasAvailableExternallyLinkage());
62 assert(!F.isDeclaration());
63 // If we can't find a single use that's a call, just delete the function.
64 if (F.uses().end() == llvm::find_if(Range: F.uses(), P: [&](Use &U) {
65 return isa<CallBase>(Val: U.getUser());
66 }))
67 return deleteFunction(F);
68
69 auto OrigName = F.getName().str();
70 // Build a new name. We still need the old name (see below).
71 // We could just rely on internal linking allowing 2 modules have internal
72 // functions with the same name, but that just creates more trouble than
73 // necessary e.g. distinguishing profiles or debugging. Instead, we append the
74 // module identifier.
75 std::string NewName = getNewName(M, GV: F);
76 F.setName(NewName);
77 if (auto *SP = F.getSubprogram())
78 SP->replaceLinkageName(LN: MDString::get(Context&: F.getParent()->getContext(), Str: NewName));
79
80 F.setLinkage(GlobalValue::InternalLinkage);
81 // Now make a declaration for the old name. We'll use it if there are non-call
82 // uses. For those, it would be incorrect to replace them with the local copy:
83 // for example, one such use could be taking the address of the function and
84 // passing it to an external function, which, in turn, might compare the
85 // function pointer to the original (non-local) function pointer, e.g. as part
86 // of indirect call promotion.
87 auto *Decl =
88 Function::Create(Ty: F.getFunctionType(), Linkage: GlobalValue::ExternalLinkage,
89 AddrSpace: F.getAddressSpace(), N: OrigName, M: F.getParent());
90 F.replaceUsesWithIf(New: Decl,
91 ShouldReplace: [&](Use &U) { return !isa<CallBase>(Val: U.getUser()); });
92 ++NumFunctionsConverted;
93}
94
95/// Similar to the function above, this is to convert an externally available
96/// global variable to local.
97static void convertToLocalCopy(Module &M, GlobalVariable &GV) {
98 assert(GV.hasAvailableExternallyLinkage());
99 GV.setName(getNewName(M, GV));
100 GV.setLinkage(GlobalValue::InternalLinkage);
101 ++NumGlobalVariablesConverted;
102}
103
104static bool eliminateAvailableExternally(Module &M, bool Convert,
105 FunctionAnalysisManager &FAM) {
106 const IPOOptions &Opts = getIPOOptions(M);
107 bool Changed = false;
108
109 // If a global variable is available externally and in the specified address
110 // space, convert it to local linkage; otherwise, drop its initializer.
111 for (GlobalVariable &GV : M.globals()) {
112 if (!GV.hasAvailableExternallyLinkage())
113 continue;
114 if (GV.getAddressSpace() == Opts.avail_extern_gv_in_addrspace_to_local &&
115 !GV.use_empty()) {
116 convertToLocalCopy(M, GV);
117 Changed = true;
118 continue;
119 }
120 if (GV.hasInitializer()) {
121 Constant *Init = GV.getInitializer();
122 GV.setInitializer(nullptr);
123 if (isSafeToDestroyConstant(C: Init))
124 Init->destroyConstant();
125 }
126 GV.removeDeadConstantUsers();
127 GV.setLinkage(GlobalValue::ExternalLinkage);
128 ++NumVariables;
129 Changed = true;
130 }
131
132 // Drop the bodies of available externally functions.
133 for (Function &F : llvm::make_early_inc_range(Range&: M)) {
134 if (F.isDeclaration() || !F.hasAvailableExternallyLinkage())
135 continue;
136
137 if (Convert) {
138 convertToLocalCopy(M, F);
139 } else {
140 FAM.clear(IR&: F, Name: F.getName());
141 deleteFunction(F);
142 }
143
144 F.removeDeadConstantUsers();
145 Changed = true;
146 }
147
148 return Changed;
149}
150
151PreservedAnalyses
152EliminateAvailableExternallyPass::run(Module &M, ModuleAnalysisManager &MAM) {
153 auto *CtxProf = MAM.getCachedResult<CtxProfAnalysis>(IR&: M);
154 // Convert to local instead of eliding if we use contextual profiling in this
155 // module. This is because the IPO decisions performed with contextual
156 // information will likely differ from decisions made without. For a function
157 // that's imported, its optimizations will, thus, differ, and be specialized
158 // for this contextual information. Eliding it in favor of the original would
159 // undo these optimizations.
160 bool Convert = (CtxProf && CtxProf->isInSpecializedModule()) ||
161 getIPOOptions(M).avail_extern_to_local;
162 FunctionAnalysisManager &FAM =
163 MAM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
164 if (!eliminateAvailableExternally(M, Convert, FAM))
165 return PreservedAnalyses::all();
166
167 if (Convert)
168 return PreservedAnalyses::none();
169
170 // Only function bodies were deleted, and their analyses were cleared.
171 PreservedAnalyses PA;
172 PA.preserve<FunctionAnalysisManagerModuleProxy>();
173 PA.preserveSet<CFGAnalyses>();
174 return PA;
175}
176