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