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