1 //===- CalledValuePropagation.cpp - Propagate called values -----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements a transformation that attaches !callees metadata to
10 // indirect call sites. For a given call site, the metadata, if present,
11 // indicates the set of functions the call site could possibly target at
12 // run-time. This metadata is added to indirect call sites when the set of
13 // possible targets can be determined by analysis and is known to be small. The
14 // analysis driving the transformation is similar to constant propagation and
15 // makes uses of the generic sparse propagation solver.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
20 #include "llvm/Analysis/SparsePropagation.h"
21 #include "llvm/Analysis/ValueLatticeUtils.h"
22 #include "llvm/IR/MDBuilder.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Transforms/IPO.h"
28 #define DEBUG_TYPE "called-value-propagation"
30 /// The maximum number of functions to track per lattice value. Once the number
31 /// of functions a call site can possibly target exceeds this threshold, it's
32 /// lattice value becomes overdefined. The number of possible lattice values is
33 /// bounded by Ch(F, M), where F is the number of functions in the module and M
34 /// is MaxFunctionsPerValue. As such, this value should be kept very small. We
35 /// likely can't do anything useful for call sites with a large number of
36 /// possible targets, anyway.
37 static cl::opt
<unsigned> MaxFunctionsPerValue(
38 "cvp-max-functions-per-value", cl::Hidden
, cl::init(4),
39 cl::desc("The maximum number of functions to track per lattice value"));
42 /// To enable interprocedural analysis, we assign LLVM values to the following
43 /// groups. The register group represents SSA registers, the return group
44 /// represents the return values of functions, and the memory group represents
45 /// in-memory values. An LLVM Value can technically be in more than one group.
46 /// It's necessary to distinguish these groups so we can, for example, track a
47 /// global variable separately from the value stored at its location.
48 enum class IPOGrouping
{ Register
, Return
, Memory
};
50 /// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.
51 using CVPLatticeKey
= PointerIntPair
<Value
*, 2, IPOGrouping
>;
53 /// The lattice value type used by our custom lattice function. It holds the
54 /// lattice state, and a set of functions.
57 /// The states of the lattice values. Only the FunctionSet state is
58 /// interesting. It indicates the set of functions to which an LLVM value may
60 enum CVPLatticeStateTy
{ Undefined
, FunctionSet
, Overdefined
, Untracked
};
62 /// Comparator for sorting the functions set. We want to keep the order
63 /// deterministic for testing, etc.
65 bool operator()(const Function
*LHS
, const Function
*RHS
) const {
66 return LHS
->getName() < RHS
->getName();
70 CVPLatticeVal() : LatticeState(Undefined
) {}
71 CVPLatticeVal(CVPLatticeStateTy LatticeState
) : LatticeState(LatticeState
) {}
72 CVPLatticeVal(std::vector
<Function
*> &&Functions
)
73 : LatticeState(FunctionSet
), Functions(std::move(Functions
)) {
74 assert(llvm::is_sorted(this->Functions
, Compare()));
77 /// Get a reference to the functions held by this lattice value. The number
78 /// of functions will be zero for states other than FunctionSet.
79 const std::vector
<Function
*> &getFunctions() const {
83 /// Returns true if the lattice value is in the FunctionSet state.
84 bool isFunctionSet() const { return LatticeState
== FunctionSet
; }
86 bool operator==(const CVPLatticeVal
&RHS
) const {
87 return LatticeState
== RHS
.LatticeState
&& Functions
== RHS
.Functions
;
90 bool operator!=(const CVPLatticeVal
&RHS
) const {
91 return LatticeState
!= RHS
.LatticeState
|| Functions
!= RHS
.Functions
;
95 /// Holds the state this lattice value is in.
96 CVPLatticeStateTy LatticeState
;
98 /// Holds functions indicating the possible targets of call sites. This set
99 /// is empty for lattice values in the undefined, overdefined, and untracked
100 /// states. The maximum size of the set is controlled by
101 /// MaxFunctionsPerValue. Since most LLVM values are expected to be in
102 /// uninteresting states (i.e., overdefined), CVPLatticeVal objects should be
103 /// small and efficiently copyable.
104 // FIXME: This could be a TinyPtrVector and/or merge with LatticeState.
105 std::vector
<Function
*> Functions
;
108 /// The custom lattice function used by the generic sparse propagation solver.
109 /// It handles merging lattice values and computing new lattice values for
110 /// constants, arguments, values returned from trackable functions, and values
111 /// located in trackable global variables. It also computes the lattice values
112 /// that change as a result of executing instructions.
114 : public AbstractLatticeFunction
<CVPLatticeKey
, CVPLatticeVal
> {
117 : AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined
),
118 CVPLatticeVal(CVPLatticeVal::Overdefined
),
119 CVPLatticeVal(CVPLatticeVal::Untracked
)) {}
121 /// Compute and return a CVPLatticeVal for the given CVPLatticeKey.
122 CVPLatticeVal
ComputeLatticeVal(CVPLatticeKey Key
) override
{
123 switch (Key
.getInt()) {
124 case IPOGrouping::Register
:
125 if (isa
<Instruction
>(Key
.getPointer())) {
126 return getUndefVal();
127 } else if (auto *A
= dyn_cast
<Argument
>(Key
.getPointer())) {
128 if (canTrackArgumentsInterprocedurally(A
->getParent()))
129 return getUndefVal();
130 } else if (auto *C
= dyn_cast
<Constant
>(Key
.getPointer())) {
131 return computeConstant(C
);
133 return getOverdefinedVal();
134 case IPOGrouping::Memory
:
135 case IPOGrouping::Return
:
136 if (auto *GV
= dyn_cast
<GlobalVariable
>(Key
.getPointer())) {
137 if (canTrackGlobalVariableInterprocedurally(GV
))
138 return computeConstant(GV
->getInitializer());
139 } else if (auto *F
= cast
<Function
>(Key
.getPointer()))
140 if (canTrackReturnsInterprocedurally(F
))
141 return getUndefVal();
143 return getOverdefinedVal();
146 /// Merge the two given lattice values. The interesting cases are merging two
147 /// FunctionSet values and a FunctionSet value with an Undefined value. For
148 /// these cases, we simply union the function sets. If the size of the union
149 /// is greater than the maximum functions we track, the merged value is
151 CVPLatticeVal
MergeValues(CVPLatticeVal X
, CVPLatticeVal Y
) override
{
152 if (X
== getOverdefinedVal() || Y
== getOverdefinedVal())
153 return getOverdefinedVal();
154 if (X
== getUndefVal() && Y
== getUndefVal())
155 return getUndefVal();
156 std::vector
<Function
*> Union
;
157 std::set_union(X
.getFunctions().begin(), X
.getFunctions().end(),
158 Y
.getFunctions().begin(), Y
.getFunctions().end(),
159 std::back_inserter(Union
), CVPLatticeVal::Compare
{});
160 if (Union
.size() > MaxFunctionsPerValue
)
161 return getOverdefinedVal();
162 return CVPLatticeVal(std::move(Union
));
165 /// Compute the lattice values that change as a result of executing the given
166 /// instruction. The changed values are stored in \p ChangedValues. We handle
167 /// just a few kinds of instructions since we're only propagating values that
169 void ComputeInstructionState(
170 Instruction
&I
, DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
171 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) override
{
172 switch (I
.getOpcode()) {
173 case Instruction::Call
:
174 case Instruction::Invoke
:
175 return visitCallBase(cast
<CallBase
>(I
), ChangedValues
, SS
);
176 case Instruction::Load
:
177 return visitLoad(*cast
<LoadInst
>(&I
), ChangedValues
, SS
);
178 case Instruction::Ret
:
179 return visitReturn(*cast
<ReturnInst
>(&I
), ChangedValues
, SS
);
180 case Instruction::Select
:
181 return visitSelect(*cast
<SelectInst
>(&I
), ChangedValues
, SS
);
182 case Instruction::Store
:
183 return visitStore(*cast
<StoreInst
>(&I
), ChangedValues
, SS
);
185 return visitInst(I
, ChangedValues
, SS
);
189 /// Print the given CVPLatticeVal to the specified stream.
190 void PrintLatticeVal(CVPLatticeVal LV
, raw_ostream
&OS
) override
{
191 if (LV
== getUndefVal())
193 else if (LV
== getOverdefinedVal())
195 else if (LV
== getUntrackedVal())
201 /// Print the given CVPLatticeKey to the specified stream.
202 void PrintLatticeKey(CVPLatticeKey Key
, raw_ostream
&OS
) override
{
203 if (Key
.getInt() == IPOGrouping::Register
)
205 else if (Key
.getInt() == IPOGrouping::Memory
)
207 else if (Key
.getInt() == IPOGrouping::Return
)
209 if (isa
<Function
>(Key
.getPointer()))
210 OS
<< Key
.getPointer()->getName();
212 OS
<< *Key
.getPointer();
215 /// We collect a set of indirect calls when visiting call sites. This method
216 /// returns a reference to that set.
217 SmallPtrSetImpl
<CallBase
*> &getIndirectCalls() { return IndirectCalls
; }
220 /// Holds the indirect calls we encounter during the analysis. We will attach
221 /// metadata to these calls after the analysis indicating the functions the
222 /// calls can possibly target.
223 SmallPtrSet
<CallBase
*, 32> IndirectCalls
;
225 /// Compute a new lattice value for the given constant. The constant, after
226 /// stripping any pointer casts, should be a Function. We ignore null
227 /// pointers as an optimization, since calling these values is undefined
229 CVPLatticeVal
computeConstant(Constant
*C
) {
230 if (isa
<ConstantPointerNull
>(C
))
231 return CVPLatticeVal(CVPLatticeVal::FunctionSet
);
232 if (auto *F
= dyn_cast
<Function
>(C
->stripPointerCasts()))
233 return CVPLatticeVal({F
});
234 return getOverdefinedVal();
237 /// Handle return instructions. The function's return state is the merge of
238 /// the returned value state and the function's return state.
239 void visitReturn(ReturnInst
&I
,
240 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
241 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
242 Function
*F
= I
.getParent()->getParent();
243 if (F
->getReturnType()->isVoidTy())
245 auto RegI
= CVPLatticeKey(I
.getReturnValue(), IPOGrouping::Register
);
246 auto RetF
= CVPLatticeKey(F
, IPOGrouping::Return
);
247 ChangedValues
[RetF
] =
248 MergeValues(SS
.getValueState(RegI
), SS
.getValueState(RetF
));
251 /// Handle call sites. The state of a called function's formal arguments is
252 /// the merge of the argument state with the call sites corresponding actual
253 /// argument state. The call site state is the merge of the call site state
254 /// with the returned value state of the called function.
255 void visitCallBase(CallBase
&CB
,
256 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
257 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
258 Function
*F
= CB
.getCalledFunction();
259 auto RegI
= CVPLatticeKey(&CB
, IPOGrouping::Register
);
261 // If this is an indirect call, save it so we can quickly revisit it when
262 // attaching metadata.
264 IndirectCalls
.insert(&CB
);
266 // If we can't track the function's return values, there's nothing to do.
267 if (!F
|| !canTrackReturnsInterprocedurally(F
)) {
268 // Void return, No need to create and update CVPLattice state as no one
270 if (CB
.getType()->isVoidTy())
272 ChangedValues
[RegI
] = getOverdefinedVal();
276 // Inform the solver that the called function is executable, and perform
277 // the merges for the arguments and return value.
278 SS
.MarkBlockExecutable(&F
->front());
279 auto RetF
= CVPLatticeKey(F
, IPOGrouping::Return
);
280 for (Argument
&A
: F
->args()) {
281 auto RegFormal
= CVPLatticeKey(&A
, IPOGrouping::Register
);
283 CVPLatticeKey(CB
.getArgOperand(A
.getArgNo()), IPOGrouping::Register
);
284 ChangedValues
[RegFormal
] =
285 MergeValues(SS
.getValueState(RegFormal
), SS
.getValueState(RegActual
));
288 // Void return, No need to create and update CVPLattice state as no one can
290 if (CB
.getType()->isVoidTy())
293 ChangedValues
[RegI
] =
294 MergeValues(SS
.getValueState(RegI
), SS
.getValueState(RetF
));
297 /// Handle select instructions. The select instruction state is the merge the
298 /// true and false value states.
299 void visitSelect(SelectInst
&I
,
300 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
301 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
302 auto RegI
= CVPLatticeKey(&I
, IPOGrouping::Register
);
303 auto RegT
= CVPLatticeKey(I
.getTrueValue(), IPOGrouping::Register
);
304 auto RegF
= CVPLatticeKey(I
.getFalseValue(), IPOGrouping::Register
);
305 ChangedValues
[RegI
] =
306 MergeValues(SS
.getValueState(RegT
), SS
.getValueState(RegF
));
309 /// Handle load instructions. If the pointer operand of the load is a global
310 /// variable, we attempt to track the value. The loaded value state is the
311 /// merge of the loaded value state with the global variable state.
312 void visitLoad(LoadInst
&I
,
313 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
314 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
315 auto RegI
= CVPLatticeKey(&I
, IPOGrouping::Register
);
316 if (auto *GV
= dyn_cast
<GlobalVariable
>(I
.getPointerOperand())) {
317 auto MemGV
= CVPLatticeKey(GV
, IPOGrouping::Memory
);
318 ChangedValues
[RegI
] =
319 MergeValues(SS
.getValueState(RegI
), SS
.getValueState(MemGV
));
321 ChangedValues
[RegI
] = getOverdefinedVal();
325 /// Handle store instructions. If the pointer operand of the store is a
326 /// global variable, we attempt to track the value. The global variable state
327 /// is the merge of the stored value state with the global variable state.
328 void visitStore(StoreInst
&I
,
329 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
330 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
331 auto *GV
= dyn_cast
<GlobalVariable
>(I
.getPointerOperand());
334 auto RegI
= CVPLatticeKey(I
.getValueOperand(), IPOGrouping::Register
);
335 auto MemGV
= CVPLatticeKey(GV
, IPOGrouping::Memory
);
336 ChangedValues
[MemGV
] =
337 MergeValues(SS
.getValueState(RegI
), SS
.getValueState(MemGV
));
340 /// Handle all other instructions. All other instructions are marked
342 void visitInst(Instruction
&I
,
343 DenseMap
<CVPLatticeKey
, CVPLatticeVal
> &ChangedValues
,
344 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> &SS
) {
345 // Simply bail if this instruction has no user.
348 auto RegI
= CVPLatticeKey(&I
, IPOGrouping::Register
);
349 ChangedValues
[RegI
] = getOverdefinedVal();
355 /// A specialization of LatticeKeyInfo for CVPLatticeKeys. The generic solver
356 /// must translate between LatticeKeys and LLVM Values when adding Values to
357 /// its work list and inspecting the state of control-flow related values.
358 template <> struct LatticeKeyInfo
<CVPLatticeKey
> {
359 static inline Value
*getValueFromLatticeKey(CVPLatticeKey Key
) {
360 return Key
.getPointer();
362 static inline CVPLatticeKey
getLatticeKeyFromValue(Value
*V
) {
363 return CVPLatticeKey(V
, IPOGrouping::Register
);
368 static bool runCVP(Module
&M
) {
369 // Our custom lattice function and generic sparse propagation solver.
370 CVPLatticeFunc Lattice
;
371 SparseSolver
<CVPLatticeKey
, CVPLatticeVal
> Solver(&Lattice
);
373 // For each function in the module, if we can't track its arguments, let the
374 // generic solver assume it is executable.
375 for (Function
&F
: M
)
376 if (!F
.isDeclaration() && !canTrackArgumentsInterprocedurally(&F
))
377 Solver
.MarkBlockExecutable(&F
.front());
379 // Solver our custom lattice. In doing so, we will also build a set of
380 // indirect call sites.
383 // Attach metadata to the indirect call sites that were collected indicating
384 // the set of functions they can possibly target.
385 bool Changed
= false;
386 MDBuilder
MDB(M
.getContext());
387 for (CallBase
*C
: Lattice
.getIndirectCalls()) {
388 auto RegI
= CVPLatticeKey(C
->getCalledOperand(), IPOGrouping::Register
);
389 CVPLatticeVal LV
= Solver
.getExistingValueState(RegI
);
390 if (!LV
.isFunctionSet() || LV
.getFunctions().empty())
392 MDNode
*Callees
= MDB
.createCallees(LV
.getFunctions());
393 C
->setMetadata(LLVMContext::MD_callees
, Callees
);
400 PreservedAnalyses
CalledValuePropagationPass::run(Module
&M
,
401 ModuleAnalysisManager
&) {
403 return PreservedAnalyses::all();
407 class CalledValuePropagationLegacyPass
: public ModulePass
{
411 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
412 AU
.setPreservesAll();
415 CalledValuePropagationLegacyPass() : ModulePass(ID
) {
416 initializeCalledValuePropagationLegacyPassPass(
417 *PassRegistry::getPassRegistry());
420 bool runOnModule(Module
&M
) override
{
428 char CalledValuePropagationLegacyPass::ID
= 0;
429 INITIALIZE_PASS(CalledValuePropagationLegacyPass
, "called-value-propagation",
430 "Called Value Propagation", false, false)
432 ModulePass
*llvm::createCalledValuePropagationPass() {
433 return new CalledValuePropagationLegacyPass();