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