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