1 //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
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 pass reassociates commutative expressions in an order that is designed
10 // to promote better constant propagation, GCSE, LICM, PRE, etc.
11 //
12 // For example: 4 + (x + 5) -> x + (4 + 5)
13 //
14 // In the implementation of this algorithm, constants are assigned rank = 0,
15 // function arguments are rank = 1, and other values are assigned ranks
16 // corresponding to the reverse post order traversal of current function
17 // (starting at 2), which effectively gives values in deep loops higher rank
18 // than values not in loops.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar/Reassociate.h"
23 #include "llvm/ADT/APFloat.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/BasicBlock.h"
36 #include "llvm/IR/CFG.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Operator.h"
46 #include "llvm/IR/PassManager.h"
47 #include "llvm/IR/PatternMatch.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/User.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/IR/ValueHandle.h"
52 #include "llvm/InitializePasses.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Scalar.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include <algorithm>
61 #include <cassert>
62 #include <utility>
63
64 using namespace llvm;
65 using namespace reassociate;
66 using namespace PatternMatch;
67
68 #define DEBUG_TYPE "reassociate"
69
70 STATISTIC(NumChanged, "Number of insts reassociated");
71 STATISTIC(NumAnnihil, "Number of expr tree annihilated");
72 STATISTIC(NumFactor , "Number of multiplies factored");
73
74 #ifndef NDEBUG
75 /// Print out the expression identified in the Ops list.
PrintOps(Instruction * I,const SmallVectorImpl<ValueEntry> & Ops)76 static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
77 Module *M = I->getModule();
78 dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
79 << *Ops[0].Op->getType() << '\t';
80 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
81 dbgs() << "[ ";
82 Ops[i].Op->printAsOperand(dbgs(), false, M);
83 dbgs() << ", #" << Ops[i].Rank << "] ";
84 }
85 }
86 #endif
87
88 /// Utility class representing a non-constant Xor-operand. We classify
89 /// non-constant Xor-Operands into two categories:
90 /// C1) The operand is in the form "X & C", where C is a constant and C != ~0
91 /// C2)
92 /// C2.1) The operand is in the form of "X | C", where C is a non-zero
93 /// constant.
94 /// C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
95 /// operand as "E | 0"
96 class llvm::reassociate::XorOpnd {
97 public:
98 XorOpnd(Value *V);
99
isInvalid() const100 bool isInvalid() const { return SymbolicPart == nullptr; }
isOrExpr() const101 bool isOrExpr() const { return isOr; }
getValue() const102 Value *getValue() const { return OrigVal; }
getSymbolicPart() const103 Value *getSymbolicPart() const { return SymbolicPart; }
getSymbolicRank() const104 unsigned getSymbolicRank() const { return SymbolicRank; }
getConstPart() const105 const APInt &getConstPart() const { return ConstPart; }
106
Invalidate()107 void Invalidate() { SymbolicPart = OrigVal = nullptr; }
setSymbolicRank(unsigned R)108 void setSymbolicRank(unsigned R) { SymbolicRank = R; }
109
110 private:
111 Value *OrigVal;
112 Value *SymbolicPart;
113 APInt ConstPart;
114 unsigned SymbolicRank;
115 bool isOr;
116 };
117
XorOpnd(Value * V)118 XorOpnd::XorOpnd(Value *V) {
119 assert(!isa<ConstantInt>(V) && "No ConstantInt");
120 OrigVal = V;
121 Instruction *I = dyn_cast<Instruction>(V);
122 SymbolicRank = 0;
123
124 if (I && (I->getOpcode() == Instruction::Or ||
125 I->getOpcode() == Instruction::And)) {
126 Value *V0 = I->getOperand(0);
127 Value *V1 = I->getOperand(1);
128 const APInt *C;
129 if (match(V0, m_APInt(C)))
130 std::swap(V0, V1);
131
132 if (match(V1, m_APInt(C))) {
133 ConstPart = *C;
134 SymbolicPart = V0;
135 isOr = (I->getOpcode() == Instruction::Or);
136 return;
137 }
138 }
139
140 // view the operand as "V | 0"
141 SymbolicPart = V;
142 ConstPart = APInt::getNullValue(V->getType()->getScalarSizeInBits());
143 isOr = true;
144 }
145
146 /// Return true if V is an instruction of the specified opcode and if it
147 /// only has one use.
isReassociableOp(Value * V,unsigned Opcode)148 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
149 auto *I = dyn_cast<Instruction>(V);
150 if (I && I->hasOneUse() && I->getOpcode() == Opcode)
151 if (!isa<FPMathOperator>(I) || I->isFast())
152 return cast<BinaryOperator>(I);
153 return nullptr;
154 }
155
isReassociableOp(Value * V,unsigned Opcode1,unsigned Opcode2)156 static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1,
157 unsigned Opcode2) {
158 auto *I = dyn_cast<Instruction>(V);
159 if (I && I->hasOneUse() &&
160 (I->getOpcode() == Opcode1 || I->getOpcode() == Opcode2))
161 if (!isa<FPMathOperator>(I) || I->isFast())
162 return cast<BinaryOperator>(I);
163 return nullptr;
164 }
165
BuildRankMap(Function & F,ReversePostOrderTraversal<Function * > & RPOT)166 void ReassociatePass::BuildRankMap(Function &F,
167 ReversePostOrderTraversal<Function*> &RPOT) {
168 unsigned Rank = 2;
169
170 // Assign distinct ranks to function arguments.
171 for (auto &Arg : F.args()) {
172 ValueRankMap[&Arg] = ++Rank;
173 LLVM_DEBUG(dbgs() << "Calculated Rank[" << Arg.getName() << "] = " << Rank
174 << "\n");
175 }
176
177 // Traverse basic blocks in ReversePostOrder.
178 for (BasicBlock *BB : RPOT) {
179 unsigned BBRank = RankMap[BB] = ++Rank << 16;
180
181 // Walk the basic block, adding precomputed ranks for any instructions that
182 // we cannot move. This ensures that the ranks for these instructions are
183 // all different in the block.
184 for (Instruction &I : *BB)
185 if (mayBeMemoryDependent(I))
186 ValueRankMap[&I] = ++BBRank;
187 }
188 }
189
getRank(Value * V)190 unsigned ReassociatePass::getRank(Value *V) {
191 Instruction *I = dyn_cast<Instruction>(V);
192 if (!I) {
193 if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument.
194 return 0; // Otherwise it's a global or constant, rank 0.
195 }
196
197 if (unsigned Rank = ValueRankMap[I])
198 return Rank; // Rank already known?
199
200 // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
201 // we can reassociate expressions for code motion! Since we do not recurse
202 // for PHI nodes, we cannot have infinite recursion here, because there
203 // cannot be loops in the value graph that do not go through PHI nodes.
204 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
205 for (unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i)
206 Rank = std::max(Rank, getRank(I->getOperand(i)));
207
208 // If this is a 'not' or 'neg' instruction, do not count it for rank. This
209 // assures us that X and ~X will have the same rank.
210 if (!match(I, m_Not(m_Value())) && !match(I, m_Neg(m_Value())) &&
211 !match(I, m_FNeg(m_Value())))
212 ++Rank;
213
214 LLVM_DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = " << Rank
215 << "\n");
216
217 return ValueRankMap[I] = Rank;
218 }
219
220 // Canonicalize constants to RHS. Otherwise, sort the operands by rank.
canonicalizeOperands(Instruction * I)221 void ReassociatePass::canonicalizeOperands(Instruction *I) {
222 assert(isa<BinaryOperator>(I) && "Expected binary operator.");
223 assert(I->isCommutative() && "Expected commutative operator.");
224
225 Value *LHS = I->getOperand(0);
226 Value *RHS = I->getOperand(1);
227 if (LHS == RHS || isa<Constant>(RHS))
228 return;
229 if (isa<Constant>(LHS) || getRank(RHS) < getRank(LHS))
230 cast<BinaryOperator>(I)->swapOperands();
231 }
232
CreateAdd(Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)233 static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name,
234 Instruction *InsertBefore, Value *FlagsOp) {
235 if (S1->getType()->isIntOrIntVectorTy())
236 return BinaryOperator::CreateAdd(S1, S2, Name, InsertBefore);
237 else {
238 BinaryOperator *Res =
239 BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
240 Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
241 return Res;
242 }
243 }
244
CreateMul(Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)245 static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name,
246 Instruction *InsertBefore, Value *FlagsOp) {
247 if (S1->getType()->isIntOrIntVectorTy())
248 return BinaryOperator::CreateMul(S1, S2, Name, InsertBefore);
249 else {
250 BinaryOperator *Res =
251 BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
252 Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
253 return Res;
254 }
255 }
256
CreateNeg(Value * S1,const Twine & Name,Instruction * InsertBefore,Value * FlagsOp)257 static BinaryOperator *CreateNeg(Value *S1, const Twine &Name,
258 Instruction *InsertBefore, Value *FlagsOp) {
259 if (S1->getType()->isIntOrIntVectorTy())
260 return BinaryOperator::CreateNeg(S1, Name, InsertBefore);
261 else {
262 BinaryOperator *Res = BinaryOperator::CreateFNeg(S1, Name, InsertBefore);
263 Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
264 return Res;
265 }
266 }
267
268 /// Replace 0-X with X*-1.
LowerNegateToMultiply(Instruction * Neg)269 static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
270 assert((isa<UnaryOperator>(Neg) || isa<BinaryOperator>(Neg)) &&
271 "Expected a Negate!");
272 // FIXME: It's not safe to lower a unary FNeg into a FMul by -1.0.
273 unsigned OpNo = isa<BinaryOperator>(Neg) ? 1 : 0;
274 Type *Ty = Neg->getType();
275 Constant *NegOne = Ty->isIntOrIntVectorTy() ?
276 ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, -1.0);
277
278 BinaryOperator *Res = CreateMul(Neg->getOperand(OpNo), NegOne, "", Neg, Neg);
279 Neg->setOperand(OpNo, Constant::getNullValue(Ty)); // Drop use of op.
280 Res->takeName(Neg);
281 Neg->replaceAllUsesWith(Res);
282 Res->setDebugLoc(Neg->getDebugLoc());
283 return Res;
284 }
285
286 /// Returns k such that lambda(2^Bitwidth) = 2^k, where lambda is the Carmichael
287 /// function. This means that x^(2^k) === 1 mod 2^Bitwidth for
288 /// every odd x, i.e. x^(2^k) = 1 for every odd x in Bitwidth-bit arithmetic.
289 /// Note that 0 <= k < Bitwidth, and if Bitwidth > 3 then x^(2^k) = 0 for every
290 /// even x in Bitwidth-bit arithmetic.
CarmichaelShift(unsigned Bitwidth)291 static unsigned CarmichaelShift(unsigned Bitwidth) {
292 if (Bitwidth < 3)
293 return Bitwidth - 1;
294 return Bitwidth - 2;
295 }
296
297 /// Add the extra weight 'RHS' to the existing weight 'LHS',
298 /// reducing the combined weight using any special properties of the operation.
299 /// The existing weight LHS represents the computation X op X op ... op X where
300 /// X occurs LHS times. The combined weight represents X op X op ... op X with
301 /// X occurring LHS + RHS times. If op is "Xor" for example then the combined
302 /// operation is equivalent to X if LHS + RHS is odd, or 0 if LHS + RHS is even;
303 /// the routine returns 1 in LHS in the first case, and 0 in LHS in the second.
IncorporateWeight(APInt & LHS,const APInt & RHS,unsigned Opcode)304 static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode) {
305 // If we were working with infinite precision arithmetic then the combined
306 // weight would be LHS + RHS. But we are using finite precision arithmetic,
307 // and the APInt sum LHS + RHS may not be correct if it wraps (it is correct
308 // for nilpotent operations and addition, but not for idempotent operations
309 // and multiplication), so it is important to correctly reduce the combined
310 // weight back into range if wrapping would be wrong.
311
312 // If RHS is zero then the weight didn't change.
313 if (RHS.isMinValue())
314 return;
315 // If LHS is zero then the combined weight is RHS.
316 if (LHS.isMinValue()) {
317 LHS = RHS;
318 return;
319 }
320 // From this point on we know that neither LHS nor RHS is zero.
321
322 if (Instruction::isIdempotent(Opcode)) {
323 // Idempotent means X op X === X, so any non-zero weight is equivalent to a
324 // weight of 1. Keeping weights at zero or one also means that wrapping is
325 // not a problem.
326 assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
327 return; // Return a weight of 1.
328 }
329 if (Instruction::isNilpotent(Opcode)) {
330 // Nilpotent means X op X === 0, so reduce weights modulo 2.
331 assert(LHS == 1 && RHS == 1 && "Weights not reduced!");
332 LHS = 0; // 1 + 1 === 0 modulo 2.
333 return;
334 }
335 if (Opcode == Instruction::Add || Opcode == Instruction::FAdd) {
336 // TODO: Reduce the weight by exploiting nsw/nuw?
337 LHS += RHS;
338 return;
339 }
340
341 assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
342 "Unknown associative operation!");
343 unsigned Bitwidth = LHS.getBitWidth();
344 // If CM is the Carmichael number then a weight W satisfying W >= CM+Bitwidth
345 // can be replaced with W-CM. That's because x^W=x^(W-CM) for every Bitwidth
346 // bit number x, since either x is odd in which case x^CM = 1, or x is even in
347 // which case both x^W and x^(W - CM) are zero. By subtracting off multiples
348 // of CM like this weights can always be reduced to the range [0, CM+Bitwidth)
349 // which by a happy accident means that they can always be represented using
350 // Bitwidth bits.
351 // TODO: Reduce the weight by exploiting nsw/nuw? (Could do much better than
352 // the Carmichael number).
353 if (Bitwidth > 3) {
354 /// CM - The value of Carmichael's lambda function.
355 APInt CM = APInt::getOneBitSet(Bitwidth, CarmichaelShift(Bitwidth));
356 // Any weight W >= Threshold can be replaced with W - CM.
357 APInt Threshold = CM + Bitwidth;
358 assert(LHS.ult(Threshold) && RHS.ult(Threshold) && "Weights not reduced!");
359 // For Bitwidth 4 or more the following sum does not overflow.
360 LHS += RHS;
361 while (LHS.uge(Threshold))
362 LHS -= CM;
363 } else {
364 // To avoid problems with overflow do everything the same as above but using
365 // a larger type.
366 unsigned CM = 1U << CarmichaelShift(Bitwidth);
367 unsigned Threshold = CM + Bitwidth;
368 assert(LHS.getZExtValue() < Threshold && RHS.getZExtValue() < Threshold &&
369 "Weights not reduced!");
370 unsigned Total = LHS.getZExtValue() + RHS.getZExtValue();
371 while (Total >= Threshold)
372 Total -= CM;
373 LHS = Total;
374 }
375 }
376
377 using RepeatedValue = std::pair<Value*, APInt>;
378
379 /// Given an associative binary expression, return the leaf
380 /// nodes in Ops along with their weights (how many times the leaf occurs). The
381 /// original expression is the same as
382 /// (Ops[0].first op Ops[0].first op ... Ops[0].first) <- Ops[0].second times
383 /// op
384 /// (Ops[1].first op Ops[1].first op ... Ops[1].first) <- Ops[1].second times
385 /// op
386 /// ...
387 /// op
388 /// (Ops[N].first op Ops[N].first op ... Ops[N].first) <- Ops[N].second times
389 ///
390 /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
391 ///
392 /// This routine may modify the function, in which case it returns 'true'. The
393 /// changes it makes may well be destructive, changing the value computed by 'I'
394 /// to something completely different. Thus if the routine returns 'true' then
395 /// you MUST either replace I with a new expression computed from the Ops array,
396 /// or use RewriteExprTree to put the values back in.
397 ///
398 /// A leaf node is either not a binary operation of the same kind as the root
399 /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
400 /// opcode), or is the same kind of binary operator but has a use which either
401 /// does not belong to the expression, or does belong to the expression but is
402 /// a leaf node. Every leaf node has at least one use that is a non-leaf node
403 /// of the expression, while for non-leaf nodes (except for the root 'I') every
404 /// use is a non-leaf node of the expression.
405 ///
406 /// For example:
407 /// expression graph node names
408 ///
409 /// + | I
410 /// / \ |
411 /// + + | A, B
412 /// / \ / \ |
413 /// * + * | C, D, E
414 /// / \ / \ / \ |
415 /// + * | F, G
416 ///
417 /// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in
418 /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
419 ///
420 /// The expression is maximal: if some instruction is a binary operator of the
421 /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
422 /// then the instruction also belongs to the expression, is not a leaf node of
423 /// it, and its operands also belong to the expression (but may be leaf nodes).
424 ///
425 /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
426 /// order to ensure that every non-root node in the expression has *exactly one*
427 /// use by a non-leaf node of the expression. This destruction means that the
428 /// caller MUST either replace 'I' with a new expression or use something like
429 /// RewriteExprTree to put the values back in if the routine indicates that it
430 /// made a change by returning 'true'.
431 ///
432 /// In the above example either the right operand of A or the left operand of B
433 /// will be replaced by undef. If it is B's operand then this gives:
434 ///
435 /// + | I
436 /// / \ |
437 /// + + | A, B - operand of B replaced with undef
438 /// / \ \ |
439 /// * + * | C, D, E
440 /// / \ / \ / \ |
441 /// + * | F, G
442 ///
443 /// Note that such undef operands can only be reached by passing through 'I'.
444 /// For example, if you visit operands recursively starting from a leaf node
445 /// then you will never see such an undef operand unless you get back to 'I',
446 /// which requires passing through a phi node.
447 ///
448 /// Note that this routine may also mutate binary operators of the wrong type
449 /// that have all uses inside the expression (i.e. only used by non-leaf nodes
450 /// of the expression) if it can turn them into binary operators of the right
451 /// type and thus make the expression bigger.
LinearizeExprTree(Instruction * I,SmallVectorImpl<RepeatedValue> & Ops)452 static bool LinearizeExprTree(Instruction *I,
453 SmallVectorImpl<RepeatedValue> &Ops) {
454 assert((isa<UnaryOperator>(I) || isa<BinaryOperator>(I)) &&
455 "Expected a UnaryOperator or BinaryOperator!");
456 LLVM_DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
457 unsigned Bitwidth = I->getType()->getScalarType()->getPrimitiveSizeInBits();
458 unsigned Opcode = I->getOpcode();
459 assert(I->isAssociative() && I->isCommutative() &&
460 "Expected an associative and commutative operation!");
461
462 // Visit all operands of the expression, keeping track of their weight (the
463 // number of paths from the expression root to the operand, or if you like
464 // the number of times that operand occurs in the linearized expression).
465 // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
466 // while A has weight two.
467
468 // Worklist of non-leaf nodes (their operands are in the expression too) along
469 // with their weights, representing a certain number of paths to the operator.
470 // If an operator occurs in the worklist multiple times then we found multiple
471 // ways to get to it.
472 SmallVector<std::pair<Instruction*, APInt>, 8> Worklist; // (Op, Weight)
473 Worklist.push_back(std::make_pair(I, APInt(Bitwidth, 1)));
474 bool Changed = false;
475
476 // Leaves of the expression are values that either aren't the right kind of
477 // operation (eg: a constant, or a multiply in an add tree), or are, but have
478 // some uses that are not inside the expression. For example, in I = X + X,
479 // X = A + B, the value X has two uses (by I) that are in the expression. If
480 // X has any other uses, for example in a return instruction, then we consider
481 // X to be a leaf, and won't analyze it further. When we first visit a value,
482 // if it has more than one use then at first we conservatively consider it to
483 // be a leaf. Later, as the expression is explored, we may discover some more
484 // uses of the value from inside the expression. If all uses turn out to be
485 // from within the expression (and the value is a binary operator of the right
486 // kind) then the value is no longer considered to be a leaf, and its operands
487 // are explored.
488
489 // Leaves - Keeps track of the set of putative leaves as well as the number of
490 // paths to each leaf seen so far.
491 using LeafMap = DenseMap<Value *, APInt>;
492 LeafMap Leaves; // Leaf -> Total weight so far.
493 SmallVector<Value *, 8> LeafOrder; // Ensure deterministic leaf output order.
494
495 #ifndef NDEBUG
496 SmallPtrSet<Value *, 8> Visited; // For sanity checking the iteration scheme.
497 #endif
498 while (!Worklist.empty()) {
499 std::pair<Instruction*, APInt> P = Worklist.pop_back_val();
500 I = P.first; // We examine the operands of this binary operator.
501
502 for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); ++OpIdx) { // Visit operands.
503 Value *Op = I->getOperand(OpIdx);
504 APInt Weight = P.second; // Number of paths to this operand.
505 LLVM_DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
506 assert(!Op->use_empty() && "No uses, so how did we get to it?!");
507
508 // If this is a binary operation of the right kind with only one use then
509 // add its operands to the expression.
510 if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
511 assert(Visited.insert(Op).second && "Not first visit!");
512 LLVM_DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
513 Worklist.push_back(std::make_pair(BO, Weight));
514 continue;
515 }
516
517 // Appears to be a leaf. Is the operand already in the set of leaves?
518 LeafMap::iterator It = Leaves.find(Op);
519 if (It == Leaves.end()) {
520 // Not in the leaf map. Must be the first time we saw this operand.
521 assert(Visited.insert(Op).second && "Not first visit!");
522 if (!Op->hasOneUse()) {
523 // This value has uses not accounted for by the expression, so it is
524 // not safe to modify. Mark it as being a leaf.
525 LLVM_DEBUG(dbgs()
526 << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
527 LeafOrder.push_back(Op);
528 Leaves[Op] = Weight;
529 continue;
530 }
531 // No uses outside the expression, try morphing it.
532 } else {
533 // Already in the leaf map.
534 assert(It != Leaves.end() && Visited.count(Op) &&
535 "In leaf map but not visited!");
536
537 // Update the number of paths to the leaf.
538 IncorporateWeight(It->second, Weight, Opcode);
539
540 #if 0 // TODO: Re-enable once PR13021 is fixed.
541 // The leaf already has one use from inside the expression. As we want
542 // exactly one such use, drop this new use of the leaf.
543 assert(!Op->hasOneUse() && "Only one use, but we got here twice!");
544 I->setOperand(OpIdx, UndefValue::get(I->getType()));
545 Changed = true;
546
547 // If the leaf is a binary operation of the right kind and we now see
548 // that its multiple original uses were in fact all by nodes belonging
549 // to the expression, then no longer consider it to be a leaf and add
550 // its operands to the expression.
551 if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
552 LLVM_DEBUG(dbgs() << "UNLEAF: " << *Op << " (" << It->second << ")\n");
553 Worklist.push_back(std::make_pair(BO, It->second));
554 Leaves.erase(It);
555 continue;
556 }
557 #endif
558
559 // If we still have uses that are not accounted for by the expression
560 // then it is not safe to modify the value.
561 if (!Op->hasOneUse())
562 continue;
563
564 // No uses outside the expression, try morphing it.
565 Weight = It->second;
566 Leaves.erase(It); // Since the value may be morphed below.
567 }
568
569 // At this point we have a value which, first of all, is not a binary
570 // expression of the right kind, and secondly, is only used inside the
571 // expression. This means that it can safely be modified. See if we
572 // can usefully morph it into an expression of the right kind.
573 assert((!isa<Instruction>(Op) ||
574 cast<Instruction>(Op)->getOpcode() != Opcode
575 || (isa<FPMathOperator>(Op) &&
576 !cast<Instruction>(Op)->isFast())) &&
577 "Should have been handled above!");
578 assert(Op->hasOneUse() && "Has uses outside the expression tree!");
579
580 // If this is a multiply expression, turn any internal negations into
581 // multiplies by -1 so they can be reassociated.
582 if (Instruction *Tmp = dyn_cast<Instruction>(Op))
583 if ((Opcode == Instruction::Mul && match(Tmp, m_Neg(m_Value()))) ||
584 (Opcode == Instruction::FMul && match(Tmp, m_FNeg(m_Value())))) {
585 LLVM_DEBUG(dbgs()
586 << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
587 Tmp = LowerNegateToMultiply(Tmp);
588 LLVM_DEBUG(dbgs() << *Tmp << '\n');
589 Worklist.push_back(std::make_pair(Tmp, Weight));
590 Changed = true;
591 continue;
592 }
593
594 // Failed to morph into an expression of the right type. This really is
595 // a leaf.
596 LLVM_DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
597 assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
598 LeafOrder.push_back(Op);
599 Leaves[Op] = Weight;
600 }
601 }
602
603 // The leaves, repeated according to their weights, represent the linearized
604 // form of the expression.
605 for (unsigned i = 0, e = LeafOrder.size(); i != e; ++i) {
606 Value *V = LeafOrder[i];
607 LeafMap::iterator It = Leaves.find(V);
608 if (It == Leaves.end())
609 // Node initially thought to be a leaf wasn't.
610 continue;
611 assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
612 APInt Weight = It->second;
613 if (Weight.isMinValue())
614 // Leaf already output or weight reduction eliminated it.
615 continue;
616 // Ensure the leaf is only output once.
617 It->second = 0;
618 Ops.push_back(std::make_pair(V, Weight));
619 }
620
621 // For nilpotent operations or addition there may be no operands, for example
622 // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
623 // in both cases the weight reduces to 0 causing the value to be skipped.
624 if (Ops.empty()) {
625 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
626 assert(Identity && "Associative operation without identity!");
627 Ops.emplace_back(Identity, APInt(Bitwidth, 1));
628 }
629
630 return Changed;
631 }
632
633 /// Now that the operands for this expression tree are
634 /// linearized and optimized, emit them in-order.
RewriteExprTree(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)635 void ReassociatePass::RewriteExprTree(BinaryOperator *I,
636 SmallVectorImpl<ValueEntry> &Ops) {
637 assert(Ops.size() > 1 && "Single values should be used directly!");
638
639 // Since our optimizations should never increase the number of operations, the
640 // new expression can usually be written reusing the existing binary operators
641 // from the original expression tree, without creating any new instructions,
642 // though the rewritten expression may have a completely different topology.
643 // We take care to not change anything if the new expression will be the same
644 // as the original. If more than trivial changes (like commuting operands)
645 // were made then we are obliged to clear out any optional subclass data like
646 // nsw flags.
647
648 /// NodesToRewrite - Nodes from the original expression available for writing
649 /// the new expression into.
650 SmallVector<BinaryOperator*, 8> NodesToRewrite;
651 unsigned Opcode = I->getOpcode();
652 BinaryOperator *Op = I;
653
654 /// NotRewritable - The operands being written will be the leaves of the new
655 /// expression and must not be used as inner nodes (via NodesToRewrite) by
656 /// mistake. Inner nodes are always reassociable, and usually leaves are not
657 /// (if they were they would have been incorporated into the expression and so
658 /// would not be leaves), so most of the time there is no danger of this. But
659 /// in rare cases a leaf may become reassociable if an optimization kills uses
660 /// of it, or it may momentarily become reassociable during rewriting (below)
661 /// due it being removed as an operand of one of its uses. Ensure that misuse
662 /// of leaf nodes as inner nodes cannot occur by remembering all of the future
663 /// leaves and refusing to reuse any of them as inner nodes.
664 SmallPtrSet<Value*, 8> NotRewritable;
665 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
666 NotRewritable.insert(Ops[i].Op);
667
668 // ExpressionChanged - Non-null if the rewritten expression differs from the
669 // original in some non-trivial way, requiring the clearing of optional flags.
670 // Flags are cleared from the operator in ExpressionChanged up to I inclusive.
671 BinaryOperator *ExpressionChanged = nullptr;
672 for (unsigned i = 0; ; ++i) {
673 // The last operation (which comes earliest in the IR) is special as both
674 // operands will come from Ops, rather than just one with the other being
675 // a subexpression.
676 if (i+2 == Ops.size()) {
677 Value *NewLHS = Ops[i].Op;
678 Value *NewRHS = Ops[i+1].Op;
679 Value *OldLHS = Op->getOperand(0);
680 Value *OldRHS = Op->getOperand(1);
681
682 if (NewLHS == OldLHS && NewRHS == OldRHS)
683 // Nothing changed, leave it alone.
684 break;
685
686 if (NewLHS == OldRHS && NewRHS == OldLHS) {
687 // The order of the operands was reversed. Swap them.
688 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
689 Op->swapOperands();
690 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
691 MadeChange = true;
692 ++NumChanged;
693 break;
694 }
695
696 // The new operation differs non-trivially from the original. Overwrite
697 // the old operands with the new ones.
698 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
699 if (NewLHS != OldLHS) {
700 BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
701 if (BO && !NotRewritable.count(BO))
702 NodesToRewrite.push_back(BO);
703 Op->setOperand(0, NewLHS);
704 }
705 if (NewRHS != OldRHS) {
706 BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
707 if (BO && !NotRewritable.count(BO))
708 NodesToRewrite.push_back(BO);
709 Op->setOperand(1, NewRHS);
710 }
711 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
712
713 ExpressionChanged = Op;
714 MadeChange = true;
715 ++NumChanged;
716
717 break;
718 }
719
720 // Not the last operation. The left-hand side will be a sub-expression
721 // while the right-hand side will be the current element of Ops.
722 Value *NewRHS = Ops[i].Op;
723 if (NewRHS != Op->getOperand(1)) {
724 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
725 if (NewRHS == Op->getOperand(0)) {
726 // The new right-hand side was already present as the left operand. If
727 // we are lucky then swapping the operands will sort out both of them.
728 Op->swapOperands();
729 } else {
730 // Overwrite with the new right-hand side.
731 BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
732 if (BO && !NotRewritable.count(BO))
733 NodesToRewrite.push_back(BO);
734 Op->setOperand(1, NewRHS);
735 ExpressionChanged = Op;
736 }
737 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
738 MadeChange = true;
739 ++NumChanged;
740 }
741
742 // Now deal with the left-hand side. If this is already an operation node
743 // from the original expression then just rewrite the rest of the expression
744 // into it.
745 BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
746 if (BO && !NotRewritable.count(BO)) {
747 Op = BO;
748 continue;
749 }
750
751 // Otherwise, grab a spare node from the original expression and use that as
752 // the left-hand side. If there are no nodes left then the optimizers made
753 // an expression with more nodes than the original! This usually means that
754 // they did something stupid but it might mean that the problem was just too
755 // hard (finding the mimimal number of multiplications needed to realize a
756 // multiplication expression is NP-complete). Whatever the reason, smart or
757 // stupid, create a new node if there are none left.
758 BinaryOperator *NewOp;
759 if (NodesToRewrite.empty()) {
760 Constant *Undef = UndefValue::get(I->getType());
761 NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode),
762 Undef, Undef, "", I);
763 if (NewOp->getType()->isFPOrFPVectorTy())
764 NewOp->setFastMathFlags(I->getFastMathFlags());
765 } else {
766 NewOp = NodesToRewrite.pop_back_val();
767 }
768
769 LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
770 Op->setOperand(0, NewOp);
771 LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
772 ExpressionChanged = Op;
773 MadeChange = true;
774 ++NumChanged;
775 Op = NewOp;
776 }
777
778 // If the expression changed non-trivially then clear out all subclass data
779 // starting from the operator specified in ExpressionChanged, and compactify
780 // the operators to just before the expression root to guarantee that the
781 // expression tree is dominated by all of Ops.
782 if (ExpressionChanged)
783 do {
784 // Preserve FastMathFlags.
785 if (isa<FPMathOperator>(I)) {
786 FastMathFlags Flags = I->getFastMathFlags();
787 ExpressionChanged->clearSubclassOptionalData();
788 ExpressionChanged->setFastMathFlags(Flags);
789 } else
790 ExpressionChanged->clearSubclassOptionalData();
791
792 if (ExpressionChanged == I)
793 break;
794
795 // Discard any debug info related to the expressions that has changed (we
796 // can leave debug infor related to the root, since the result of the
797 // expression tree should be the same even after reassociation).
798 replaceDbgUsesWithUndef(ExpressionChanged);
799
800 ExpressionChanged->moveBefore(I);
801 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->user_begin());
802 } while (true);
803
804 // Throw away any left over nodes from the original expression.
805 for (unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
806 RedoInsts.insert(NodesToRewrite[i]);
807 }
808
809 /// Insert instructions before the instruction pointed to by BI,
810 /// that computes the negative version of the value specified. The negative
811 /// version of the value is returned, and BI is left pointing at the instruction
812 /// that should be processed next by the reassociation pass.
813 /// Also add intermediate instructions to the redo list that are modified while
814 /// pushing the negates through adds. These will be revisited to see if
815 /// additional opportunities have been exposed.
NegateValue(Value * V,Instruction * BI,ReassociatePass::OrderedSet & ToRedo)816 static Value *NegateValue(Value *V, Instruction *BI,
817 ReassociatePass::OrderedSet &ToRedo) {
818 if (auto *C = dyn_cast<Constant>(V))
819 return C->getType()->isFPOrFPVectorTy() ? ConstantExpr::getFNeg(C) :
820 ConstantExpr::getNeg(C);
821
822 // We are trying to expose opportunity for reassociation. One of the things
823 // that we want to do to achieve this is to push a negation as deep into an
824 // expression chain as possible, to expose the add instructions. In practice,
825 // this means that we turn this:
826 // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
827 // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
828 // the constants. We assume that instcombine will clean up the mess later if
829 // we introduce tons of unnecessary negation instructions.
830 //
831 if (BinaryOperator *I =
832 isReassociableOp(V, Instruction::Add, Instruction::FAdd)) {
833 // Push the negates through the add.
834 I->setOperand(0, NegateValue(I->getOperand(0), BI, ToRedo));
835 I->setOperand(1, NegateValue(I->getOperand(1), BI, ToRedo));
836 if (I->getOpcode() == Instruction::Add) {
837 I->setHasNoUnsignedWrap(false);
838 I->setHasNoSignedWrap(false);
839 }
840
841 // We must move the add instruction here, because the neg instructions do
842 // not dominate the old add instruction in general. By moving it, we are
843 // assured that the neg instructions we just inserted dominate the
844 // instruction we are about to insert after them.
845 //
846 I->moveBefore(BI);
847 I->setName(I->getName()+".neg");
848
849 // Add the intermediate negates to the redo list as processing them later
850 // could expose more reassociating opportunities.
851 ToRedo.insert(I);
852 return I;
853 }
854
855 // Okay, we need to materialize a negated version of V with an instruction.
856 // Scan the use lists of V to see if we have one already.
857 for (User *U : V->users()) {
858 if (!match(U, m_Neg(m_Value())) && !match(U, m_FNeg(m_Value())))
859 continue;
860
861 // We found one! Now we have to make sure that the definition dominates
862 // this use. We do this by moving it to the entry block (if it is a
863 // non-instruction value) or right after the definition. These negates will
864 // be zapped by reassociate later, so we don't need much finesse here.
865 Instruction *TheNeg = cast<Instruction>(U);
866
867 // Verify that the negate is in this function, V might be a constant expr.
868 if (TheNeg->getParent()->getParent() != BI->getParent()->getParent())
869 continue;
870
871 bool FoundCatchSwitch = false;
872
873 BasicBlock::iterator InsertPt;
874 if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
875 if (InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
876 InsertPt = II->getNormalDest()->begin();
877 } else {
878 InsertPt = ++InstInput->getIterator();
879 }
880
881 const BasicBlock *BB = InsertPt->getParent();
882
883 // Make sure we don't move anything before PHIs or exception
884 // handling pads.
885 while (InsertPt != BB->end() && (isa<PHINode>(InsertPt) ||
886 InsertPt->isEHPad())) {
887 if (isa<CatchSwitchInst>(InsertPt))
888 // A catchswitch cannot have anything in the block except
889 // itself and PHIs. We'll bail out below.
890 FoundCatchSwitch = true;
891 ++InsertPt;
892 }
893 } else {
894 InsertPt = TheNeg->getParent()->getParent()->getEntryBlock().begin();
895 }
896
897 // We found a catchswitch in the block where we want to move the
898 // neg. We cannot move anything into that block. Bail and just
899 // create the neg before BI, as if we hadn't found an existing
900 // neg.
901 if (FoundCatchSwitch)
902 break;
903
904 TheNeg->moveBefore(&*InsertPt);
905 if (TheNeg->getOpcode() == Instruction::Sub) {
906 TheNeg->setHasNoUnsignedWrap(false);
907 TheNeg->setHasNoSignedWrap(false);
908 } else {
909 TheNeg->andIRFlags(BI);
910 }
911 ToRedo.insert(TheNeg);
912 return TheNeg;
913 }
914
915 // Insert a 'neg' instruction that subtracts the value from zero to get the
916 // negation.
917 BinaryOperator *NewNeg = CreateNeg(V, V->getName() + ".neg", BI, BI);
918 ToRedo.insert(NewNeg);
919 return NewNeg;
920 }
921
922 /// Return true if we should break up this subtract of X-Y into (X + -Y).
ShouldBreakUpSubtract(Instruction * Sub)923 static bool ShouldBreakUpSubtract(Instruction *Sub) {
924 // If this is a negation, we can't split it up!
925 if (match(Sub, m_Neg(m_Value())) || match(Sub, m_FNeg(m_Value())))
926 return false;
927
928 // Don't breakup X - undef.
929 if (isa<UndefValue>(Sub->getOperand(1)))
930 return false;
931
932 // Don't bother to break this up unless either the LHS is an associable add or
933 // subtract or if this is only used by one.
934 Value *V0 = Sub->getOperand(0);
935 if (isReassociableOp(V0, Instruction::Add, Instruction::FAdd) ||
936 isReassociableOp(V0, Instruction::Sub, Instruction::FSub))
937 return true;
938 Value *V1 = Sub->getOperand(1);
939 if (isReassociableOp(V1, Instruction::Add, Instruction::FAdd) ||
940 isReassociableOp(V1, Instruction::Sub, Instruction::FSub))
941 return true;
942 Value *VB = Sub->user_back();
943 if (Sub->hasOneUse() &&
944 (isReassociableOp(VB, Instruction::Add, Instruction::FAdd) ||
945 isReassociableOp(VB, Instruction::Sub, Instruction::FSub)))
946 return true;
947
948 return false;
949 }
950
951 /// If we have (X-Y), and if either X is an add, or if this is only used by an
952 /// add, transform this into (X+(0-Y)) to promote better reassociation.
BreakUpSubtract(Instruction * Sub,ReassociatePass::OrderedSet & ToRedo)953 static BinaryOperator *BreakUpSubtract(Instruction *Sub,
954 ReassociatePass::OrderedSet &ToRedo) {
955 // Convert a subtract into an add and a neg instruction. This allows sub
956 // instructions to be commuted with other add instructions.
957 //
958 // Calculate the negative value of Operand 1 of the sub instruction,
959 // and set it as the RHS of the add instruction we just made.
960 Value *NegVal = NegateValue(Sub->getOperand(1), Sub, ToRedo);
961 BinaryOperator *New = CreateAdd(Sub->getOperand(0), NegVal, "", Sub, Sub);
962 Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
963 Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
964 New->takeName(Sub);
965
966 // Everyone now refers to the add instruction.
967 Sub->replaceAllUsesWith(New);
968 New->setDebugLoc(Sub->getDebugLoc());
969
970 LLVM_DEBUG(dbgs() << "Negated: " << *New << '\n');
971 return New;
972 }
973
974 /// If this is a shift of a reassociable multiply or is used by one, change
975 /// this into a multiply by a constant to assist with further reassociation.
ConvertShiftToMul(Instruction * Shl)976 static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
977 Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
978 MulCst = ConstantExpr::getShl(MulCst, cast<Constant>(Shl->getOperand(1)));
979
980 BinaryOperator *Mul =
981 BinaryOperator::CreateMul(Shl->getOperand(0), MulCst, "", Shl);
982 Shl->setOperand(0, UndefValue::get(Shl->getType())); // Drop use of op.
983 Mul->takeName(Shl);
984
985 // Everyone now refers to the mul instruction.
986 Shl->replaceAllUsesWith(Mul);
987 Mul->setDebugLoc(Shl->getDebugLoc());
988
989 // We can safely preserve the nuw flag in all cases. It's also safe to turn a
990 // nuw nsw shl into a nuw nsw mul. However, nsw in isolation requires special
991 // handling.
992 bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
993 bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
994 if (NSW && NUW)
995 Mul->setHasNoSignedWrap(true);
996 Mul->setHasNoUnsignedWrap(NUW);
997 return Mul;
998 }
999
1000 /// Scan backwards and forwards among values with the same rank as element i
1001 /// to see if X exists. If X does not exist, return i. This is useful when
1002 /// scanning for 'x' when we see '-x' because they both get the same rank.
FindInOperandList(const SmallVectorImpl<ValueEntry> & Ops,unsigned i,Value * X)1003 static unsigned FindInOperandList(const SmallVectorImpl<ValueEntry> &Ops,
1004 unsigned i, Value *X) {
1005 unsigned XRank = Ops[i].Rank;
1006 unsigned e = Ops.size();
1007 for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
1008 if (Ops[j].Op == X)
1009 return j;
1010 if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
1011 if (Instruction *I2 = dyn_cast<Instruction>(X))
1012 if (I1->isIdenticalTo(I2))
1013 return j;
1014 }
1015 // Scan backwards.
1016 for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
1017 if (Ops[j].Op == X)
1018 return j;
1019 if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
1020 if (Instruction *I2 = dyn_cast<Instruction>(X))
1021 if (I1->isIdenticalTo(I2))
1022 return j;
1023 }
1024 return i;
1025 }
1026
1027 /// Emit a tree of add instructions, summing Ops together
1028 /// and returning the result. Insert the tree before I.
EmitAddTreeOfValues(Instruction * I,SmallVectorImpl<WeakTrackingVH> & Ops)1029 static Value *EmitAddTreeOfValues(Instruction *I,
1030 SmallVectorImpl<WeakTrackingVH> &Ops) {
1031 if (Ops.size() == 1) return Ops.back();
1032
1033 Value *V1 = Ops.back();
1034 Ops.pop_back();
1035 Value *V2 = EmitAddTreeOfValues(I, Ops);
1036 return CreateAdd(V2, V1, "reass.add", I, I);
1037 }
1038
1039 /// If V is an expression tree that is a multiplication sequence,
1040 /// and if this sequence contains a multiply by Factor,
1041 /// remove Factor from the tree and return the new tree.
RemoveFactorFromExpression(Value * V,Value * Factor)1042 Value *ReassociatePass::RemoveFactorFromExpression(Value *V, Value *Factor) {
1043 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
1044 if (!BO)
1045 return nullptr;
1046
1047 SmallVector<RepeatedValue, 8> Tree;
1048 MadeChange |= LinearizeExprTree(BO, Tree);
1049 SmallVector<ValueEntry, 8> Factors;
1050 Factors.reserve(Tree.size());
1051 for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
1052 RepeatedValue E = Tree[i];
1053 Factors.append(E.second.getZExtValue(),
1054 ValueEntry(getRank(E.first), E.first));
1055 }
1056
1057 bool FoundFactor = false;
1058 bool NeedsNegate = false;
1059 for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1060 if (Factors[i].Op == Factor) {
1061 FoundFactor = true;
1062 Factors.erase(Factors.begin()+i);
1063 break;
1064 }
1065
1066 // If this is a negative version of this factor, remove it.
1067 if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1068 if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
1069 if (FC1->getValue() == -FC2->getValue()) {
1070 FoundFactor = NeedsNegate = true;
1071 Factors.erase(Factors.begin()+i);
1072 break;
1073 }
1074 } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1075 if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) {
1076 const APFloat &F1 = FC1->getValueAPF();
1077 APFloat F2(FC2->getValueAPF());
1078 F2.changeSign();
1079 if (F1.compare(F2) == APFloat::cmpEqual) {
1080 FoundFactor = NeedsNegate = true;
1081 Factors.erase(Factors.begin() + i);
1082 break;
1083 }
1084 }
1085 }
1086 }
1087
1088 if (!FoundFactor) {
1089 // Make sure to restore the operands to the expression tree.
1090 RewriteExprTree(BO, Factors);
1091 return nullptr;
1092 }
1093
1094 BasicBlock::iterator InsertPt = ++BO->getIterator();
1095
1096 // If this was just a single multiply, remove the multiply and return the only
1097 // remaining operand.
1098 if (Factors.size() == 1) {
1099 RedoInsts.insert(BO);
1100 V = Factors[0].Op;
1101 } else {
1102 RewriteExprTree(BO, Factors);
1103 V = BO;
1104 }
1105
1106 if (NeedsNegate)
1107 V = CreateNeg(V, "neg", &*InsertPt, BO);
1108
1109 return V;
1110 }
1111
1112 /// If V is a single-use multiply, recursively add its operands as factors,
1113 /// otherwise add V to the list of factors.
1114 ///
1115 /// Ops is the top-level list of add operands we're trying to factor.
FindSingleUseMultiplyFactors(Value * V,SmallVectorImpl<Value * > & Factors)1116 static void FindSingleUseMultiplyFactors(Value *V,
1117 SmallVectorImpl<Value*> &Factors) {
1118 BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
1119 if (!BO) {
1120 Factors.push_back(V);
1121 return;
1122 }
1123
1124 // Otherwise, add the LHS and RHS to the list of factors.
1125 FindSingleUseMultiplyFactors(BO->getOperand(1), Factors);
1126 FindSingleUseMultiplyFactors(BO->getOperand(0), Factors);
1127 }
1128
1129 /// Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
1130 /// This optimizes based on identities. If it can be reduced to a single Value,
1131 /// it is returned, otherwise the Ops list is mutated as necessary.
OptimizeAndOrXor(unsigned Opcode,SmallVectorImpl<ValueEntry> & Ops)1132 static Value *OptimizeAndOrXor(unsigned Opcode,
1133 SmallVectorImpl<ValueEntry> &Ops) {
1134 // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
1135 // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
1136 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1137 // First, check for X and ~X in the operand list.
1138 assert(i < Ops.size());
1139 Value *X;
1140 if (match(Ops[i].Op, m_Not(m_Value(X)))) { // Cannot occur for ^.
1141 unsigned FoundX = FindInOperandList(Ops, i, X);
1142 if (FoundX != i) {
1143 if (Opcode == Instruction::And) // ...&X&~X = 0
1144 return Constant::getNullValue(X->getType());
1145
1146 if (Opcode == Instruction::Or) // ...|X|~X = -1
1147 return Constant::getAllOnesValue(X->getType());
1148 }
1149 }
1150
1151 // Next, check for duplicate pairs of values, which we assume are next to
1152 // each other, due to our sorting criteria.
1153 assert(i < Ops.size());
1154 if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
1155 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1156 // Drop duplicate values for And and Or.
1157 Ops.erase(Ops.begin()+i);
1158 --i; --e;
1159 ++NumAnnihil;
1160 continue;
1161 }
1162
1163 // Drop pairs of values for Xor.
1164 assert(Opcode == Instruction::Xor);
1165 if (e == 2)
1166 return Constant::getNullValue(Ops[0].Op->getType());
1167
1168 // Y ^ X^X -> Y
1169 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1170 i -= 1; e -= 2;
1171 ++NumAnnihil;
1172 }
1173 }
1174 return nullptr;
1175 }
1176
1177 /// Helper function of CombineXorOpnd(). It creates a bitwise-and
1178 /// instruction with the given two operands, and return the resulting
1179 /// instruction. There are two special cases: 1) if the constant operand is 0,
1180 /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
1181 /// be returned.
createAndInstr(Instruction * InsertBefore,Value * Opnd,const APInt & ConstOpnd)1182 static Value *createAndInstr(Instruction *InsertBefore, Value *Opnd,
1183 const APInt &ConstOpnd) {
1184 if (ConstOpnd.isNullValue())
1185 return nullptr;
1186
1187 if (ConstOpnd.isAllOnesValue())
1188 return Opnd;
1189
1190 Instruction *I = BinaryOperator::CreateAnd(
1191 Opnd, ConstantInt::get(Opnd->getType(), ConstOpnd), "and.ra",
1192 InsertBefore);
1193 I->setDebugLoc(InsertBefore->getDebugLoc());
1194 return I;
1195 }
1196
1197 // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
1198 // into "R ^ C", where C would be 0, and R is a symbolic value.
1199 //
1200 // If it was successful, true is returned, and the "R" and "C" is returned
1201 // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
1202 // and both "Res" and "ConstOpnd" remain unchanged.
CombineXorOpnd(Instruction * I,XorOpnd * Opnd1,APInt & ConstOpnd,Value * & Res)1203 bool ReassociatePass::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
1204 APInt &ConstOpnd, Value *&Res) {
1205 // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
1206 // = ((x | c1) ^ c1) ^ (c1 ^ c2)
1207 // = (x & ~c1) ^ (c1 ^ c2)
1208 // It is useful only when c1 == c2.
1209 if (!Opnd1->isOrExpr() || Opnd1->getConstPart().isNullValue())
1210 return false;
1211
1212 if (!Opnd1->getValue()->hasOneUse())
1213 return false;
1214
1215 const APInt &C1 = Opnd1->getConstPart();
1216 if (C1 != ConstOpnd)
1217 return false;
1218
1219 Value *X = Opnd1->getSymbolicPart();
1220 Res = createAndInstr(I, X, ~C1);
1221 // ConstOpnd was C2, now C1 ^ C2.
1222 ConstOpnd ^= C1;
1223
1224 if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1225 RedoInsts.insert(T);
1226 return true;
1227 }
1228
1229 // Helper function of OptimizeXor(). It tries to simplify
1230 // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
1231 // symbolic value.
1232 //
1233 // If it was successful, true is returned, and the "R" and "C" is returned
1234 // via "Res" and "ConstOpnd", respectively (If the entire expression is
1235 // evaluated to a constant, the Res is set to NULL); otherwise, false is
1236 // returned, and both "Res" and "ConstOpnd" remain unchanged.
CombineXorOpnd(Instruction * I,XorOpnd * Opnd1,XorOpnd * Opnd2,APInt & ConstOpnd,Value * & Res)1237 bool ReassociatePass::CombineXorOpnd(Instruction *I, XorOpnd *Opnd1,
1238 XorOpnd *Opnd2, APInt &ConstOpnd,
1239 Value *&Res) {
1240 Value *X = Opnd1->getSymbolicPart();
1241 if (X != Opnd2->getSymbolicPart())
1242 return false;
1243
1244 // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
1245 int DeadInstNum = 1;
1246 if (Opnd1->getValue()->hasOneUse())
1247 DeadInstNum++;
1248 if (Opnd2->getValue()->hasOneUse())
1249 DeadInstNum++;
1250
1251 // Xor-Rule 2:
1252 // (x | c1) ^ (x & c2)
1253 // = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
1254 // = (x & ~c1) ^ (x & c2) ^ c1 // Xor-Rule 1
1255 // = (x & c3) ^ c1, where c3 = ~c1 ^ c2 // Xor-rule 3
1256 //
1257 if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
1258 if (Opnd2->isOrExpr())
1259 std::swap(Opnd1, Opnd2);
1260
1261 const APInt &C1 = Opnd1->getConstPart();
1262 const APInt &C2 = Opnd2->getConstPart();
1263 APInt C3((~C1) ^ C2);
1264
1265 // Do not increase code size!
1266 if (!C3.isNullValue() && !C3.isAllOnesValue()) {
1267 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
1268 if (NewInstNum > DeadInstNum)
1269 return false;
1270 }
1271
1272 Res = createAndInstr(I, X, C3);
1273 ConstOpnd ^= C1;
1274 } else if (Opnd1->isOrExpr()) {
1275 // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
1276 //
1277 const APInt &C1 = Opnd1->getConstPart();
1278 const APInt &C2 = Opnd2->getConstPart();
1279 APInt C3 = C1 ^ C2;
1280
1281 // Do not increase code size
1282 if (!C3.isNullValue() && !C3.isAllOnesValue()) {
1283 int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
1284 if (NewInstNum > DeadInstNum)
1285 return false;
1286 }
1287
1288 Res = createAndInstr(I, X, C3);
1289 ConstOpnd ^= C3;
1290 } else {
1291 // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
1292 //
1293 const APInt &C1 = Opnd1->getConstPart();
1294 const APInt &C2 = Opnd2->getConstPart();
1295 APInt C3 = C1 ^ C2;
1296 Res = createAndInstr(I, X, C3);
1297 }
1298
1299 // Put the original operands in the Redo list; hope they will be deleted
1300 // as dead code.
1301 if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
1302 RedoInsts.insert(T);
1303 if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
1304 RedoInsts.insert(T);
1305
1306 return true;
1307 }
1308
1309 /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
1310 /// to a single Value, it is returned, otherwise the Ops list is mutated as
1311 /// necessary.
OptimizeXor(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)1312 Value *ReassociatePass::OptimizeXor(Instruction *I,
1313 SmallVectorImpl<ValueEntry> &Ops) {
1314 if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
1315 return V;
1316
1317 if (Ops.size() == 1)
1318 return nullptr;
1319
1320 SmallVector<XorOpnd, 8> Opnds;
1321 SmallVector<XorOpnd*, 8> OpndPtrs;
1322 Type *Ty = Ops[0].Op->getType();
1323 APInt ConstOpnd(Ty->getScalarSizeInBits(), 0);
1324
1325 // Step 1: Convert ValueEntry to XorOpnd
1326 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1327 Value *V = Ops[i].Op;
1328 const APInt *C;
1329 // TODO: Support non-splat vectors.
1330 if (match(V, m_APInt(C))) {
1331 ConstOpnd ^= *C;
1332 } else {
1333 XorOpnd O(V);
1334 O.setSymbolicRank(getRank(O.getSymbolicPart()));
1335 Opnds.push_back(O);
1336 }
1337 }
1338
1339 // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
1340 // It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
1341 // the "OpndPtrs" as well. For the similar reason, do not fuse this loop
1342 // with the previous loop --- the iterator of the "Opnds" may be invalidated
1343 // when new elements are added to the vector.
1344 for (unsigned i = 0, e = Opnds.size(); i != e; ++i)
1345 OpndPtrs.push_back(&Opnds[i]);
1346
1347 // Step 2: Sort the Xor-Operands in a way such that the operands containing
1348 // the same symbolic value cluster together. For instance, the input operand
1349 // sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
1350 // ("x | 123", "x & 789", "y & 456").
1351 //
1352 // The purpose is twofold:
1353 // 1) Cluster together the operands sharing the same symbolic-value.
1354 // 2) Operand having smaller symbolic-value-rank is permuted earlier, which
1355 // could potentially shorten crital path, and expose more loop-invariants.
1356 // Note that values' rank are basically defined in RPO order (FIXME).
1357 // So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
1358 // than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
1359 // "z" in the order of X-Y-Z is better than any other orders.
1360 llvm::stable_sort(OpndPtrs, [](XorOpnd *LHS, XorOpnd *RHS) {
1361 return LHS->getSymbolicRank() < RHS->getSymbolicRank();
1362 });
1363
1364 // Step 3: Combine adjacent operands
1365 XorOpnd *PrevOpnd = nullptr;
1366 bool Changed = false;
1367 for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
1368 XorOpnd *CurrOpnd = OpndPtrs[i];
1369 // The combined value
1370 Value *CV;
1371
1372 // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
1373 if (!ConstOpnd.isNullValue() &&
1374 CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1375 Changed = true;
1376 if (CV)
1377 *CurrOpnd = XorOpnd(CV);
1378 else {
1379 CurrOpnd->Invalidate();
1380 continue;
1381 }
1382 }
1383
1384 if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1385 PrevOpnd = CurrOpnd;
1386 continue;
1387 }
1388
1389 // step 3.2: When previous and current operands share the same symbolic
1390 // value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
1391 if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1392 // Remove previous operand
1393 PrevOpnd->Invalidate();
1394 if (CV) {
1395 *CurrOpnd = XorOpnd(CV);
1396 PrevOpnd = CurrOpnd;
1397 } else {
1398 CurrOpnd->Invalidate();
1399 PrevOpnd = nullptr;
1400 }
1401 Changed = true;
1402 }
1403 }
1404
1405 // Step 4: Reassemble the Ops
1406 if (Changed) {
1407 Ops.clear();
1408 for (unsigned int i = 0, e = Opnds.size(); i < e; i++) {
1409 XorOpnd &O = Opnds[i];
1410 if (O.isInvalid())
1411 continue;
1412 ValueEntry VE(getRank(O.getValue()), O.getValue());
1413 Ops.push_back(VE);
1414 }
1415 if (!ConstOpnd.isNullValue()) {
1416 Value *C = ConstantInt::get(Ty, ConstOpnd);
1417 ValueEntry VE(getRank(C), C);
1418 Ops.push_back(VE);
1419 }
1420 unsigned Sz = Ops.size();
1421 if (Sz == 1)
1422 return Ops.back().Op;
1423 if (Sz == 0) {
1424 assert(ConstOpnd.isNullValue());
1425 return ConstantInt::get(Ty, ConstOpnd);
1426 }
1427 }
1428
1429 return nullptr;
1430 }
1431
1432 /// Optimize a series of operands to an 'add' instruction. This
1433 /// optimizes based on identities. If it can be reduced to a single Value, it
1434 /// is returned, otherwise the Ops list is mutated as necessary.
OptimizeAdd(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)1435 Value *ReassociatePass::OptimizeAdd(Instruction *I,
1436 SmallVectorImpl<ValueEntry> &Ops) {
1437 // Scan the operand lists looking for X and -X pairs. If we find any, we
1438 // can simplify expressions like X+-X == 0 and X+~X ==-1. While we're at it,
1439 // scan for any
1440 // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
1441
1442 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1443 Value *TheOp = Ops[i].Op;
1444 // Check to see if we've seen this operand before. If so, we factor all
1445 // instances of the operand together. Due to our sorting criteria, we know
1446 // that these need to be next to each other in the vector.
1447 if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
1448 // Rescan the list, remove all instances of this operand from the expr.
1449 unsigned NumFound = 0;
1450 do {
1451 Ops.erase(Ops.begin()+i);
1452 ++NumFound;
1453 } while (i != Ops.size() && Ops[i].Op == TheOp);
1454
1455 LLVM_DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp
1456 << '\n');
1457 ++NumFactor;
1458
1459 // Insert a new multiply.
1460 Type *Ty = TheOp->getType();
1461 Constant *C = Ty->isIntOrIntVectorTy() ?
1462 ConstantInt::get(Ty, NumFound) : ConstantFP::get(Ty, NumFound);
1463 Instruction *Mul = CreateMul(TheOp, C, "factor", I, I);
1464
1465 // Now that we have inserted a multiply, optimize it. This allows us to
1466 // handle cases that require multiple factoring steps, such as this:
1467 // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
1468 RedoInsts.insert(Mul);
1469
1470 // If every add operand was a duplicate, return the multiply.
1471 if (Ops.empty())
1472 return Mul;
1473
1474 // Otherwise, we had some input that didn't have the dupe, such as
1475 // "A + A + B" -> "A*2 + B". Add the new multiply to the list of
1476 // things being added by this operation.
1477 Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
1478
1479 --i;
1480 e = Ops.size();
1481 continue;
1482 }
1483
1484 // Check for X and -X or X and ~X in the operand list.
1485 Value *X;
1486 if (!match(TheOp, m_Neg(m_Value(X))) && !match(TheOp, m_Not(m_Value(X))) &&
1487 !match(TheOp, m_FNeg(m_Value(X))))
1488 continue;
1489
1490 unsigned FoundX = FindInOperandList(Ops, i, X);
1491 if (FoundX == i)
1492 continue;
1493
1494 // Remove X and -X from the operand list.
1495 if (Ops.size() == 2 &&
1496 (match(TheOp, m_Neg(m_Value())) || match(TheOp, m_FNeg(m_Value()))))
1497 return Constant::getNullValue(X->getType());
1498
1499 // Remove X and ~X from the operand list.
1500 if (Ops.size() == 2 && match(TheOp, m_Not(m_Value())))
1501 return Constant::getAllOnesValue(X->getType());
1502
1503 Ops.erase(Ops.begin()+i);
1504 if (i < FoundX)
1505 --FoundX;
1506 else
1507 --i; // Need to back up an extra one.
1508 Ops.erase(Ops.begin()+FoundX);
1509 ++NumAnnihil;
1510 --i; // Revisit element.
1511 e -= 2; // Removed two elements.
1512
1513 // if X and ~X we append -1 to the operand list.
1514 if (match(TheOp, m_Not(m_Value()))) {
1515 Value *V = Constant::getAllOnesValue(X->getType());
1516 Ops.insert(Ops.end(), ValueEntry(getRank(V), V));
1517 e += 1;
1518 }
1519 }
1520
1521 // Scan the operand list, checking to see if there are any common factors
1522 // between operands. Consider something like A*A+A*B*C+D. We would like to
1523 // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
1524 // To efficiently find this, we count the number of times a factor occurs
1525 // for any ADD operands that are MULs.
1526 DenseMap<Value*, unsigned> FactorOccurrences;
1527
1528 // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
1529 // where they are actually the same multiply.
1530 unsigned MaxOcc = 0;
1531 Value *MaxOccVal = nullptr;
1532 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1533 BinaryOperator *BOp =
1534 isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
1535 if (!BOp)
1536 continue;
1537
1538 // Compute all of the factors of this added value.
1539 SmallVector<Value*, 8> Factors;
1540 FindSingleUseMultiplyFactors(BOp, Factors);
1541 assert(Factors.size() > 1 && "Bad linearize!");
1542
1543 // Add one to FactorOccurrences for each unique factor in this op.
1544 SmallPtrSet<Value*, 8> Duplicates;
1545 for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
1546 Value *Factor = Factors[i];
1547 if (!Duplicates.insert(Factor).second)
1548 continue;
1549
1550 unsigned Occ = ++FactorOccurrences[Factor];
1551 if (Occ > MaxOcc) {
1552 MaxOcc = Occ;
1553 MaxOccVal = Factor;
1554 }
1555
1556 // If Factor is a negative constant, add the negated value as a factor
1557 // because we can percolate the negate out. Watch for minint, which
1558 // cannot be positivified.
1559 if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1560 if (CI->isNegative() && !CI->isMinValue(true)) {
1561 Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
1562 if (!Duplicates.insert(Factor).second)
1563 continue;
1564 unsigned Occ = ++FactorOccurrences[Factor];
1565 if (Occ > MaxOcc) {
1566 MaxOcc = Occ;
1567 MaxOccVal = Factor;
1568 }
1569 }
1570 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1571 if (CF->isNegative()) {
1572 APFloat F(CF->getValueAPF());
1573 F.changeSign();
1574 Factor = ConstantFP::get(CF->getContext(), F);
1575 if (!Duplicates.insert(Factor).second)
1576 continue;
1577 unsigned Occ = ++FactorOccurrences[Factor];
1578 if (Occ > MaxOcc) {
1579 MaxOcc = Occ;
1580 MaxOccVal = Factor;
1581 }
1582 }
1583 }
1584 }
1585 }
1586
1587 // If any factor occurred more than one time, we can pull it out.
1588 if (MaxOcc > 1) {
1589 LLVM_DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal
1590 << '\n');
1591 ++NumFactor;
1592
1593 // Create a new instruction that uses the MaxOccVal twice. If we don't do
1594 // this, we could otherwise run into situations where removing a factor
1595 // from an expression will drop a use of maxocc, and this can cause
1596 // RemoveFactorFromExpression on successive values to behave differently.
1597 Instruction *DummyInst =
1598 I->getType()->isIntOrIntVectorTy()
1599 ? BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal)
1600 : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
1601
1602 SmallVector<WeakTrackingVH, 4> NewMulOps;
1603 for (unsigned i = 0; i != Ops.size(); ++i) {
1604 // Only try to remove factors from expressions we're allowed to.
1605 BinaryOperator *BOp =
1606 isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
1607 if (!BOp)
1608 continue;
1609
1610 if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1611 // The factorized operand may occur several times. Convert them all in
1612 // one fell swoop.
1613 for (unsigned j = Ops.size(); j != i;) {
1614 --j;
1615 if (Ops[j].Op == Ops[i].Op) {
1616 NewMulOps.push_back(V);
1617 Ops.erase(Ops.begin()+j);
1618 }
1619 }
1620 --i;
1621 }
1622 }
1623
1624 // No need for extra uses anymore.
1625 DummyInst->deleteValue();
1626
1627 unsigned NumAddedValues = NewMulOps.size();
1628 Value *V = EmitAddTreeOfValues(I, NewMulOps);
1629
1630 // Now that we have inserted the add tree, optimize it. This allows us to
1631 // handle cases that require multiple factoring steps, such as this:
1632 // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
1633 assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
1634 (void)NumAddedValues;
1635 if (Instruction *VI = dyn_cast<Instruction>(V))
1636 RedoInsts.insert(VI);
1637
1638 // Create the multiply.
1639 Instruction *V2 = CreateMul(V, MaxOccVal, "reass.mul", I, I);
1640
1641 // Rerun associate on the multiply in case the inner expression turned into
1642 // a multiply. We want to make sure that we keep things in canonical form.
1643 RedoInsts.insert(V2);
1644
1645 // If every add operand included the factor (e.g. "A*B + A*C"), then the
1646 // entire result expression is just the multiply "A*(B+C)".
1647 if (Ops.empty())
1648 return V2;
1649
1650 // Otherwise, we had some input that didn't have the factor, such as
1651 // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
1652 // things being added by this operation.
1653 Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
1654 }
1655
1656 return nullptr;
1657 }
1658
1659 /// Build up a vector of value/power pairs factoring a product.
1660 ///
1661 /// Given a series of multiplication operands, build a vector of factors and
1662 /// the powers each is raised to when forming the final product. Sort them in
1663 /// the order of descending power.
1664 ///
1665 /// (x*x) -> [(x, 2)]
1666 /// ((x*x)*x) -> [(x, 3)]
1667 /// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
1668 ///
1669 /// \returns Whether any factors have a power greater than one.
collectMultiplyFactors(SmallVectorImpl<ValueEntry> & Ops,SmallVectorImpl<Factor> & Factors)1670 static bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
1671 SmallVectorImpl<Factor> &Factors) {
1672 // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
1673 // Compute the sum of powers of simplifiable factors.
1674 unsigned FactorPowerSum = 0;
1675 for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
1676 Value *Op = Ops[Idx-1].Op;
1677
1678 // Count the number of occurrences of this value.
1679 unsigned Count = 1;
1680 for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
1681 ++Count;
1682 // Track for simplification all factors which occur 2 or more times.
1683 if (Count > 1)
1684 FactorPowerSum += Count;
1685 }
1686
1687 // We can only simplify factors if the sum of the powers of our simplifiable
1688 // factors is 4 or higher. When that is the case, we will *always* have
1689 // a simplification. This is an important invariant to prevent cyclicly
1690 // trying to simplify already minimal formations.
1691 if (FactorPowerSum < 4)
1692 return false;
1693
1694 // Now gather the simplifiable factors, removing them from Ops.
1695 FactorPowerSum = 0;
1696 for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
1697 Value *Op = Ops[Idx-1].Op;
1698
1699 // Count the number of occurrences of this value.
1700 unsigned Count = 1;
1701 for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
1702 ++Count;
1703 if (Count == 1)
1704 continue;
1705 // Move an even number of occurrences to Factors.
1706 Count &= ~1U;
1707 Idx -= Count;
1708 FactorPowerSum += Count;
1709 Factors.push_back(Factor(Op, Count));
1710 Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
1711 }
1712
1713 // None of the adjustments above should have reduced the sum of factor powers
1714 // below our mininum of '4'.
1715 assert(FactorPowerSum >= 4);
1716
1717 llvm::stable_sort(Factors, [](const Factor &LHS, const Factor &RHS) {
1718 return LHS.Power > RHS.Power;
1719 });
1720 return true;
1721 }
1722
1723 /// Build a tree of multiplies, computing the product of Ops.
buildMultiplyTree(IRBuilder<> & Builder,SmallVectorImpl<Value * > & Ops)1724 static Value *buildMultiplyTree(IRBuilder<> &Builder,
1725 SmallVectorImpl<Value*> &Ops) {
1726 if (Ops.size() == 1)
1727 return Ops.back();
1728
1729 Value *LHS = Ops.pop_back_val();
1730 do {
1731 if (LHS->getType()->isIntOrIntVectorTy())
1732 LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
1733 else
1734 LHS = Builder.CreateFMul(LHS, Ops.pop_back_val());
1735 } while (!Ops.empty());
1736
1737 return LHS;
1738 }
1739
1740 /// Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
1741 ///
1742 /// Given a vector of values raised to various powers, where no two values are
1743 /// equal and the powers are sorted in decreasing order, compute the minimal
1744 /// DAG of multiplies to compute the final product, and return that product
1745 /// value.
1746 Value *
buildMinimalMultiplyDAG(IRBuilder<> & Builder,SmallVectorImpl<Factor> & Factors)1747 ReassociatePass::buildMinimalMultiplyDAG(IRBuilder<> &Builder,
1748 SmallVectorImpl<Factor> &Factors) {
1749 assert(Factors[0].Power);
1750 SmallVector<Value *, 4> OuterProduct;
1751 for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
1752 Idx < Size && Factors[Idx].Power > 0; ++Idx) {
1753 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1754 LastIdx = Idx;
1755 continue;
1756 }
1757
1758 // We want to multiply across all the factors with the same power so that
1759 // we can raise them to that power as a single entity. Build a mini tree
1760 // for that.
1761 SmallVector<Value *, 4> InnerProduct;
1762 InnerProduct.push_back(Factors[LastIdx].Base);
1763 do {
1764 InnerProduct.push_back(Factors[Idx].Base);
1765 ++Idx;
1766 } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
1767
1768 // Reset the base value of the first factor to the new expression tree.
1769 // We'll remove all the factors with the same power in a second pass.
1770 Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
1771 if (Instruction *MI = dyn_cast<Instruction>(M))
1772 RedoInsts.insert(MI);
1773
1774 LastIdx = Idx;
1775 }
1776 // Unique factors with equal powers -- we've folded them into the first one's
1777 // base.
1778 Factors.erase(std::unique(Factors.begin(), Factors.end(),
1779 [](const Factor &LHS, const Factor &RHS) {
1780 return LHS.Power == RHS.Power;
1781 }),
1782 Factors.end());
1783
1784 // Iteratively collect the base of each factor with an add power into the
1785 // outer product, and halve each power in preparation for squaring the
1786 // expression.
1787 for (unsigned Idx = 0, Size = Factors.size(); Idx != Size; ++Idx) {
1788 if (Factors[Idx].Power & 1)
1789 OuterProduct.push_back(Factors[Idx].Base);
1790 Factors[Idx].Power >>= 1;
1791 }
1792 if (Factors[0].Power) {
1793 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1794 OuterProduct.push_back(SquareRoot);
1795 OuterProduct.push_back(SquareRoot);
1796 }
1797 if (OuterProduct.size() == 1)
1798 return OuterProduct.front();
1799
1800 Value *V = buildMultiplyTree(Builder, OuterProduct);
1801 return V;
1802 }
1803
OptimizeMul(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)1804 Value *ReassociatePass::OptimizeMul(BinaryOperator *I,
1805 SmallVectorImpl<ValueEntry> &Ops) {
1806 // We can only optimize the multiplies when there is a chain of more than
1807 // three, such that a balanced tree might require fewer total multiplies.
1808 if (Ops.size() < 4)
1809 return nullptr;
1810
1811 // Try to turn linear trees of multiplies without other uses of the
1812 // intermediate stages into minimal multiply DAGs with perfect sub-expression
1813 // re-use.
1814 SmallVector<Factor, 4> Factors;
1815 if (!collectMultiplyFactors(Ops, Factors))
1816 return nullptr; // All distinct factors, so nothing left for us to do.
1817
1818 IRBuilder<> Builder(I);
1819 // The reassociate transformation for FP operations is performed only
1820 // if unsafe algebra is permitted by FastMathFlags. Propagate those flags
1821 // to the newly generated operations.
1822 if (auto FPI = dyn_cast<FPMathOperator>(I))
1823 Builder.setFastMathFlags(FPI->getFastMathFlags());
1824
1825 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1826 if (Ops.empty())
1827 return V;
1828
1829 ValueEntry NewEntry = ValueEntry(getRank(V), V);
1830 Ops.insert(llvm::lower_bound(Ops, NewEntry), NewEntry);
1831 return nullptr;
1832 }
1833
OptimizeExpression(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)1834 Value *ReassociatePass::OptimizeExpression(BinaryOperator *I,
1835 SmallVectorImpl<ValueEntry> &Ops) {
1836 // Now that we have the linearized expression tree, try to optimize it.
1837 // Start by folding any constants that we found.
1838 Constant *Cst = nullptr;
1839 unsigned Opcode = I->getOpcode();
1840 while (!Ops.empty() && isa<Constant>(Ops.back().Op)) {
1841 Constant *C = cast<Constant>(Ops.pop_back_val().Op);
1842 Cst = Cst ? ConstantExpr::get(Opcode, C, Cst) : C;
1843 }
1844 // If there was nothing but constants then we are done.
1845 if (Ops.empty())
1846 return Cst;
1847
1848 // Put the combined constant back at the end of the operand list, except if
1849 // there is no point. For example, an add of 0 gets dropped here, while a
1850 // multiplication by zero turns the whole expression into zero.
1851 if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
1852 if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
1853 return Cst;
1854 Ops.push_back(ValueEntry(0, Cst));
1855 }
1856
1857 if (Ops.size() == 1) return Ops[0].Op;
1858
1859 // Handle destructive annihilation due to identities between elements in the
1860 // argument list here.
1861 unsigned NumOps = Ops.size();
1862 switch (Opcode) {
1863 default: break;
1864 case Instruction::And:
1865 case Instruction::Or:
1866 if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
1867 return Result;
1868 break;
1869
1870 case Instruction::Xor:
1871 if (Value *Result = OptimizeXor(I, Ops))
1872 return Result;
1873 break;
1874
1875 case Instruction::Add:
1876 case Instruction::FAdd:
1877 if (Value *Result = OptimizeAdd(I, Ops))
1878 return Result;
1879 break;
1880
1881 case Instruction::Mul:
1882 case Instruction::FMul:
1883 if (Value *Result = OptimizeMul(I, Ops))
1884 return Result;
1885 break;
1886 }
1887
1888 if (Ops.size() != NumOps)
1889 return OptimizeExpression(I, Ops);
1890 return nullptr;
1891 }
1892
1893 // Remove dead instructions and if any operands are trivially dead add them to
1894 // Insts so they will be removed as well.
RecursivelyEraseDeadInsts(Instruction * I,OrderedSet & Insts)1895 void ReassociatePass::RecursivelyEraseDeadInsts(Instruction *I,
1896 OrderedSet &Insts) {
1897 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1898 SmallVector<Value *, 4> Ops(I->op_begin(), I->op_end());
1899 ValueRankMap.erase(I);
1900 Insts.remove(I);
1901 RedoInsts.remove(I);
1902 llvm::salvageDebugInfoOrMarkUndef(*I);
1903 I->eraseFromParent();
1904 for (auto Op : Ops)
1905 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1906 if (OpInst->use_empty())
1907 Insts.insert(OpInst);
1908 }
1909
1910 /// Zap the given instruction, adding interesting operands to the work list.
EraseInst(Instruction * I)1911 void ReassociatePass::EraseInst(Instruction *I) {
1912 assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1913 LLVM_DEBUG(dbgs() << "Erasing dead inst: "; I->dump());
1914
1915 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1916 // Erase the dead instruction.
1917 ValueRankMap.erase(I);
1918 RedoInsts.remove(I);
1919 llvm::salvageDebugInfoOrMarkUndef(*I);
1920 I->eraseFromParent();
1921 // Optimize its operands.
1922 SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
1923 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1924 if (Instruction *Op = dyn_cast<Instruction>(Ops[i])) {
1925 // If this is a node in an expression tree, climb to the expression root
1926 // and add that since that's where optimization actually happens.
1927 unsigned Opcode = Op->getOpcode();
1928 while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
1929 Visited.insert(Op).second)
1930 Op = Op->user_back();
1931
1932 // The instruction we're going to push may be coming from a
1933 // dead block, and Reassociate skips the processing of unreachable
1934 // blocks because it's a waste of time and also because it can
1935 // lead to infinite loop due to LLVM's non-standard definition
1936 // of dominance.
1937 if (ValueRankMap.find(Op) != ValueRankMap.end())
1938 RedoInsts.insert(Op);
1939 }
1940
1941 MadeChange = true;
1942 }
1943
1944 /// Recursively analyze an expression to build a list of instructions that have
1945 /// negative floating-point constant operands. The caller can then transform
1946 /// the list to create positive constants for better reassociation and CSE.
getNegatibleInsts(Value * V,SmallVectorImpl<Instruction * > & Candidates)1947 static void getNegatibleInsts(Value *V,
1948 SmallVectorImpl<Instruction *> &Candidates) {
1949 // Handle only one-use instructions. Combining negations does not justify
1950 // replicating instructions.
1951 Instruction *I;
1952 if (!match(V, m_OneUse(m_Instruction(I))))
1953 return;
1954
1955 // Handle expressions of multiplications and divisions.
1956 // TODO: This could look through floating-point casts.
1957 const APFloat *C;
1958 switch (I->getOpcode()) {
1959 case Instruction::FMul:
1960 // Not expecting non-canonical code here. Bail out and wait.
1961 if (match(I->getOperand(0), m_Constant()))
1962 break;
1963
1964 if (match(I->getOperand(1), m_APFloat(C)) && C->isNegative()) {
1965 Candidates.push_back(I);
1966 LLVM_DEBUG(dbgs() << "FMul with negative constant: " << *I << '\n');
1967 }
1968 getNegatibleInsts(I->getOperand(0), Candidates);
1969 getNegatibleInsts(I->getOperand(1), Candidates);
1970 break;
1971 case Instruction::FDiv:
1972 // Not expecting non-canonical code here. Bail out and wait.
1973 if (match(I->getOperand(0), m_Constant()) &&
1974 match(I->getOperand(1), m_Constant()))
1975 break;
1976
1977 if ((match(I->getOperand(0), m_APFloat(C)) && C->isNegative()) ||
1978 (match(I->getOperand(1), m_APFloat(C)) && C->isNegative())) {
1979 Candidates.push_back(I);
1980 LLVM_DEBUG(dbgs() << "FDiv with negative constant: " << *I << '\n');
1981 }
1982 getNegatibleInsts(I->getOperand(0), Candidates);
1983 getNegatibleInsts(I->getOperand(1), Candidates);
1984 break;
1985 default:
1986 break;
1987 }
1988 }
1989
1990 /// Given an fadd/fsub with an operand that is a one-use instruction
1991 /// (the fadd/fsub), try to change negative floating-point constants into
1992 /// positive constants to increase potential for reassociation and CSE.
canonicalizeNegFPConstantsForOp(Instruction * I,Instruction * Op,Value * OtherOp)1993 Instruction *ReassociatePass::canonicalizeNegFPConstantsForOp(Instruction *I,
1994 Instruction *Op,
1995 Value *OtherOp) {
1996 assert((I->getOpcode() == Instruction::FAdd ||
1997 I->getOpcode() == Instruction::FSub) && "Expected fadd/fsub");
1998
1999 // Collect instructions with negative FP constants from the subtree that ends
2000 // in Op.
2001 SmallVector<Instruction *, 4> Candidates;
2002 getNegatibleInsts(Op, Candidates);
2003 if (Candidates.empty())
2004 return nullptr;
2005
2006 // Don't canonicalize x + (-Constant * y) -> x - (Constant * y), if the
2007 // resulting subtract will be broken up later. This can get us into an
2008 // infinite loop during reassociation.
2009 bool IsFSub = I->getOpcode() == Instruction::FSub;
2010 bool NeedsSubtract = !IsFSub && Candidates.size() % 2 == 1;
2011 if (NeedsSubtract && ShouldBreakUpSubtract(I))
2012 return nullptr;
2013
2014 for (Instruction *Negatible : Candidates) {
2015 const APFloat *C;
2016 if (match(Negatible->getOperand(0), m_APFloat(C))) {
2017 assert(!match(Negatible->getOperand(1), m_Constant()) &&
2018 "Expecting only 1 constant operand");
2019 assert(C->isNegative() && "Expected negative FP constant");
2020 Negatible->setOperand(0, ConstantFP::get(Negatible->getType(), abs(*C)));
2021 MadeChange = true;
2022 }
2023 if (match(Negatible->getOperand(1), m_APFloat(C))) {
2024 assert(!match(Negatible->getOperand(0), m_Constant()) &&
2025 "Expecting only 1 constant operand");
2026 assert(C->isNegative() && "Expected negative FP constant");
2027 Negatible->setOperand(1, ConstantFP::get(Negatible->getType(), abs(*C)));
2028 MadeChange = true;
2029 }
2030 }
2031 assert(MadeChange == true && "Negative constant candidate was not changed");
2032
2033 // Negations cancelled out.
2034 if (Candidates.size() % 2 == 0)
2035 return I;
2036
2037 // Negate the final operand in the expression by flipping the opcode of this
2038 // fadd/fsub.
2039 assert(Candidates.size() % 2 == 1 && "Expected odd number");
2040 IRBuilder<> Builder(I);
2041 Value *NewInst = IsFSub ? Builder.CreateFAddFMF(OtherOp, Op, I)
2042 : Builder.CreateFSubFMF(OtherOp, Op, I);
2043 I->replaceAllUsesWith(NewInst);
2044 RedoInsts.insert(I);
2045 return dyn_cast<Instruction>(NewInst);
2046 }
2047
2048 /// Canonicalize expressions that contain a negative floating-point constant
2049 /// of the following form:
2050 /// OtherOp + (subtree) -> OtherOp {+/-} (canonical subtree)
2051 /// (subtree) + OtherOp -> OtherOp {+/-} (canonical subtree)
2052 /// OtherOp - (subtree) -> OtherOp {+/-} (canonical subtree)
2053 ///
2054 /// The fadd/fsub opcode may be switched to allow folding a negation into the
2055 /// input instruction.
canonicalizeNegFPConstants(Instruction * I)2056 Instruction *ReassociatePass::canonicalizeNegFPConstants(Instruction *I) {
2057 LLVM_DEBUG(dbgs() << "Combine negations for: " << *I << '\n');
2058 Value *X;
2059 Instruction *Op;
2060 if (match(I, m_FAdd(m_Value(X), m_OneUse(m_Instruction(Op)))))
2061 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2062 I = R;
2063 if (match(I, m_FAdd(m_OneUse(m_Instruction(Op)), m_Value(X))))
2064 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2065 I = R;
2066 if (match(I, m_FSub(m_Value(X), m_OneUse(m_Instruction(Op)))))
2067 if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2068 I = R;
2069 return I;
2070 }
2071
2072 /// Inspect and optimize the given instruction. Note that erasing
2073 /// instructions is not allowed.
OptimizeInst(Instruction * I)2074 void ReassociatePass::OptimizeInst(Instruction *I) {
2075 // Only consider operations that we understand.
2076 if (!isa<UnaryOperator>(I) && !isa<BinaryOperator>(I))
2077 return;
2078
2079 if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(I->getOperand(1)))
2080 // If an operand of this shift is a reassociable multiply, or if the shift
2081 // is used by a reassociable multiply or add, turn into a multiply.
2082 if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
2083 (I->hasOneUse() &&
2084 (isReassociableOp(I->user_back(), Instruction::Mul) ||
2085 isReassociableOp(I->user_back(), Instruction::Add)))) {
2086 Instruction *NI = ConvertShiftToMul(I);
2087 RedoInsts.insert(I);
2088 MadeChange = true;
2089 I = NI;
2090 }
2091
2092 // Commute binary operators, to canonicalize the order of their operands.
2093 // This can potentially expose more CSE opportunities, and makes writing other
2094 // transformations simpler.
2095 if (I->isCommutative())
2096 canonicalizeOperands(I);
2097
2098 // Canonicalize negative constants out of expressions.
2099 if (Instruction *Res = canonicalizeNegFPConstants(I))
2100 I = Res;
2101
2102 // Don't optimize floating-point instructions unless they are 'fast'.
2103 if (I->getType()->isFPOrFPVectorTy() && !I->isFast())
2104 return;
2105
2106 // Do not reassociate boolean (i1) expressions. We want to preserve the
2107 // original order of evaluation for short-circuited comparisons that
2108 // SimplifyCFG has folded to AND/OR expressions. If the expression
2109 // is not further optimized, it is likely to be transformed back to a
2110 // short-circuited form for code gen, and the source order may have been
2111 // optimized for the most likely conditions.
2112 if (I->getType()->isIntegerTy(1))
2113 return;
2114
2115 // If this is a subtract instruction which is not already in negate form,
2116 // see if we can convert it to X+-Y.
2117 if (I->getOpcode() == Instruction::Sub) {
2118 if (ShouldBreakUpSubtract(I)) {
2119 Instruction *NI = BreakUpSubtract(I, RedoInsts);
2120 RedoInsts.insert(I);
2121 MadeChange = true;
2122 I = NI;
2123 } else if (match(I, m_Neg(m_Value()))) {
2124 // Otherwise, this is a negation. See if the operand is a multiply tree
2125 // and if this is not an inner node of a multiply tree.
2126 if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
2127 (!I->hasOneUse() ||
2128 !isReassociableOp(I->user_back(), Instruction::Mul))) {
2129 Instruction *NI = LowerNegateToMultiply(I);
2130 // If the negate was simplified, revisit the users to see if we can
2131 // reassociate further.
2132 for (User *U : NI->users()) {
2133 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
2134 RedoInsts.insert(Tmp);
2135 }
2136 RedoInsts.insert(I);
2137 MadeChange = true;
2138 I = NI;
2139 }
2140 }
2141 } else if (I->getOpcode() == Instruction::FNeg ||
2142 I->getOpcode() == Instruction::FSub) {
2143 if (ShouldBreakUpSubtract(I)) {
2144 Instruction *NI = BreakUpSubtract(I, RedoInsts);
2145 RedoInsts.insert(I);
2146 MadeChange = true;
2147 I = NI;
2148 } else if (match(I, m_FNeg(m_Value()))) {
2149 // Otherwise, this is a negation. See if the operand is a multiply tree
2150 // and if this is not an inner node of a multiply tree.
2151 Value *Op = isa<BinaryOperator>(I) ? I->getOperand(1) :
2152 I->getOperand(0);
2153 if (isReassociableOp(Op, Instruction::FMul) &&
2154 (!I->hasOneUse() ||
2155 !isReassociableOp(I->user_back(), Instruction::FMul))) {
2156 // If the negate was simplified, revisit the users to see if we can
2157 // reassociate further.
2158 Instruction *NI = LowerNegateToMultiply(I);
2159 for (User *U : NI->users()) {
2160 if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
2161 RedoInsts.insert(Tmp);
2162 }
2163 RedoInsts.insert(I);
2164 MadeChange = true;
2165 I = NI;
2166 }
2167 }
2168 }
2169
2170 // If this instruction is an associative binary operator, process it.
2171 if (!I->isAssociative()) return;
2172 BinaryOperator *BO = cast<BinaryOperator>(I);
2173
2174 // If this is an interior node of a reassociable tree, ignore it until we
2175 // get to the root of the tree, to avoid N^2 analysis.
2176 unsigned Opcode = BO->getOpcode();
2177 if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode) {
2178 // During the initial run we will get to the root of the tree.
2179 // But if we get here while we are redoing instructions, there is no
2180 // guarantee that the root will be visited. So Redo later
2181 if (BO->user_back() != BO &&
2182 BO->getParent() == BO->user_back()->getParent())
2183 RedoInsts.insert(BO->user_back());
2184 return;
2185 }
2186
2187 // If this is an add tree that is used by a sub instruction, ignore it
2188 // until we process the subtract.
2189 if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
2190 cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub)
2191 return;
2192 if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd &&
2193 cast<Instruction>(BO->user_back())->getOpcode() == Instruction::FSub)
2194 return;
2195
2196 ReassociateExpression(BO);
2197 }
2198
ReassociateExpression(BinaryOperator * I)2199 void ReassociatePass::ReassociateExpression(BinaryOperator *I) {
2200 // First, walk the expression tree, linearizing the tree, collecting the
2201 // operand information.
2202 SmallVector<RepeatedValue, 8> Tree;
2203 MadeChange |= LinearizeExprTree(I, Tree);
2204 SmallVector<ValueEntry, 8> Ops;
2205 Ops.reserve(Tree.size());
2206 for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
2207 RepeatedValue E = Tree[i];
2208 Ops.append(E.second.getZExtValue(),
2209 ValueEntry(getRank(E.first), E.first));
2210 }
2211
2212 LLVM_DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
2213
2214 // Now that we have linearized the tree to a list and have gathered all of
2215 // the operands and their ranks, sort the operands by their rank. Use a
2216 // stable_sort so that values with equal ranks will have their relative
2217 // positions maintained (and so the compiler is deterministic). Note that
2218 // this sorts so that the highest ranking values end up at the beginning of
2219 // the vector.
2220 llvm::stable_sort(Ops);
2221
2222 // Now that we have the expression tree in a convenient
2223 // sorted form, optimize it globally if possible.
2224 if (Value *V = OptimizeExpression(I, Ops)) {
2225 if (V == I)
2226 // Self-referential expression in unreachable code.
2227 return;
2228 // This expression tree simplified to something that isn't a tree,
2229 // eliminate it.
2230 LLVM_DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
2231 I->replaceAllUsesWith(V);
2232 if (Instruction *VI = dyn_cast<Instruction>(V))
2233 if (I->getDebugLoc())
2234 VI->setDebugLoc(I->getDebugLoc());
2235 RedoInsts.insert(I);
2236 ++NumAnnihil;
2237 return;
2238 }
2239
2240 // We want to sink immediates as deeply as possible except in the case where
2241 // this is a multiply tree used only by an add, and the immediate is a -1.
2242 // In this case we reassociate to put the negation on the outside so that we
2243 // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
2244 if (I->hasOneUse()) {
2245 if (I->getOpcode() == Instruction::Mul &&
2246 cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add &&
2247 isa<ConstantInt>(Ops.back().Op) &&
2248 cast<ConstantInt>(Ops.back().Op)->isMinusOne()) {
2249 ValueEntry Tmp = Ops.pop_back_val();
2250 Ops.insert(Ops.begin(), Tmp);
2251 } else if (I->getOpcode() == Instruction::FMul &&
2252 cast<Instruction>(I->user_back())->getOpcode() ==
2253 Instruction::FAdd &&
2254 isa<ConstantFP>(Ops.back().Op) &&
2255 cast<ConstantFP>(Ops.back().Op)->isExactlyValue(-1.0)) {
2256 ValueEntry Tmp = Ops.pop_back_val();
2257 Ops.insert(Ops.begin(), Tmp);
2258 }
2259 }
2260
2261 LLVM_DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
2262
2263 if (Ops.size() == 1) {
2264 if (Ops[0].Op == I)
2265 // Self-referential expression in unreachable code.
2266 return;
2267
2268 // This expression tree simplified to something that isn't a tree,
2269 // eliminate it.
2270 I->replaceAllUsesWith(Ops[0].Op);
2271 if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2272 OI->setDebugLoc(I->getDebugLoc());
2273 RedoInsts.insert(I);
2274 return;
2275 }
2276
2277 if (Ops.size() > 2 && Ops.size() <= GlobalReassociateLimit) {
2278 // Find the pair with the highest count in the pairmap and move it to the
2279 // back of the list so that it can later be CSE'd.
2280 // example:
2281 // a*b*c*d*e
2282 // if c*e is the most "popular" pair, we can express this as
2283 // (((c*e)*d)*b)*a
2284 unsigned Max = 1;
2285 unsigned BestRank = 0;
2286 std::pair<unsigned, unsigned> BestPair;
2287 unsigned Idx = I->getOpcode() - Instruction::BinaryOpsBegin;
2288 for (unsigned i = 0; i < Ops.size() - 1; ++i)
2289 for (unsigned j = i + 1; j < Ops.size(); ++j) {
2290 unsigned Score = 0;
2291 Value *Op0 = Ops[i].Op;
2292 Value *Op1 = Ops[j].Op;
2293 if (std::less<Value *>()(Op1, Op0))
2294 std::swap(Op0, Op1);
2295 auto it = PairMap[Idx].find({Op0, Op1});
2296 if (it != PairMap[Idx].end()) {
2297 // Functions like BreakUpSubtract() can erase the Values we're using
2298 // as keys and create new Values after we built the PairMap. There's a
2299 // small chance that the new nodes can have the same address as
2300 // something already in the table. We shouldn't accumulate the stored
2301 // score in that case as it refers to the wrong Value.
2302 if (it->second.isValid())
2303 Score += it->second.Score;
2304 }
2305
2306 unsigned MaxRank = std::max(Ops[i].Rank, Ops[j].Rank);
2307 if (Score > Max || (Score == Max && MaxRank < BestRank)) {
2308 BestPair = {i, j};
2309 Max = Score;
2310 BestRank = MaxRank;
2311 }
2312 }
2313 if (Max > 1) {
2314 auto Op0 = Ops[BestPair.first];
2315 auto Op1 = Ops[BestPair.second];
2316 Ops.erase(&Ops[BestPair.second]);
2317 Ops.erase(&Ops[BestPair.first]);
2318 Ops.push_back(Op0);
2319 Ops.push_back(Op1);
2320 }
2321 }
2322 // Now that we ordered and optimized the expressions, splat them back into
2323 // the expression tree, removing any unneeded nodes.
2324 RewriteExprTree(I, Ops);
2325 }
2326
2327 void
BuildPairMap(ReversePostOrderTraversal<Function * > & RPOT)2328 ReassociatePass::BuildPairMap(ReversePostOrderTraversal<Function *> &RPOT) {
2329 // Make a "pairmap" of how often each operand pair occurs.
2330 for (BasicBlock *BI : RPOT) {
2331 for (Instruction &I : *BI) {
2332 if (!I.isAssociative())
2333 continue;
2334
2335 // Ignore nodes that aren't at the root of trees.
2336 if (I.hasOneUse() && I.user_back()->getOpcode() == I.getOpcode())
2337 continue;
2338
2339 // Collect all operands in a single reassociable expression.
2340 // Since Reassociate has already been run once, we can assume things
2341 // are already canonical according to Reassociation's regime.
2342 SmallVector<Value *, 8> Worklist = { I.getOperand(0), I.getOperand(1) };
2343 SmallVector<Value *, 8> Ops;
2344 while (!Worklist.empty() && Ops.size() <= GlobalReassociateLimit) {
2345 Value *Op = Worklist.pop_back_val();
2346 Instruction *OpI = dyn_cast<Instruction>(Op);
2347 if (!OpI || OpI->getOpcode() != I.getOpcode() || !OpI->hasOneUse()) {
2348 Ops.push_back(Op);
2349 continue;
2350 }
2351 // Be paranoid about self-referencing expressions in unreachable code.
2352 if (OpI->getOperand(0) != OpI)
2353 Worklist.push_back(OpI->getOperand(0));
2354 if (OpI->getOperand(1) != OpI)
2355 Worklist.push_back(OpI->getOperand(1));
2356 }
2357 // Skip extremely long expressions.
2358 if (Ops.size() > GlobalReassociateLimit)
2359 continue;
2360
2361 // Add all pairwise combinations of operands to the pair map.
2362 unsigned BinaryIdx = I.getOpcode() - Instruction::BinaryOpsBegin;
2363 SmallSet<std::pair<Value *, Value*>, 32> Visited;
2364 for (unsigned i = 0; i < Ops.size() - 1; ++i) {
2365 for (unsigned j = i + 1; j < Ops.size(); ++j) {
2366 // Canonicalize operand orderings.
2367 Value *Op0 = Ops[i];
2368 Value *Op1 = Ops[j];
2369 if (std::less<Value *>()(Op1, Op0))
2370 std::swap(Op0, Op1);
2371 if (!Visited.insert({Op0, Op1}).second)
2372 continue;
2373 auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, {Op0, Op1, 1}});
2374 if (!res.second) {
2375 // If either key value has been erased then we've got the same
2376 // address by coincidence. That can't happen here because nothing is
2377 // erasing values but it can happen by the time we're querying the
2378 // map.
2379 assert(res.first->second.isValid() && "WeakVH invalidated");
2380 ++res.first->second.Score;
2381 }
2382 }
2383 }
2384 }
2385 }
2386 }
2387
run(Function & F,FunctionAnalysisManager &)2388 PreservedAnalyses ReassociatePass::run(Function &F, FunctionAnalysisManager &) {
2389 // Get the functions basic blocks in Reverse Post Order. This order is used by
2390 // BuildRankMap to pre calculate ranks correctly. It also excludes dead basic
2391 // blocks (it has been seen that the analysis in this pass could hang when
2392 // analysing dead basic blocks).
2393 ReversePostOrderTraversal<Function *> RPOT(&F);
2394
2395 // Calculate the rank map for F.
2396 BuildRankMap(F, RPOT);
2397
2398 // Build the pair map before running reassociate.
2399 // Technically this would be more accurate if we did it after one round
2400 // of reassociation, but in practice it doesn't seem to help much on
2401 // real-world code, so don't waste the compile time running reassociate
2402 // twice.
2403 // If a user wants, they could expicitly run reassociate twice in their
2404 // pass pipeline for further potential gains.
2405 // It might also be possible to update the pair map during runtime, but the
2406 // overhead of that may be large if there's many reassociable chains.
2407 BuildPairMap(RPOT);
2408
2409 MadeChange = false;
2410
2411 // Traverse the same blocks that were analysed by BuildRankMap.
2412 for (BasicBlock *BI : RPOT) {
2413 assert(RankMap.count(&*BI) && "BB should be ranked.");
2414 // Optimize every instruction in the basic block.
2415 for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;)
2416 if (isInstructionTriviallyDead(&*II)) {
2417 EraseInst(&*II++);
2418 } else {
2419 OptimizeInst(&*II);
2420 assert(II->getParent() == &*BI && "Moved to a different block!");
2421 ++II;
2422 }
2423
2424 // Make a copy of all the instructions to be redone so we can remove dead
2425 // instructions.
2426 OrderedSet ToRedo(RedoInsts);
2427 // Iterate over all instructions to be reevaluated and remove trivially dead
2428 // instructions. If any operand of the trivially dead instruction becomes
2429 // dead mark it for deletion as well. Continue this process until all
2430 // trivially dead instructions have been removed.
2431 while (!ToRedo.empty()) {
2432 Instruction *I = ToRedo.pop_back_val();
2433 if (isInstructionTriviallyDead(I)) {
2434 RecursivelyEraseDeadInsts(I, ToRedo);
2435 MadeChange = true;
2436 }
2437 }
2438
2439 // Now that we have removed dead instructions, we can reoptimize the
2440 // remaining instructions.
2441 while (!RedoInsts.empty()) {
2442 Instruction *I = RedoInsts.front();
2443 RedoInsts.erase(RedoInsts.begin());
2444 if (isInstructionTriviallyDead(I))
2445 EraseInst(I);
2446 else
2447 OptimizeInst(I);
2448 }
2449 }
2450
2451 // We are done with the rank map and pair map.
2452 RankMap.clear();
2453 ValueRankMap.clear();
2454 for (auto &Entry : PairMap)
2455 Entry.clear();
2456
2457 if (MadeChange) {
2458 PreservedAnalyses PA;
2459 PA.preserveSet<CFGAnalyses>();
2460 PA.preserve<GlobalsAA>();
2461 return PA;
2462 }
2463
2464 return PreservedAnalyses::all();
2465 }
2466
2467 namespace {
2468
2469 class ReassociateLegacyPass : public FunctionPass {
2470 ReassociatePass Impl;
2471
2472 public:
2473 static char ID; // Pass identification, replacement for typeid
2474
ReassociateLegacyPass()2475 ReassociateLegacyPass() : FunctionPass(ID) {
2476 initializeReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
2477 }
2478
runOnFunction(Function & F)2479 bool runOnFunction(Function &F) override {
2480 if (skipFunction(F))
2481 return false;
2482
2483 FunctionAnalysisManager DummyFAM;
2484 auto PA = Impl.run(F, DummyFAM);
2485 return !PA.areAllPreserved();
2486 }
2487
getAnalysisUsage(AnalysisUsage & AU) const2488 void getAnalysisUsage(AnalysisUsage &AU) const override {
2489 AU.setPreservesCFG();
2490 AU.addPreserved<GlobalsAAWrapperPass>();
2491 }
2492 };
2493
2494 } // end anonymous namespace
2495
2496 char ReassociateLegacyPass::ID = 0;
2497
2498 INITIALIZE_PASS(ReassociateLegacyPass, "reassociate",
2499 "Reassociate expressions", false, false)
2500
2501 // Public interface to the Reassociate pass
createReassociatePass()2502 FunctionPass *llvm::createReassociatePass() {
2503 return new ReassociateLegacyPass();
2504 }
2505