1 //===----------------------------------------------------------------------===//
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 #include "ReduceOperandsSkip.h"
10 #include "llvm/ADT/Sequence.h"
11 #include "llvm/ADT/SetVector.h"
12 #include "llvm/IR/Constants.h"
13 #include "llvm/IR/Dominators.h"
14 #include "llvm/IR/InstIterator.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/Operator.h"
20 /// Collect all values that are directly or indirectly referenced by @p Root,
21 /// including Root itself. This is a BF search such that the more steps needed
22 /// to get to the reference, the more behind it is found in @p Collection. Each
23 /// step could be its own reduction, therefore we consider later values "more
25 static SetVector
<Value
*> collectReferencedValues(Value
*Root
) {
26 SetVector
<Value
*> Refs
;
27 std::deque
<Value
*> Worklist
;
28 Worklist
.push_back(Root
);
30 while (!Worklist
.empty()) {
31 Value
*Val
= Worklist
.front();
33 if (!Refs
.insert(Val
))
36 if (auto *O
= dyn_cast
<Operator
>(Val
)) {
37 for (Use
&Op
: O
->operands())
38 Worklist
.push_back(Op
.get());
45 static bool shouldReduceOperand(Use
&Op
) {
46 Type
*Ty
= Op
->getType();
47 if (Ty
->isLabelTy() || Ty
->isMetadataTy())
49 // TODO: be more precise about which GEP operands we can reduce (e.g. array
51 if (isa
<GEPOperator
>(Op
.getUser()))
53 if (auto *CB
= dyn_cast
<CallBase
>(Op
.getUser())) {
54 if (&CB
->getCalledOperandUse() == &Op
)
60 /// Return a reduction priority for @p V. A higher values means "more reduced".
61 static int classifyReductivePower(Value
*V
) {
62 if (auto *C
= dyn_cast
<ConstantData
>(V
)) {
63 if (isa
<UndefValue
>(V
))
75 if (isa
<GlobalValue
>(V
))
81 if (isa
<Instruction
>(V
))
87 /// Calls @p Callback for every reduction opportunity in @p F. Used by
88 /// countOperands() and extractOperandsFromModule() to ensure consistency
91 opportunities(Function
&F
,
92 function_ref
<void(Use
&, ArrayRef
<Value
*>)> Callback
) {
93 if (F
.isDeclaration())
96 // Need DominatorTree to find out whether an SSA value can be referenced.
99 // Return whether @p LHS is "more reduced" that @p RHS. That is, whether
100 // @p RHS should be preferred over @p LHS in a reduced output. This is a
101 // partial order, a Value may not be preferable over another.
102 auto IsMoreReduced
= [&DT
](Value
*LHS
, Value
*RHS
) -> bool {
103 // A value is not more reduced than itself.
107 int ReductivePowerDiff
=
108 classifyReductivePower(RHS
) - classifyReductivePower(LHS
);
109 if (ReductivePowerDiff
!= 0)
110 return ReductivePowerDiff
< 0;
112 // LHS is more reduced if it is defined further up the dominance tree. In a
113 // chain of definitions,
119 // every use of %b can be replaced by %a, but not by a use of %c. That is, a
120 // use %c can be replaced in steps first by %b, then by %a, making %a the
121 // "more reduced" choice that skips over more instructions.
122 auto *LHSInst
= dyn_cast
<Instruction
>(LHS
);
123 auto *RHSInst
= dyn_cast
<Instruction
>(RHS
);
124 if (LHSInst
&& RHSInst
) {
125 if (DT
.dominates(LHSInst
, RHSInst
))
129 // Compress the number of used arguments by prefering the first ones. Unused
130 // trailing argument can be removed by the arguments pass.
131 auto *LHSArg
= dyn_cast
<Argument
>(LHS
);
132 auto *RHSArg
= dyn_cast
<Argument
>(RHS
);
133 if (LHSArg
&& RHSArg
) {
134 if (LHSArg
->getArgNo() < RHSArg
->getArgNo())
141 for (Instruction
&I
: instructions(&F
)) {
142 for (Use
&Op
: I
.operands()) {
143 if (!shouldReduceOperand(Op
))
145 Value
*OpVal
= Op
.get();
147 // Collect refenced values as potential replacement candidates.
148 SetVector
<Value
*> ReferencedVals
= collectReferencedValues(OpVal
);
150 // Regardless whether referenced, add the function arguments as
151 // replacement possibility with the goal of reducing the number of (used)
152 // function arguments, possibly created by the operands-to-args.
153 for (Argument
&Arg
: F
.args())
154 ReferencedVals
.insert(&Arg
);
156 // After all candidates have been added, it doesn't need to be a set
158 auto Candidates
= ReferencedVals
.takeVector();
160 // Remove ineligible candidates.
161 llvm::erase_if(Candidates
, [&, OpVal
](Value
*V
) {
162 // Candidate value must have the same type.
163 if (OpVal
->getType() != V
->getType())
166 // Do not introduce address captures of intrinsics.
167 if (Function
*F
= dyn_cast
<Function
>(V
)) {
168 if (F
->isIntrinsic())
172 // Only consider candidates that are "more reduced" than the original
173 // value. This explicitly also rules out candidates with the same
174 // reduction power. This is to ensure that repeated invocations of this
175 // pass eventually reach a fixpoint without switch back and forth
176 // between two opportunities with the same reductive power.
177 return !IsMoreReduced(V
, OpVal
);
180 if (Candidates
.empty())
183 // collectReferencedValues pushed the more reductive values to the end of
184 // the collection, but we need them at the front.
185 std::reverse(Candidates
.begin(), Candidates
.end());
187 // Independency of collectReferencedValues's idea of reductive power,
188 // ensure the partial order of IsMoreReduced is enforced.
189 llvm::stable_sort(Candidates
, IsMoreReduced
);
191 Callback(Op
, Candidates
);
196 static void extractOperandsFromModule(Oracle
&O
, ReducerWorkItem
&WorkItem
) {
197 Module
&Program
= WorkItem
.getModule();
199 for (Function
&F
: Program
.functions()) {
200 SmallVector
<std::pair
<Use
*, Value
*>> Replacements
;
201 opportunities(F
, [&](Use
&Op
, ArrayRef
<Value
*> Candidates
) {
202 // Only apply the candidate the Oracle selected to keep that is the most
203 // reduced. Candidates with less reductive power can be interpreted as an
204 // intermediate step that is immediately replaced with the more reduced
205 // one. The number of shouldKeep() calls must be independent of the result
206 // of previous shouldKeep() calls to keep the total number of calls
207 // in-sync with what countOperands() has computed.
208 bool AlreadyReplaced
= false;
209 for (Value
*C
: Candidates
) {
210 bool Keep
= O
.shouldKeep();
211 if (AlreadyReplaced
|| Keep
)
214 // Replacing the operand value immediately would influence the candidate
215 // set for the following operands. Delay it until after all candidates
216 // have been determined.
217 Replacements
.push_back({&Op
, C
});
219 AlreadyReplaced
= true;
223 for (std::pair
<Use
*, Value
*> P
: Replacements
) {
224 if (PHINode
*Phi
= dyn_cast
<PHINode
>(P
.first
->getUser()))
225 Phi
->setIncomingValueForBlock(Phi
->getIncomingBlock(*P
.first
), P
.second
);
227 P
.first
->set(P
.second
);
232 void llvm::reduceOperandsSkipDeltaPass(TestRunner
&Test
) {
233 runDeltaPass(Test
, extractOperandsFromModule
,
234 "Reducing operands by skipping over instructions");