10b57cec5SDimitry Andric //===- Reassociate.cpp - Reassociate binary expressions -------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass reassociates commutative expressions in an order that is designed
100b57cec5SDimitry Andric // to promote better constant propagation, GCSE, LICM, PRE, etc.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric // For example: 4 + (x + 5) -> x + (4 + 5)
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric // In the implementation of this algorithm, constants are assigned rank = 0,
150b57cec5SDimitry Andric // function arguments are rank = 1, and other values are assigned ranks
160b57cec5SDimitry Andric // corresponding to the reverse post order traversal of current function
170b57cec5SDimitry Andric // (starting at 2), which effectively gives values in deep loops higher rank
180b57cec5SDimitry Andric // than values not in loops.
190b57cec5SDimitry Andric //
200b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
210b57cec5SDimitry Andric
220b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/Reassociate.h"
230b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
240b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
250b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
260b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
270b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
280b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
290b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
300b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
315ffd83dbSDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
32753f127fSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
330b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
340b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
350b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
360b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
370b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
380b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
390b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
400b57cec5SDimitry Andric #include "llvm/IR/Function.h"
410b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
420b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
430b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
440b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
450b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
460b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
470b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
480b57cec5SDimitry Andric #include "llvm/IR/Type.h"
490b57cec5SDimitry Andric #include "llvm/IR/User.h"
500b57cec5SDimitry Andric #include "llvm/IR/Value.h"
510b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
52480093f4SDimitry Andric #include "llvm/InitializePasses.h"
530b57cec5SDimitry Andric #include "llvm/Pass.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
5506c3fb27SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
580b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
59480093f4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
600b57cec5SDimitry Andric #include <algorithm>
610b57cec5SDimitry Andric #include <cassert>
620b57cec5SDimitry Andric #include <utility>
630b57cec5SDimitry Andric
640b57cec5SDimitry Andric using namespace llvm;
650b57cec5SDimitry Andric using namespace reassociate;
660b57cec5SDimitry Andric using namespace PatternMatch;
670b57cec5SDimitry Andric
680b57cec5SDimitry Andric #define DEBUG_TYPE "reassociate"
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric STATISTIC(NumChanged, "Number of insts reassociated");
710b57cec5SDimitry Andric STATISTIC(NumAnnihil, "Number of expr tree annihilated");
720b57cec5SDimitry Andric STATISTIC(NumFactor , "Number of multiplies factored");
730b57cec5SDimitry Andric
7406c3fb27SDimitry Andric static cl::opt<bool>
7506c3fb27SDimitry Andric UseCSELocalOpt(DEBUG_TYPE "-use-cse-local",
7606c3fb27SDimitry Andric cl::desc("Only reorder expressions within a basic block "
7706c3fb27SDimitry Andric "when exposing CSE opportunities"),
7806c3fb27SDimitry Andric cl::init(true), cl::Hidden);
7906c3fb27SDimitry Andric
800b57cec5SDimitry Andric #ifndef NDEBUG
810b57cec5SDimitry Andric /// Print out the expression identified in the Ops list.
PrintOps(Instruction * I,const SmallVectorImpl<ValueEntry> & Ops)820b57cec5SDimitry Andric static void PrintOps(Instruction *I, const SmallVectorImpl<ValueEntry> &Ops) {
830b57cec5SDimitry Andric Module *M = I->getModule();
840b57cec5SDimitry Andric dbgs() << Instruction::getOpcodeName(I->getOpcode()) << " "
850b57cec5SDimitry Andric << *Ops[0].Op->getType() << '\t';
860b57cec5SDimitry Andric for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
870b57cec5SDimitry Andric dbgs() << "[ ";
880b57cec5SDimitry Andric Ops[i].Op->printAsOperand(dbgs(), false, M);
890b57cec5SDimitry Andric dbgs() << ", #" << Ops[i].Rank << "] ";
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric #endif
930b57cec5SDimitry Andric
940b57cec5SDimitry Andric /// Utility class representing a non-constant Xor-operand. We classify
950b57cec5SDimitry Andric /// non-constant Xor-Operands into two categories:
960b57cec5SDimitry Andric /// C1) The operand is in the form "X & C", where C is a constant and C != ~0
970b57cec5SDimitry Andric /// C2)
980b57cec5SDimitry Andric /// C2.1) The operand is in the form of "X | C", where C is a non-zero
990b57cec5SDimitry Andric /// constant.
1000b57cec5SDimitry Andric /// C2.2) Any operand E which doesn't fall into C1 and C2.1, we view this
1010b57cec5SDimitry Andric /// operand as "E | 0"
1020b57cec5SDimitry Andric class llvm::reassociate::XorOpnd {
1030b57cec5SDimitry Andric public:
1040b57cec5SDimitry Andric XorOpnd(Value *V);
1050b57cec5SDimitry Andric
isInvalid() const1060b57cec5SDimitry Andric bool isInvalid() const { return SymbolicPart == nullptr; }
isOrExpr() const1070b57cec5SDimitry Andric bool isOrExpr() const { return isOr; }
getValue() const1080b57cec5SDimitry Andric Value *getValue() const { return OrigVal; }
getSymbolicPart() const1090b57cec5SDimitry Andric Value *getSymbolicPart() const { return SymbolicPart; }
getSymbolicRank() const1100b57cec5SDimitry Andric unsigned getSymbolicRank() const { return SymbolicRank; }
getConstPart() const1110b57cec5SDimitry Andric const APInt &getConstPart() const { return ConstPart; }
1120b57cec5SDimitry Andric
Invalidate()1130b57cec5SDimitry Andric void Invalidate() { SymbolicPart = OrigVal = nullptr; }
setSymbolicRank(unsigned R)1140b57cec5SDimitry Andric void setSymbolicRank(unsigned R) { SymbolicRank = R; }
1150b57cec5SDimitry Andric
1160b57cec5SDimitry Andric private:
1170b57cec5SDimitry Andric Value *OrigVal;
1180b57cec5SDimitry Andric Value *SymbolicPart;
1190b57cec5SDimitry Andric APInt ConstPart;
1200b57cec5SDimitry Andric unsigned SymbolicRank;
1210b57cec5SDimitry Andric bool isOr;
1220b57cec5SDimitry Andric };
1230b57cec5SDimitry Andric
XorOpnd(Value * V)1240b57cec5SDimitry Andric XorOpnd::XorOpnd(Value *V) {
1250b57cec5SDimitry Andric assert(!isa<ConstantInt>(V) && "No ConstantInt");
1260b57cec5SDimitry Andric OrigVal = V;
1270b57cec5SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
1280b57cec5SDimitry Andric SymbolicRank = 0;
1290b57cec5SDimitry Andric
1300b57cec5SDimitry Andric if (I && (I->getOpcode() == Instruction::Or ||
1310b57cec5SDimitry Andric I->getOpcode() == Instruction::And)) {
1320b57cec5SDimitry Andric Value *V0 = I->getOperand(0);
1330b57cec5SDimitry Andric Value *V1 = I->getOperand(1);
1340b57cec5SDimitry Andric const APInt *C;
1350b57cec5SDimitry Andric if (match(V0, m_APInt(C)))
1360b57cec5SDimitry Andric std::swap(V0, V1);
1370b57cec5SDimitry Andric
1380b57cec5SDimitry Andric if (match(V1, m_APInt(C))) {
1390b57cec5SDimitry Andric ConstPart = *C;
1400b57cec5SDimitry Andric SymbolicPart = V0;
1410b57cec5SDimitry Andric isOr = (I->getOpcode() == Instruction::Or);
1420b57cec5SDimitry Andric return;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric
1460b57cec5SDimitry Andric // view the operand as "V | 0"
1470b57cec5SDimitry Andric SymbolicPart = V;
148349cc55cSDimitry Andric ConstPart = APInt::getZero(V->getType()->getScalarSizeInBits());
1490b57cec5SDimitry Andric isOr = true;
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric
152fcaf7f86SDimitry Andric /// Return true if I is an instruction with the FastMathFlags that are needed
153fcaf7f86SDimitry Andric /// for general reassociation set. This is not the same as testing
154fcaf7f86SDimitry Andric /// Instruction::isAssociative() because it includes operations like fsub.
155fcaf7f86SDimitry Andric /// (This routine is only intended to be called for floating-point operations.)
hasFPAssociativeFlags(Instruction * I)156fcaf7f86SDimitry Andric static bool hasFPAssociativeFlags(Instruction *I) {
157972a253aSDimitry Andric assert(I && isa<FPMathOperator>(I) && "Should only check FP ops");
158fcaf7f86SDimitry Andric return I->hasAllowReassoc() && I->hasNoSignedZeros();
159fcaf7f86SDimitry Andric }
160fcaf7f86SDimitry Andric
1610b57cec5SDimitry Andric /// Return true if V is an instruction of the specified opcode and if it
1620b57cec5SDimitry Andric /// only has one use.
isReassociableOp(Value * V,unsigned Opcode)1630b57cec5SDimitry Andric static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode) {
164972a253aSDimitry Andric auto *BO = dyn_cast<BinaryOperator>(V);
165972a253aSDimitry Andric if (BO && BO->hasOneUse() && BO->getOpcode() == Opcode)
166972a253aSDimitry Andric if (!isa<FPMathOperator>(BO) || hasFPAssociativeFlags(BO))
167972a253aSDimitry Andric return BO;
1680b57cec5SDimitry Andric return nullptr;
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric
isReassociableOp(Value * V,unsigned Opcode1,unsigned Opcode2)1710b57cec5SDimitry Andric static BinaryOperator *isReassociableOp(Value *V, unsigned Opcode1,
1720b57cec5SDimitry Andric unsigned Opcode2) {
173972a253aSDimitry Andric auto *BO = dyn_cast<BinaryOperator>(V);
174972a253aSDimitry Andric if (BO && BO->hasOneUse() &&
175972a253aSDimitry Andric (BO->getOpcode() == Opcode1 || BO->getOpcode() == Opcode2))
176972a253aSDimitry Andric if (!isa<FPMathOperator>(BO) || hasFPAssociativeFlags(BO))
177972a253aSDimitry Andric return BO;
1780b57cec5SDimitry Andric return nullptr;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric
BuildRankMap(Function & F,ReversePostOrderTraversal<Function * > & RPOT)1810b57cec5SDimitry Andric void ReassociatePass::BuildRankMap(Function &F,
1820b57cec5SDimitry Andric ReversePostOrderTraversal<Function*> &RPOT) {
1830b57cec5SDimitry Andric unsigned Rank = 2;
1840b57cec5SDimitry Andric
1850b57cec5SDimitry Andric // Assign distinct ranks to function arguments.
1860b57cec5SDimitry Andric for (auto &Arg : F.args()) {
1870b57cec5SDimitry Andric ValueRankMap[&Arg] = ++Rank;
1880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Calculated Rank[" << Arg.getName() << "] = " << Rank
1890b57cec5SDimitry Andric << "\n");
1900b57cec5SDimitry Andric }
1910b57cec5SDimitry Andric
192480093f4SDimitry Andric // Traverse basic blocks in ReversePostOrder.
1930b57cec5SDimitry Andric for (BasicBlock *BB : RPOT) {
1940b57cec5SDimitry Andric unsigned BBRank = RankMap[BB] = ++Rank << 16;
1950b57cec5SDimitry Andric
1960b57cec5SDimitry Andric // Walk the basic block, adding precomputed ranks for any instructions that
1970b57cec5SDimitry Andric // we cannot move. This ensures that the ranks for these instructions are
1980b57cec5SDimitry Andric // all different in the block.
1990b57cec5SDimitry Andric for (Instruction &I : *BB)
20081ad6265SDimitry Andric if (mayHaveNonDefUseDependency(I))
2010b57cec5SDimitry Andric ValueRankMap[&I] = ++BBRank;
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric
getRank(Value * V)2050b57cec5SDimitry Andric unsigned ReassociatePass::getRank(Value *V) {
2060b57cec5SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
2070b57cec5SDimitry Andric if (!I) {
2080b57cec5SDimitry Andric if (isa<Argument>(V)) return ValueRankMap[V]; // Function argument.
2090b57cec5SDimitry Andric return 0; // Otherwise it's a global or constant, rank 0.
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric
2120b57cec5SDimitry Andric if (unsigned Rank = ValueRankMap[I])
2130b57cec5SDimitry Andric return Rank; // Rank already known?
2140b57cec5SDimitry Andric
2150b57cec5SDimitry Andric // If this is an expression, return the 1+MAX(rank(LHS), rank(RHS)) so that
2160b57cec5SDimitry Andric // we can reassociate expressions for code motion! Since we do not recurse
2170b57cec5SDimitry Andric // for PHI nodes, we cannot have infinite recursion here, because there
2180b57cec5SDimitry Andric // cannot be loops in the value graph that do not go through PHI nodes.
2190b57cec5SDimitry Andric unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
2200b57cec5SDimitry Andric for (unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i)
2210b57cec5SDimitry Andric Rank = std::max(Rank, getRank(I->getOperand(i)));
2220b57cec5SDimitry Andric
2230b57cec5SDimitry Andric // If this is a 'not' or 'neg' instruction, do not count it for rank. This
2240b57cec5SDimitry Andric // assures us that X and ~X will have the same rank.
2250b57cec5SDimitry Andric if (!match(I, m_Not(m_Value())) && !match(I, m_Neg(m_Value())) &&
2260b57cec5SDimitry Andric !match(I, m_FNeg(m_Value())))
2270b57cec5SDimitry Andric ++Rank;
2280b57cec5SDimitry Andric
2290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Calculated Rank[" << V->getName() << "] = " << Rank
2300b57cec5SDimitry Andric << "\n");
2310b57cec5SDimitry Andric
2320b57cec5SDimitry Andric return ValueRankMap[I] = Rank;
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric
2350b57cec5SDimitry Andric // Canonicalize constants to RHS. Otherwise, sort the operands by rank.
canonicalizeOperands(Instruction * I)2360b57cec5SDimitry Andric void ReassociatePass::canonicalizeOperands(Instruction *I) {
2370b57cec5SDimitry Andric assert(isa<BinaryOperator>(I) && "Expected binary operator.");
2380b57cec5SDimitry Andric assert(I->isCommutative() && "Expected commutative operator.");
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric Value *LHS = I->getOperand(0);
2410b57cec5SDimitry Andric Value *RHS = I->getOperand(1);
2420b57cec5SDimitry Andric if (LHS == RHS || isa<Constant>(RHS))
2430b57cec5SDimitry Andric return;
2440b57cec5SDimitry Andric if (isa<Constant>(LHS) || getRank(RHS) < getRank(LHS))
2450b57cec5SDimitry Andric cast<BinaryOperator>(I)->swapOperands();
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric
CreateAdd(Value * S1,Value * S2,const Twine & Name,BasicBlock::iterator InsertBefore,Value * FlagsOp)2480b57cec5SDimitry Andric static BinaryOperator *CreateAdd(Value *S1, Value *S2, const Twine &Name,
249*0fca6ea1SDimitry Andric BasicBlock::iterator InsertBefore,
250*0fca6ea1SDimitry Andric Value *FlagsOp) {
2510b57cec5SDimitry Andric if (S1->getType()->isIntOrIntVectorTy())
2520b57cec5SDimitry Andric return BinaryOperator::CreateAdd(S1, S2, Name, InsertBefore);
2530b57cec5SDimitry Andric else {
2540b57cec5SDimitry Andric BinaryOperator *Res =
2550b57cec5SDimitry Andric BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
2560b57cec5SDimitry Andric Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
2570b57cec5SDimitry Andric return Res;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric
CreateMul(Value * S1,Value * S2,const Twine & Name,BasicBlock::iterator InsertBefore,Value * FlagsOp)2610b57cec5SDimitry Andric static BinaryOperator *CreateMul(Value *S1, Value *S2, const Twine &Name,
262*0fca6ea1SDimitry Andric BasicBlock::iterator InsertBefore,
263*0fca6ea1SDimitry Andric Value *FlagsOp) {
2640b57cec5SDimitry Andric if (S1->getType()->isIntOrIntVectorTy())
2650b57cec5SDimitry Andric return BinaryOperator::CreateMul(S1, S2, Name, InsertBefore);
2660b57cec5SDimitry Andric else {
2670b57cec5SDimitry Andric BinaryOperator *Res =
2680b57cec5SDimitry Andric BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
2690b57cec5SDimitry Andric Res->setFastMathFlags(cast<FPMathOperator>(FlagsOp)->getFastMathFlags());
2700b57cec5SDimitry Andric return Res;
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric
CreateNeg(Value * S1,const Twine & Name,BasicBlock::iterator InsertBefore,Value * FlagsOp)2745ffd83dbSDimitry Andric static Instruction *CreateNeg(Value *S1, const Twine &Name,
275*0fca6ea1SDimitry Andric BasicBlock::iterator InsertBefore,
276*0fca6ea1SDimitry Andric Value *FlagsOp) {
2770b57cec5SDimitry Andric if (S1->getType()->isIntOrIntVectorTy())
2780b57cec5SDimitry Andric return BinaryOperator::CreateNeg(S1, Name, InsertBefore);
2795ffd83dbSDimitry Andric
2805ffd83dbSDimitry Andric if (auto *FMFSource = dyn_cast<Instruction>(FlagsOp))
2815ffd83dbSDimitry Andric return UnaryOperator::CreateFNegFMF(S1, FMFSource, Name, InsertBefore);
2825ffd83dbSDimitry Andric
2835ffd83dbSDimitry Andric return UnaryOperator::CreateFNeg(S1, Name, InsertBefore);
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric
2860b57cec5SDimitry Andric /// Replace 0-X with X*-1.
LowerNegateToMultiply(Instruction * Neg)2870b57cec5SDimitry Andric static BinaryOperator *LowerNegateToMultiply(Instruction *Neg) {
2880b57cec5SDimitry Andric assert((isa<UnaryOperator>(Neg) || isa<BinaryOperator>(Neg)) &&
2890b57cec5SDimitry Andric "Expected a Negate!");
2900b57cec5SDimitry Andric // FIXME: It's not safe to lower a unary FNeg into a FMul by -1.0.
2910b57cec5SDimitry Andric unsigned OpNo = isa<BinaryOperator>(Neg) ? 1 : 0;
2920b57cec5SDimitry Andric Type *Ty = Neg->getType();
2930b57cec5SDimitry Andric Constant *NegOne = Ty->isIntOrIntVectorTy() ?
2940b57cec5SDimitry Andric ConstantInt::getAllOnesValue(Ty) : ConstantFP::get(Ty, -1.0);
2950b57cec5SDimitry Andric
296*0fca6ea1SDimitry Andric BinaryOperator *Res =
297*0fca6ea1SDimitry Andric CreateMul(Neg->getOperand(OpNo), NegOne, "", Neg->getIterator(), Neg);
2980b57cec5SDimitry Andric Neg->setOperand(OpNo, Constant::getNullValue(Ty)); // Drop use of op.
2990b57cec5SDimitry Andric Res->takeName(Neg);
3000b57cec5SDimitry Andric Neg->replaceAllUsesWith(Res);
3010b57cec5SDimitry Andric Res->setDebugLoc(Neg->getDebugLoc());
3020b57cec5SDimitry Andric return Res;
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric
305*0fca6ea1SDimitry Andric using RepeatedValue = std::pair<Value *, uint64_t>;
3060b57cec5SDimitry Andric
3070b57cec5SDimitry Andric /// Given an associative binary expression, return the leaf
3080b57cec5SDimitry Andric /// nodes in Ops along with their weights (how many times the leaf occurs). The
3090b57cec5SDimitry Andric /// original expression is the same as
3100b57cec5SDimitry Andric /// (Ops[0].first op Ops[0].first op ... Ops[0].first) <- Ops[0].second times
3110b57cec5SDimitry Andric /// op
3120b57cec5SDimitry Andric /// (Ops[1].first op Ops[1].first op ... Ops[1].first) <- Ops[1].second times
3130b57cec5SDimitry Andric /// op
3140b57cec5SDimitry Andric /// ...
3150b57cec5SDimitry Andric /// op
3160b57cec5SDimitry Andric /// (Ops[N].first op Ops[N].first op ... Ops[N].first) <- Ops[N].second times
3170b57cec5SDimitry Andric ///
3180b57cec5SDimitry Andric /// Note that the values Ops[0].first, ..., Ops[N].first are all distinct.
3190b57cec5SDimitry Andric ///
3200b57cec5SDimitry Andric /// This routine may modify the function, in which case it returns 'true'. The
3210b57cec5SDimitry Andric /// changes it makes may well be destructive, changing the value computed by 'I'
3220b57cec5SDimitry Andric /// to something completely different. Thus if the routine returns 'true' then
3230b57cec5SDimitry Andric /// you MUST either replace I with a new expression computed from the Ops array,
3240b57cec5SDimitry Andric /// or use RewriteExprTree to put the values back in.
3250b57cec5SDimitry Andric ///
3260b57cec5SDimitry Andric /// A leaf node is either not a binary operation of the same kind as the root
3270b57cec5SDimitry Andric /// node 'I' (i.e. is not a binary operator at all, or is, but with a different
3280b57cec5SDimitry Andric /// opcode), or is the same kind of binary operator but has a use which either
3290b57cec5SDimitry Andric /// does not belong to the expression, or does belong to the expression but is
3300b57cec5SDimitry Andric /// a leaf node. Every leaf node has at least one use that is a non-leaf node
3310b57cec5SDimitry Andric /// of the expression, while for non-leaf nodes (except for the root 'I') every
3320b57cec5SDimitry Andric /// use is a non-leaf node of the expression.
3330b57cec5SDimitry Andric ///
3340b57cec5SDimitry Andric /// For example:
3350b57cec5SDimitry Andric /// expression graph node names
3360b57cec5SDimitry Andric ///
3370b57cec5SDimitry Andric /// + | I
3380b57cec5SDimitry Andric /// / \ |
3390b57cec5SDimitry Andric /// + + | A, B
3400b57cec5SDimitry Andric /// / \ / \ |
3410b57cec5SDimitry Andric /// * + * | C, D, E
3420b57cec5SDimitry Andric /// / \ / \ / \ |
3430b57cec5SDimitry Andric /// + * | F, G
3440b57cec5SDimitry Andric ///
3450b57cec5SDimitry Andric /// The leaf nodes are C, E, F and G. The Ops array will contain (maybe not in
3460b57cec5SDimitry Andric /// that order) (C, 1), (E, 1), (F, 2), (G, 2).
3470b57cec5SDimitry Andric ///
3480b57cec5SDimitry Andric /// The expression is maximal: if some instruction is a binary operator of the
3490b57cec5SDimitry Andric /// same kind as 'I', and all of its uses are non-leaf nodes of the expression,
3500b57cec5SDimitry Andric /// then the instruction also belongs to the expression, is not a leaf node of
3510b57cec5SDimitry Andric /// it, and its operands also belong to the expression (but may be leaf nodes).
3520b57cec5SDimitry Andric ///
3530b57cec5SDimitry Andric /// NOTE: This routine will set operands of non-leaf non-root nodes to undef in
3540b57cec5SDimitry Andric /// order to ensure that every non-root node in the expression has *exactly one*
3550b57cec5SDimitry Andric /// use by a non-leaf node of the expression. This destruction means that the
3560b57cec5SDimitry Andric /// caller MUST either replace 'I' with a new expression or use something like
3570b57cec5SDimitry Andric /// RewriteExprTree to put the values back in if the routine indicates that it
3580b57cec5SDimitry Andric /// made a change by returning 'true'.
3590b57cec5SDimitry Andric ///
3600b57cec5SDimitry Andric /// In the above example either the right operand of A or the left operand of B
3610b57cec5SDimitry Andric /// will be replaced by undef. If it is B's operand then this gives:
3620b57cec5SDimitry Andric ///
3630b57cec5SDimitry Andric /// + | I
3640b57cec5SDimitry Andric /// / \ |
3650b57cec5SDimitry Andric /// + + | A, B - operand of B replaced with undef
3660b57cec5SDimitry Andric /// / \ \ |
3670b57cec5SDimitry Andric /// * + * | C, D, E
3680b57cec5SDimitry Andric /// / \ / \ / \ |
3690b57cec5SDimitry Andric /// + * | F, G
3700b57cec5SDimitry Andric ///
3710b57cec5SDimitry Andric /// Note that such undef operands can only be reached by passing through 'I'.
3720b57cec5SDimitry Andric /// For example, if you visit operands recursively starting from a leaf node
3730b57cec5SDimitry Andric /// then you will never see such an undef operand unless you get back to 'I',
3740b57cec5SDimitry Andric /// which requires passing through a phi node.
3750b57cec5SDimitry Andric ///
3760b57cec5SDimitry Andric /// Note that this routine may also mutate binary operators of the wrong type
3770b57cec5SDimitry Andric /// that have all uses inside the expression (i.e. only used by non-leaf nodes
3780b57cec5SDimitry Andric /// of the expression) if it can turn them into binary operators of the right
3790b57cec5SDimitry Andric /// type and thus make the expression bigger.
LinearizeExprTree(Instruction * I,SmallVectorImpl<RepeatedValue> & Ops,ReassociatePass::OrderedSet & ToRedo,reassociate::OverflowTracking & Flags)3800b57cec5SDimitry Andric static bool LinearizeExprTree(Instruction *I,
381fcaf7f86SDimitry Andric SmallVectorImpl<RepeatedValue> &Ops,
3825f757f3fSDimitry Andric ReassociatePass::OrderedSet &ToRedo,
383*0fca6ea1SDimitry Andric reassociate::OverflowTracking &Flags) {
3840b57cec5SDimitry Andric assert((isa<UnaryOperator>(I) || isa<BinaryOperator>(I)) &&
3850b57cec5SDimitry Andric "Expected a UnaryOperator or BinaryOperator!");
3860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LINEARIZE: " << *I << '\n');
3870b57cec5SDimitry Andric unsigned Opcode = I->getOpcode();
3880b57cec5SDimitry Andric assert(I->isAssociative() && I->isCommutative() &&
3890b57cec5SDimitry Andric "Expected an associative and commutative operation!");
3900b57cec5SDimitry Andric
3910b57cec5SDimitry Andric // Visit all operands of the expression, keeping track of their weight (the
3920b57cec5SDimitry Andric // number of paths from the expression root to the operand, or if you like
3930b57cec5SDimitry Andric // the number of times that operand occurs in the linearized expression).
3940b57cec5SDimitry Andric // For example, if I = X + A, where X = A + B, then I, X and B have weight 1
3950b57cec5SDimitry Andric // while A has weight two.
3960b57cec5SDimitry Andric
3970b57cec5SDimitry Andric // Worklist of non-leaf nodes (their operands are in the expression too) along
3980b57cec5SDimitry Andric // with their weights, representing a certain number of paths to the operator.
3990b57cec5SDimitry Andric // If an operator occurs in the worklist multiple times then we found multiple
4000b57cec5SDimitry Andric // ways to get to it.
401*0fca6ea1SDimitry Andric SmallVector<std::pair<Instruction *, uint64_t>, 8> Worklist; // (Op, Weight)
402*0fca6ea1SDimitry Andric Worklist.push_back(std::make_pair(I, 1));
4030b57cec5SDimitry Andric bool Changed = false;
4040b57cec5SDimitry Andric
4050b57cec5SDimitry Andric // Leaves of the expression are values that either aren't the right kind of
4060b57cec5SDimitry Andric // operation (eg: a constant, or a multiply in an add tree), or are, but have
4070b57cec5SDimitry Andric // some uses that are not inside the expression. For example, in I = X + X,
4080b57cec5SDimitry Andric // X = A + B, the value X has two uses (by I) that are in the expression. If
4090b57cec5SDimitry Andric // X has any other uses, for example in a return instruction, then we consider
4100b57cec5SDimitry Andric // X to be a leaf, and won't analyze it further. When we first visit a value,
4110b57cec5SDimitry Andric // if it has more than one use then at first we conservatively consider it to
4120b57cec5SDimitry Andric // be a leaf. Later, as the expression is explored, we may discover some more
4130b57cec5SDimitry Andric // uses of the value from inside the expression. If all uses turn out to be
4140b57cec5SDimitry Andric // from within the expression (and the value is a binary operator of the right
4150b57cec5SDimitry Andric // kind) then the value is no longer considered to be a leaf, and its operands
4160b57cec5SDimitry Andric // are explored.
4170b57cec5SDimitry Andric
4180b57cec5SDimitry Andric // Leaves - Keeps track of the set of putative leaves as well as the number of
4190b57cec5SDimitry Andric // paths to each leaf seen so far.
420*0fca6ea1SDimitry Andric using LeafMap = DenseMap<Value *, uint64_t>;
4210b57cec5SDimitry Andric LeafMap Leaves; // Leaf -> Total weight so far.
4220b57cec5SDimitry Andric SmallVector<Value *, 8> LeafOrder; // Ensure deterministic leaf output order.
423*0fca6ea1SDimitry Andric const DataLayout DL = I->getDataLayout();
4240b57cec5SDimitry Andric
4250b57cec5SDimitry Andric #ifndef NDEBUG
4264824e7fdSDimitry Andric SmallPtrSet<Value *, 8> Visited; // For checking the iteration scheme.
4270b57cec5SDimitry Andric #endif
4280b57cec5SDimitry Andric while (!Worklist.empty()) {
429*0fca6ea1SDimitry Andric // We examine the operands of this binary operator.
430*0fca6ea1SDimitry Andric auto [I, Weight] = Worklist.pop_back_val();
4310b57cec5SDimitry Andric
432*0fca6ea1SDimitry Andric if (isa<OverflowingBinaryOperator>(I)) {
433*0fca6ea1SDimitry Andric Flags.HasNUW &= I->hasNoUnsignedWrap();
434*0fca6ea1SDimitry Andric Flags.HasNSW &= I->hasNoSignedWrap();
435*0fca6ea1SDimitry Andric }
4365f757f3fSDimitry Andric
4370b57cec5SDimitry Andric for (unsigned OpIdx = 0; OpIdx < I->getNumOperands(); ++OpIdx) { // Visit operands.
4380b57cec5SDimitry Andric Value *Op = I->getOperand(OpIdx);
4390b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "OPERAND: " << *Op << " (" << Weight << ")\n");
4400b57cec5SDimitry Andric assert(!Op->use_empty() && "No uses, so how did we get to it?!");
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric // If this is a binary operation of the right kind with only one use then
4430b57cec5SDimitry Andric // add its operands to the expression.
4440b57cec5SDimitry Andric if (BinaryOperator *BO = isReassociableOp(Op, Opcode)) {
4450b57cec5SDimitry Andric assert(Visited.insert(Op).second && "Not first visit!");
4460b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "DIRECT ADD: " << *Op << " (" << Weight << ")\n");
4470b57cec5SDimitry Andric Worklist.push_back(std::make_pair(BO, Weight));
4480b57cec5SDimitry Andric continue;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric // Appears to be a leaf. Is the operand already in the set of leaves?
4520b57cec5SDimitry Andric LeafMap::iterator It = Leaves.find(Op);
4530b57cec5SDimitry Andric if (It == Leaves.end()) {
4540b57cec5SDimitry Andric // Not in the leaf map. Must be the first time we saw this operand.
4550b57cec5SDimitry Andric assert(Visited.insert(Op).second && "Not first visit!");
4560b57cec5SDimitry Andric if (!Op->hasOneUse()) {
4570b57cec5SDimitry Andric // This value has uses not accounted for by the expression, so it is
4580b57cec5SDimitry Andric // not safe to modify. Mark it as being a leaf.
4590b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
4600b57cec5SDimitry Andric << "ADD USES LEAF: " << *Op << " (" << Weight << ")\n");
4610b57cec5SDimitry Andric LeafOrder.push_back(Op);
4620b57cec5SDimitry Andric Leaves[Op] = Weight;
4630b57cec5SDimitry Andric continue;
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric // No uses outside the expression, try morphing it.
4660b57cec5SDimitry Andric } else {
4670b57cec5SDimitry Andric // Already in the leaf map.
4680b57cec5SDimitry Andric assert(It != Leaves.end() && Visited.count(Op) &&
4690b57cec5SDimitry Andric "In leaf map but not visited!");
4700b57cec5SDimitry Andric
4710b57cec5SDimitry Andric // Update the number of paths to the leaf.
472*0fca6ea1SDimitry Andric It->second += Weight;
473*0fca6ea1SDimitry Andric assert(It->second >= Weight && "Weight overflows");
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric // If we still have uses that are not accounted for by the expression
4760b57cec5SDimitry Andric // then it is not safe to modify the value.
4770b57cec5SDimitry Andric if (!Op->hasOneUse())
4780b57cec5SDimitry Andric continue;
4790b57cec5SDimitry Andric
4800b57cec5SDimitry Andric // No uses outside the expression, try morphing it.
4810b57cec5SDimitry Andric Weight = It->second;
4820b57cec5SDimitry Andric Leaves.erase(It); // Since the value may be morphed below.
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric
4850b57cec5SDimitry Andric // At this point we have a value which, first of all, is not a binary
4860b57cec5SDimitry Andric // expression of the right kind, and secondly, is only used inside the
4870b57cec5SDimitry Andric // expression. This means that it can safely be modified. See if we
4880b57cec5SDimitry Andric // can usefully morph it into an expression of the right kind.
4890b57cec5SDimitry Andric assert((!isa<Instruction>(Op) ||
4900b57cec5SDimitry Andric cast<Instruction>(Op)->getOpcode() != Opcode
4910b57cec5SDimitry Andric || (isa<FPMathOperator>(Op) &&
492fcaf7f86SDimitry Andric !hasFPAssociativeFlags(cast<Instruction>(Op)))) &&
4930b57cec5SDimitry Andric "Should have been handled above!");
4940b57cec5SDimitry Andric assert(Op->hasOneUse() && "Has uses outside the expression tree!");
4950b57cec5SDimitry Andric
4960b57cec5SDimitry Andric // If this is a multiply expression, turn any internal negations into
497fcaf7f86SDimitry Andric // multiplies by -1 so they can be reassociated. Add any users of the
498fcaf7f86SDimitry Andric // newly created multiplication by -1 to the redo list, so any
499fcaf7f86SDimitry Andric // reassociation opportunities that are exposed will be reassociated
500fcaf7f86SDimitry Andric // further.
501fcaf7f86SDimitry Andric Instruction *Neg;
502fcaf7f86SDimitry Andric if (((Opcode == Instruction::Mul && match(Op, m_Neg(m_Value()))) ||
503fcaf7f86SDimitry Andric (Opcode == Instruction::FMul && match(Op, m_FNeg(m_Value())))) &&
504fcaf7f86SDimitry Andric match(Op, m_Instruction(Neg))) {
5050b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
5060b57cec5SDimitry Andric << "MORPH LEAF: " << *Op << " (" << Weight << ") TO ");
507fcaf7f86SDimitry Andric Instruction *Mul = LowerNegateToMultiply(Neg);
508fcaf7f86SDimitry Andric LLVM_DEBUG(dbgs() << *Mul << '\n');
509fcaf7f86SDimitry Andric Worklist.push_back(std::make_pair(Mul, Weight));
510fcaf7f86SDimitry Andric for (User *U : Mul->users()) {
511fcaf7f86SDimitry Andric if (BinaryOperator *UserBO = dyn_cast<BinaryOperator>(U))
512fcaf7f86SDimitry Andric ToRedo.insert(UserBO);
513fcaf7f86SDimitry Andric }
514fcaf7f86SDimitry Andric ToRedo.insert(Neg);
5150b57cec5SDimitry Andric Changed = true;
5160b57cec5SDimitry Andric continue;
5170b57cec5SDimitry Andric }
5180b57cec5SDimitry Andric
5190b57cec5SDimitry Andric // Failed to morph into an expression of the right type. This really is
5200b57cec5SDimitry Andric // a leaf.
5210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "ADD LEAF: " << *Op << " (" << Weight << ")\n");
5220b57cec5SDimitry Andric assert(!isReassociableOp(Op, Opcode) && "Value was morphed?");
5230b57cec5SDimitry Andric LeafOrder.push_back(Op);
5240b57cec5SDimitry Andric Leaves[Op] = Weight;
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric }
5270b57cec5SDimitry Andric
5280b57cec5SDimitry Andric // The leaves, repeated according to their weights, represent the linearized
5290b57cec5SDimitry Andric // form of the expression.
53006c3fb27SDimitry Andric for (Value *V : LeafOrder) {
5310b57cec5SDimitry Andric LeafMap::iterator It = Leaves.find(V);
5320b57cec5SDimitry Andric if (It == Leaves.end())
5330b57cec5SDimitry Andric // Node initially thought to be a leaf wasn't.
5340b57cec5SDimitry Andric continue;
5350b57cec5SDimitry Andric assert(!isReassociableOp(V, Opcode) && "Shouldn't be a leaf!");
536*0fca6ea1SDimitry Andric uint64_t Weight = It->second;
5370b57cec5SDimitry Andric // Ensure the leaf is only output once.
5380b57cec5SDimitry Andric It->second = 0;
5390b57cec5SDimitry Andric Ops.push_back(std::make_pair(V, Weight));
540*0fca6ea1SDimitry Andric if (Opcode == Instruction::Add && Flags.AllKnownNonNegative && Flags.HasNSW)
541*0fca6ea1SDimitry Andric Flags.AllKnownNonNegative &= isKnownNonNegative(V, SimplifyQuery(DL));
542*0fca6ea1SDimitry Andric else if (Opcode == Instruction::Mul) {
543*0fca6ea1SDimitry Andric // To preserve NUW we need all inputs non-zero.
544*0fca6ea1SDimitry Andric // To preserve NSW we need all inputs strictly positive.
545*0fca6ea1SDimitry Andric if (Flags.AllKnownNonZero &&
546*0fca6ea1SDimitry Andric (Flags.HasNUW || (Flags.HasNSW && Flags.AllKnownNonNegative))) {
547*0fca6ea1SDimitry Andric Flags.AllKnownNonZero &= isKnownNonZero(V, SimplifyQuery(DL));
548*0fca6ea1SDimitry Andric if (Flags.HasNSW && Flags.AllKnownNonNegative)
549*0fca6ea1SDimitry Andric Flags.AllKnownNonNegative &= isKnownNonNegative(V, SimplifyQuery(DL));
550*0fca6ea1SDimitry Andric }
551*0fca6ea1SDimitry Andric }
5520b57cec5SDimitry Andric }
5530b57cec5SDimitry Andric
5540b57cec5SDimitry Andric // For nilpotent operations or addition there may be no operands, for example
5550b57cec5SDimitry Andric // because the expression was "X xor X" or consisted of 2^Bitwidth additions:
5560b57cec5SDimitry Andric // in both cases the weight reduces to 0 causing the value to be skipped.
5570b57cec5SDimitry Andric if (Ops.empty()) {
5580b57cec5SDimitry Andric Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, I->getType());
5590b57cec5SDimitry Andric assert(Identity && "Associative operation without identity!");
560*0fca6ea1SDimitry Andric Ops.emplace_back(Identity, 1);
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric
5630b57cec5SDimitry Andric return Changed;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric
5660b57cec5SDimitry Andric /// Now that the operands for this expression tree are
5670b57cec5SDimitry Andric /// linearized and optimized, emit them in-order.
RewriteExprTree(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops,OverflowTracking Flags)5680b57cec5SDimitry Andric void ReassociatePass::RewriteExprTree(BinaryOperator *I,
5695f757f3fSDimitry Andric SmallVectorImpl<ValueEntry> &Ops,
570*0fca6ea1SDimitry Andric OverflowTracking Flags) {
5710b57cec5SDimitry Andric assert(Ops.size() > 1 && "Single values should be used directly!");
5720b57cec5SDimitry Andric
5730b57cec5SDimitry Andric // Since our optimizations should never increase the number of operations, the
5740b57cec5SDimitry Andric // new expression can usually be written reusing the existing binary operators
5750b57cec5SDimitry Andric // from the original expression tree, without creating any new instructions,
5760b57cec5SDimitry Andric // though the rewritten expression may have a completely different topology.
5770b57cec5SDimitry Andric // We take care to not change anything if the new expression will be the same
5780b57cec5SDimitry Andric // as the original. If more than trivial changes (like commuting operands)
5790b57cec5SDimitry Andric // were made then we are obliged to clear out any optional subclass data like
5800b57cec5SDimitry Andric // nsw flags.
5810b57cec5SDimitry Andric
5820b57cec5SDimitry Andric /// NodesToRewrite - Nodes from the original expression available for writing
5830b57cec5SDimitry Andric /// the new expression into.
5840b57cec5SDimitry Andric SmallVector<BinaryOperator*, 8> NodesToRewrite;
5850b57cec5SDimitry Andric unsigned Opcode = I->getOpcode();
5860b57cec5SDimitry Andric BinaryOperator *Op = I;
5870b57cec5SDimitry Andric
5880b57cec5SDimitry Andric /// NotRewritable - The operands being written will be the leaves of the new
5890b57cec5SDimitry Andric /// expression and must not be used as inner nodes (via NodesToRewrite) by
5900b57cec5SDimitry Andric /// mistake. Inner nodes are always reassociable, and usually leaves are not
5910b57cec5SDimitry Andric /// (if they were they would have been incorporated into the expression and so
5920b57cec5SDimitry Andric /// would not be leaves), so most of the time there is no danger of this. But
5930b57cec5SDimitry Andric /// in rare cases a leaf may become reassociable if an optimization kills uses
5940b57cec5SDimitry Andric /// of it, or it may momentarily become reassociable during rewriting (below)
5950b57cec5SDimitry Andric /// due it being removed as an operand of one of its uses. Ensure that misuse
5960b57cec5SDimitry Andric /// of leaf nodes as inner nodes cannot occur by remembering all of the future
5970b57cec5SDimitry Andric /// leaves and refusing to reuse any of them as inner nodes.
5980b57cec5SDimitry Andric SmallPtrSet<Value*, 8> NotRewritable;
599*0fca6ea1SDimitry Andric for (const ValueEntry &Op : Ops)
600*0fca6ea1SDimitry Andric NotRewritable.insert(Op.Op);
6010b57cec5SDimitry Andric
60206c3fb27SDimitry Andric // ExpressionChangedStart - Non-null if the rewritten expression differs from
60306c3fb27SDimitry Andric // the original in some non-trivial way, requiring the clearing of optional
60406c3fb27SDimitry Andric // flags. Flags are cleared from the operator in ExpressionChangedStart up to
60506c3fb27SDimitry Andric // ExpressionChangedEnd inclusive.
60606c3fb27SDimitry Andric BinaryOperator *ExpressionChangedStart = nullptr,
60706c3fb27SDimitry Andric *ExpressionChangedEnd = nullptr;
6080b57cec5SDimitry Andric for (unsigned i = 0; ; ++i) {
6090b57cec5SDimitry Andric // The last operation (which comes earliest in the IR) is special as both
6100b57cec5SDimitry Andric // operands will come from Ops, rather than just one with the other being
6110b57cec5SDimitry Andric // a subexpression.
6120b57cec5SDimitry Andric if (i+2 == Ops.size()) {
6130b57cec5SDimitry Andric Value *NewLHS = Ops[i].Op;
6140b57cec5SDimitry Andric Value *NewRHS = Ops[i+1].Op;
6150b57cec5SDimitry Andric Value *OldLHS = Op->getOperand(0);
6160b57cec5SDimitry Andric Value *OldRHS = Op->getOperand(1);
6170b57cec5SDimitry Andric
6180b57cec5SDimitry Andric if (NewLHS == OldLHS && NewRHS == OldRHS)
6190b57cec5SDimitry Andric // Nothing changed, leave it alone.
6200b57cec5SDimitry Andric break;
6210b57cec5SDimitry Andric
6220b57cec5SDimitry Andric if (NewLHS == OldRHS && NewRHS == OldLHS) {
6230b57cec5SDimitry Andric // The order of the operands was reversed. Swap them.
6240b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
6250b57cec5SDimitry Andric Op->swapOperands();
6260b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
6270b57cec5SDimitry Andric MadeChange = true;
6280b57cec5SDimitry Andric ++NumChanged;
6290b57cec5SDimitry Andric break;
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric // The new operation differs non-trivially from the original. Overwrite
6330b57cec5SDimitry Andric // the old operands with the new ones.
6340b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
6350b57cec5SDimitry Andric if (NewLHS != OldLHS) {
6360b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(OldLHS, Opcode);
6370b57cec5SDimitry Andric if (BO && !NotRewritable.count(BO))
6380b57cec5SDimitry Andric NodesToRewrite.push_back(BO);
6390b57cec5SDimitry Andric Op->setOperand(0, NewLHS);
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric if (NewRHS != OldRHS) {
6420b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(OldRHS, Opcode);
6430b57cec5SDimitry Andric if (BO && !NotRewritable.count(BO))
6440b57cec5SDimitry Andric NodesToRewrite.push_back(BO);
6450b57cec5SDimitry Andric Op->setOperand(1, NewRHS);
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
6480b57cec5SDimitry Andric
64906c3fb27SDimitry Andric ExpressionChangedStart = Op;
65006c3fb27SDimitry Andric if (!ExpressionChangedEnd)
65106c3fb27SDimitry Andric ExpressionChangedEnd = Op;
6520b57cec5SDimitry Andric MadeChange = true;
6530b57cec5SDimitry Andric ++NumChanged;
6540b57cec5SDimitry Andric
6550b57cec5SDimitry Andric break;
6560b57cec5SDimitry Andric }
6570b57cec5SDimitry Andric
6580b57cec5SDimitry Andric // Not the last operation. The left-hand side will be a sub-expression
6590b57cec5SDimitry Andric // while the right-hand side will be the current element of Ops.
6600b57cec5SDimitry Andric Value *NewRHS = Ops[i].Op;
6610b57cec5SDimitry Andric if (NewRHS != Op->getOperand(1)) {
6620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
6630b57cec5SDimitry Andric if (NewRHS == Op->getOperand(0)) {
6640b57cec5SDimitry Andric // The new right-hand side was already present as the left operand. If
6650b57cec5SDimitry Andric // we are lucky then swapping the operands will sort out both of them.
6660b57cec5SDimitry Andric Op->swapOperands();
6670b57cec5SDimitry Andric } else {
6680b57cec5SDimitry Andric // Overwrite with the new right-hand side.
6690b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(Op->getOperand(1), Opcode);
6700b57cec5SDimitry Andric if (BO && !NotRewritable.count(BO))
6710b57cec5SDimitry Andric NodesToRewrite.push_back(BO);
6720b57cec5SDimitry Andric Op->setOperand(1, NewRHS);
67306c3fb27SDimitry Andric ExpressionChangedStart = Op;
67406c3fb27SDimitry Andric if (!ExpressionChangedEnd)
67506c3fb27SDimitry Andric ExpressionChangedEnd = Op;
6760b57cec5SDimitry Andric }
6770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
6780b57cec5SDimitry Andric MadeChange = true;
6790b57cec5SDimitry Andric ++NumChanged;
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric
6820b57cec5SDimitry Andric // Now deal with the left-hand side. If this is already an operation node
6830b57cec5SDimitry Andric // from the original expression then just rewrite the rest of the expression
6840b57cec5SDimitry Andric // into it.
6850b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(Op->getOperand(0), Opcode);
6860b57cec5SDimitry Andric if (BO && !NotRewritable.count(BO)) {
6870b57cec5SDimitry Andric Op = BO;
6880b57cec5SDimitry Andric continue;
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric
6910b57cec5SDimitry Andric // Otherwise, grab a spare node from the original expression and use that as
6920b57cec5SDimitry Andric // the left-hand side. If there are no nodes left then the optimizers made
6930b57cec5SDimitry Andric // an expression with more nodes than the original! This usually means that
6940b57cec5SDimitry Andric // they did something stupid but it might mean that the problem was just too
6950b57cec5SDimitry Andric // hard (finding the mimimal number of multiplications needed to realize a
6960b57cec5SDimitry Andric // multiplication expression is NP-complete). Whatever the reason, smart or
6970b57cec5SDimitry Andric // stupid, create a new node if there are none left.
6980b57cec5SDimitry Andric BinaryOperator *NewOp;
6990b57cec5SDimitry Andric if (NodesToRewrite.empty()) {
700*0fca6ea1SDimitry Andric Constant *Poison = PoisonValue::get(I->getType());
701*0fca6ea1SDimitry Andric NewOp = BinaryOperator::Create(Instruction::BinaryOps(Opcode), Poison,
702*0fca6ea1SDimitry Andric Poison, "", I->getIterator());
703972a253aSDimitry Andric if (isa<FPMathOperator>(NewOp))
7040b57cec5SDimitry Andric NewOp->setFastMathFlags(I->getFastMathFlags());
7050b57cec5SDimitry Andric } else {
7060b57cec5SDimitry Andric NewOp = NodesToRewrite.pop_back_val();
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric
7090b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RA: " << *Op << '\n');
7100b57cec5SDimitry Andric Op->setOperand(0, NewOp);
7110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TO: " << *Op << '\n');
71206c3fb27SDimitry Andric ExpressionChangedStart = Op;
71306c3fb27SDimitry Andric if (!ExpressionChangedEnd)
71406c3fb27SDimitry Andric ExpressionChangedEnd = Op;
7150b57cec5SDimitry Andric MadeChange = true;
7160b57cec5SDimitry Andric ++NumChanged;
7170b57cec5SDimitry Andric Op = NewOp;
7180b57cec5SDimitry Andric }
7190b57cec5SDimitry Andric
7200b57cec5SDimitry Andric // If the expression changed non-trivially then clear out all subclass data
7210b57cec5SDimitry Andric // starting from the operator specified in ExpressionChanged, and compactify
7220b57cec5SDimitry Andric // the operators to just before the expression root to guarantee that the
7230b57cec5SDimitry Andric // expression tree is dominated by all of Ops.
72406c3fb27SDimitry Andric if (ExpressionChangedStart) {
72506c3fb27SDimitry Andric bool ClearFlags = true;
7260b57cec5SDimitry Andric do {
7275f757f3fSDimitry Andric // Preserve flags.
72806c3fb27SDimitry Andric if (ClearFlags) {
7290b57cec5SDimitry Andric if (isa<FPMathOperator>(I)) {
7300b57cec5SDimitry Andric FastMathFlags Flags = I->getFastMathFlags();
73106c3fb27SDimitry Andric ExpressionChangedStart->clearSubclassOptionalData();
73206c3fb27SDimitry Andric ExpressionChangedStart->setFastMathFlags(Flags);
7335f757f3fSDimitry Andric } else {
73406c3fb27SDimitry Andric ExpressionChangedStart->clearSubclassOptionalData();
735*0fca6ea1SDimitry Andric if (ExpressionChangedStart->getOpcode() == Instruction::Add ||
736*0fca6ea1SDimitry Andric (ExpressionChangedStart->getOpcode() == Instruction::Mul &&
737*0fca6ea1SDimitry Andric Flags.AllKnownNonZero)) {
738*0fca6ea1SDimitry Andric if (Flags.HasNUW)
7395f757f3fSDimitry Andric ExpressionChangedStart->setHasNoUnsignedWrap();
740*0fca6ea1SDimitry Andric if (Flags.HasNSW && (Flags.AllKnownNonNegative || Flags.HasNUW))
741*0fca6ea1SDimitry Andric ExpressionChangedStart->setHasNoSignedWrap();
742*0fca6ea1SDimitry Andric }
7435f757f3fSDimitry Andric }
74406c3fb27SDimitry Andric }
7450b57cec5SDimitry Andric
74606c3fb27SDimitry Andric if (ExpressionChangedStart == ExpressionChangedEnd)
74706c3fb27SDimitry Andric ClearFlags = false;
74806c3fb27SDimitry Andric if (ExpressionChangedStart == I)
7490b57cec5SDimitry Andric break;
7500b57cec5SDimitry Andric
7510b57cec5SDimitry Andric // Discard any debug info related to the expressions that has changed (we
75206c3fb27SDimitry Andric // can leave debug info related to the root and any operation that didn't
75306c3fb27SDimitry Andric // change, since the result of the expression tree should be the same
75406c3fb27SDimitry Andric // even after reassociation).
75506c3fb27SDimitry Andric if (ClearFlags)
75606c3fb27SDimitry Andric replaceDbgUsesWithUndef(ExpressionChangedStart);
7570b57cec5SDimitry Andric
75806c3fb27SDimitry Andric ExpressionChangedStart->moveBefore(I);
75906c3fb27SDimitry Andric ExpressionChangedStart =
76006c3fb27SDimitry Andric cast<BinaryOperator>(*ExpressionChangedStart->user_begin());
7610b57cec5SDimitry Andric } while (true);
76206c3fb27SDimitry Andric }
7630b57cec5SDimitry Andric
7640b57cec5SDimitry Andric // Throw away any left over nodes from the original expression.
765*0fca6ea1SDimitry Andric for (BinaryOperator *BO : NodesToRewrite)
766*0fca6ea1SDimitry Andric RedoInsts.insert(BO);
7670b57cec5SDimitry Andric }
7680b57cec5SDimitry Andric
7690b57cec5SDimitry Andric /// Insert instructions before the instruction pointed to by BI,
7700b57cec5SDimitry Andric /// that computes the negative version of the value specified. The negative
7710b57cec5SDimitry Andric /// version of the value is returned, and BI is left pointing at the instruction
7720b57cec5SDimitry Andric /// that should be processed next by the reassociation pass.
7730b57cec5SDimitry Andric /// Also add intermediate instructions to the redo list that are modified while
7740b57cec5SDimitry Andric /// pushing the negates through adds. These will be revisited to see if
7750b57cec5SDimitry Andric /// additional opportunities have been exposed.
NegateValue(Value * V,Instruction * BI,ReassociatePass::OrderedSet & ToRedo)7760b57cec5SDimitry Andric static Value *NegateValue(Value *V, Instruction *BI,
7770b57cec5SDimitry Andric ReassociatePass::OrderedSet &ToRedo) {
778bdd1243dSDimitry Andric if (auto *C = dyn_cast<Constant>(V)) {
779*0fca6ea1SDimitry Andric const DataLayout &DL = BI->getDataLayout();
780bdd1243dSDimitry Andric Constant *Res = C->getType()->isFPOrFPVectorTy()
781bdd1243dSDimitry Andric ? ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)
782bdd1243dSDimitry Andric : ConstantExpr::getNeg(C);
783bdd1243dSDimitry Andric if (Res)
784bdd1243dSDimitry Andric return Res;
785bdd1243dSDimitry Andric }
7860b57cec5SDimitry Andric
7870b57cec5SDimitry Andric // We are trying to expose opportunity for reassociation. One of the things
7880b57cec5SDimitry Andric // that we want to do to achieve this is to push a negation as deep into an
7890b57cec5SDimitry Andric // expression chain as possible, to expose the add instructions. In practice,
7900b57cec5SDimitry Andric // this means that we turn this:
7910b57cec5SDimitry Andric // X = -(A+12+C+D) into X = -A + -12 + -C + -D = -12 + -A + -C + -D
7920b57cec5SDimitry Andric // so that later, a: Y = 12+X could get reassociated with the -12 to eliminate
7930b57cec5SDimitry Andric // the constants. We assume that instcombine will clean up the mess later if
7940b57cec5SDimitry Andric // we introduce tons of unnecessary negation instructions.
7950b57cec5SDimitry Andric //
7960b57cec5SDimitry Andric if (BinaryOperator *I =
7970b57cec5SDimitry Andric isReassociableOp(V, Instruction::Add, Instruction::FAdd)) {
7980b57cec5SDimitry Andric // Push the negates through the add.
7990b57cec5SDimitry Andric I->setOperand(0, NegateValue(I->getOperand(0), BI, ToRedo));
8000b57cec5SDimitry Andric I->setOperand(1, NegateValue(I->getOperand(1), BI, ToRedo));
8010b57cec5SDimitry Andric if (I->getOpcode() == Instruction::Add) {
8020b57cec5SDimitry Andric I->setHasNoUnsignedWrap(false);
8030b57cec5SDimitry Andric I->setHasNoSignedWrap(false);
8040b57cec5SDimitry Andric }
8050b57cec5SDimitry Andric
8060b57cec5SDimitry Andric // We must move the add instruction here, because the neg instructions do
8070b57cec5SDimitry Andric // not dominate the old add instruction in general. By moving it, we are
8080b57cec5SDimitry Andric // assured that the neg instructions we just inserted dominate the
8090b57cec5SDimitry Andric // instruction we are about to insert after them.
8100b57cec5SDimitry Andric //
8110b57cec5SDimitry Andric I->moveBefore(BI);
8120b57cec5SDimitry Andric I->setName(I->getName()+".neg");
8130b57cec5SDimitry Andric
8140b57cec5SDimitry Andric // Add the intermediate negates to the redo list as processing them later
8150b57cec5SDimitry Andric // could expose more reassociating opportunities.
8160b57cec5SDimitry Andric ToRedo.insert(I);
8170b57cec5SDimitry Andric return I;
8180b57cec5SDimitry Andric }
8190b57cec5SDimitry Andric
8200b57cec5SDimitry Andric // Okay, we need to materialize a negated version of V with an instruction.
8210b57cec5SDimitry Andric // Scan the use lists of V to see if we have one already.
8220b57cec5SDimitry Andric for (User *U : V->users()) {
8230b57cec5SDimitry Andric if (!match(U, m_Neg(m_Value())) && !match(U, m_FNeg(m_Value())))
8240b57cec5SDimitry Andric continue;
8250b57cec5SDimitry Andric
8260b57cec5SDimitry Andric // We found one! Now we have to make sure that the definition dominates
8270b57cec5SDimitry Andric // this use. We do this by moving it to the entry block (if it is a
8280b57cec5SDimitry Andric // non-instruction value) or right after the definition. These negates will
8290b57cec5SDimitry Andric // be zapped by reassociate later, so we don't need much finesse here.
830bdd1243dSDimitry Andric Instruction *TheNeg = dyn_cast<Instruction>(U);
8310b57cec5SDimitry Andric
832bdd1243dSDimitry Andric // We can't safely propagate a vector zero constant with poison/undef lanes.
833bdd1243dSDimitry Andric Constant *C;
834bdd1243dSDimitry Andric if (match(TheNeg, m_BinOp(m_Constant(C), m_Value())) &&
835bdd1243dSDimitry Andric C->containsUndefOrPoisonElement())
8360b57cec5SDimitry Andric continue;
8370b57cec5SDimitry Andric
838bdd1243dSDimitry Andric // Verify that the negate is in this function, V might be a constant expr.
839bdd1243dSDimitry Andric if (!TheNeg ||
840bdd1243dSDimitry Andric TheNeg->getParent()->getParent() != BI->getParent()->getParent())
841bdd1243dSDimitry Andric continue;
8420b57cec5SDimitry Andric
8435f757f3fSDimitry Andric BasicBlock::iterator InsertPt;
8440b57cec5SDimitry Andric if (Instruction *InstInput = dyn_cast<Instruction>(V)) {
8455f757f3fSDimitry Andric auto InsertPtOpt = InstInput->getInsertionPointAfterDef();
8465f757f3fSDimitry Andric if (!InsertPtOpt)
847bdd1243dSDimitry Andric continue;
8485f757f3fSDimitry Andric InsertPt = *InsertPtOpt;
8490b57cec5SDimitry Andric } else {
8505f757f3fSDimitry Andric InsertPt = TheNeg->getFunction()
8515f757f3fSDimitry Andric ->getEntryBlock()
8525f757f3fSDimitry Andric .getFirstNonPHIOrDbg()
8535f757f3fSDimitry Andric ->getIterator();
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric
856*0fca6ea1SDimitry Andric // Check that if TheNeg is moved out of its parent block, we drop its
857*0fca6ea1SDimitry Andric // debug location to avoid extra coverage.
858*0fca6ea1SDimitry Andric // See test dropping_debugloc_the_neg.ll for a detailed example.
859*0fca6ea1SDimitry Andric if (TheNeg->getParent() != InsertPt->getParent())
860*0fca6ea1SDimitry Andric TheNeg->dropLocation();
8615f757f3fSDimitry Andric TheNeg->moveBefore(*InsertPt->getParent(), InsertPt);
862*0fca6ea1SDimitry Andric
8630b57cec5SDimitry Andric if (TheNeg->getOpcode() == Instruction::Sub) {
8640b57cec5SDimitry Andric TheNeg->setHasNoUnsignedWrap(false);
8650b57cec5SDimitry Andric TheNeg->setHasNoSignedWrap(false);
8660b57cec5SDimitry Andric } else {
8670b57cec5SDimitry Andric TheNeg->andIRFlags(BI);
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric ToRedo.insert(TheNeg);
8700b57cec5SDimitry Andric return TheNeg;
8710b57cec5SDimitry Andric }
8720b57cec5SDimitry Andric
8730b57cec5SDimitry Andric // Insert a 'neg' instruction that subtracts the value from zero to get the
8740b57cec5SDimitry Andric // negation.
875*0fca6ea1SDimitry Andric Instruction *NewNeg =
876*0fca6ea1SDimitry Andric CreateNeg(V, V->getName() + ".neg", BI->getIterator(), BI);
8770b57cec5SDimitry Andric ToRedo.insert(NewNeg);
8780b57cec5SDimitry Andric return NewNeg;
8790b57cec5SDimitry Andric }
8800b57cec5SDimitry Andric
881e8d8bef9SDimitry Andric // See if this `or` looks like an load widening reduction, i.e. that it
882e8d8bef9SDimitry Andric // consists of an `or`/`shl`/`zext`/`load` nodes only. Note that we don't
883e8d8bef9SDimitry Andric // ensure that the pattern is *really* a load widening reduction,
884e8d8bef9SDimitry Andric // we do not ensure that it can really be replaced with a widened load,
885e8d8bef9SDimitry Andric // only that it mostly looks like one.
isLoadCombineCandidate(Instruction * Or)886e8d8bef9SDimitry Andric static bool isLoadCombineCandidate(Instruction *Or) {
887e8d8bef9SDimitry Andric SmallVector<Instruction *, 8> Worklist;
888e8d8bef9SDimitry Andric SmallSet<Instruction *, 8> Visited;
889e8d8bef9SDimitry Andric
890e8d8bef9SDimitry Andric auto Enqueue = [&](Value *V) {
891e8d8bef9SDimitry Andric auto *I = dyn_cast<Instruction>(V);
892e8d8bef9SDimitry Andric // Each node of an `or` reduction must be an instruction,
893e8d8bef9SDimitry Andric if (!I)
894e8d8bef9SDimitry Andric return false; // Node is certainly not part of an `or` load reduction.
895e8d8bef9SDimitry Andric // Only process instructions we have never processed before.
896e8d8bef9SDimitry Andric if (Visited.insert(I).second)
897e8d8bef9SDimitry Andric Worklist.emplace_back(I);
898e8d8bef9SDimitry Andric return true; // Will need to look at parent nodes.
899e8d8bef9SDimitry Andric };
900e8d8bef9SDimitry Andric
901e8d8bef9SDimitry Andric if (!Enqueue(Or))
902e8d8bef9SDimitry Andric return false; // Not an `or` reduction pattern.
903e8d8bef9SDimitry Andric
904e8d8bef9SDimitry Andric while (!Worklist.empty()) {
905e8d8bef9SDimitry Andric auto *I = Worklist.pop_back_val();
906e8d8bef9SDimitry Andric
907e8d8bef9SDimitry Andric // Okay, which instruction is this node?
908e8d8bef9SDimitry Andric switch (I->getOpcode()) {
909e8d8bef9SDimitry Andric case Instruction::Or:
910e8d8bef9SDimitry Andric // Got an `or` node. That's fine, just recurse into it's operands.
911e8d8bef9SDimitry Andric for (Value *Op : I->operands())
912e8d8bef9SDimitry Andric if (!Enqueue(Op))
913e8d8bef9SDimitry Andric return false; // Not an `or` reduction pattern.
914e8d8bef9SDimitry Andric continue;
915e8d8bef9SDimitry Andric
916e8d8bef9SDimitry Andric case Instruction::Shl:
917e8d8bef9SDimitry Andric case Instruction::ZExt:
918e8d8bef9SDimitry Andric // `shl`/`zext` nodes are fine, just recurse into their base operand.
919e8d8bef9SDimitry Andric if (!Enqueue(I->getOperand(0)))
920e8d8bef9SDimitry Andric return false; // Not an `or` reduction pattern.
921e8d8bef9SDimitry Andric continue;
922e8d8bef9SDimitry Andric
923e8d8bef9SDimitry Andric case Instruction::Load:
924e8d8bef9SDimitry Andric // Perfect, `load` node means we've reached an edge of the graph.
925e8d8bef9SDimitry Andric continue;
926e8d8bef9SDimitry Andric
927e8d8bef9SDimitry Andric default: // Unknown node.
928e8d8bef9SDimitry Andric return false; // Not an `or` reduction pattern.
929e8d8bef9SDimitry Andric }
930e8d8bef9SDimitry Andric }
931e8d8bef9SDimitry Andric
932e8d8bef9SDimitry Andric return true;
933e8d8bef9SDimitry Andric }
934e8d8bef9SDimitry Andric
935e8d8bef9SDimitry Andric /// Return true if it may be profitable to convert this (X|Y) into (X+Y).
shouldConvertOrWithNoCommonBitsToAdd(Instruction * Or)936fe6060f1SDimitry Andric static bool shouldConvertOrWithNoCommonBitsToAdd(Instruction *Or) {
937e8d8bef9SDimitry Andric // Don't bother to convert this up unless either the LHS is an associable add
938e8d8bef9SDimitry Andric // or subtract or mul or if this is only used by one of the above.
939e8d8bef9SDimitry Andric // This is only a compile-time improvement, it is not needed for correctness!
940e8d8bef9SDimitry Andric auto isInteresting = [](Value *V) {
941fe6060f1SDimitry Andric for (auto Op : {Instruction::Add, Instruction::Sub, Instruction::Mul,
942fe6060f1SDimitry Andric Instruction::Shl})
943e8d8bef9SDimitry Andric if (isReassociableOp(V, Op))
944e8d8bef9SDimitry Andric return true;
945e8d8bef9SDimitry Andric return false;
946e8d8bef9SDimitry Andric };
947e8d8bef9SDimitry Andric
948e8d8bef9SDimitry Andric if (any_of(Or->operands(), isInteresting))
949e8d8bef9SDimitry Andric return true;
950e8d8bef9SDimitry Andric
951e8d8bef9SDimitry Andric Value *VB = Or->user_back();
952e8d8bef9SDimitry Andric if (Or->hasOneUse() && isInteresting(VB))
953e8d8bef9SDimitry Andric return true;
954e8d8bef9SDimitry Andric
955e8d8bef9SDimitry Andric return false;
956e8d8bef9SDimitry Andric }
957e8d8bef9SDimitry Andric
958e8d8bef9SDimitry Andric /// If we have (X|Y), and iff X and Y have no common bits set,
959e8d8bef9SDimitry Andric /// transform this into (X+Y) to allow arithmetics reassociation.
convertOrWithNoCommonBitsToAdd(Instruction * Or)960fe6060f1SDimitry Andric static BinaryOperator *convertOrWithNoCommonBitsToAdd(Instruction *Or) {
961e8d8bef9SDimitry Andric // Convert an or into an add.
962*0fca6ea1SDimitry Andric BinaryOperator *New = CreateAdd(Or->getOperand(0), Or->getOperand(1), "",
963*0fca6ea1SDimitry Andric Or->getIterator(), Or);
964e8d8bef9SDimitry Andric New->setHasNoSignedWrap();
965e8d8bef9SDimitry Andric New->setHasNoUnsignedWrap();
966e8d8bef9SDimitry Andric New->takeName(Or);
967e8d8bef9SDimitry Andric
968e8d8bef9SDimitry Andric // Everyone now refers to the add instruction.
969e8d8bef9SDimitry Andric Or->replaceAllUsesWith(New);
970e8d8bef9SDimitry Andric New->setDebugLoc(Or->getDebugLoc());
971e8d8bef9SDimitry Andric
972e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Converted or into an add: " << *New << '\n');
973e8d8bef9SDimitry Andric return New;
974e8d8bef9SDimitry Andric }
975e8d8bef9SDimitry Andric
9760b57cec5SDimitry Andric /// Return true if we should break up this subtract of X-Y into (X + -Y).
ShouldBreakUpSubtract(Instruction * Sub)9770b57cec5SDimitry Andric static bool ShouldBreakUpSubtract(Instruction *Sub) {
9780b57cec5SDimitry Andric // If this is a negation, we can't split it up!
9790b57cec5SDimitry Andric if (match(Sub, m_Neg(m_Value())) || match(Sub, m_FNeg(m_Value())))
9800b57cec5SDimitry Andric return false;
9810b57cec5SDimitry Andric
9820b57cec5SDimitry Andric // Don't breakup X - undef.
9830b57cec5SDimitry Andric if (isa<UndefValue>(Sub->getOperand(1)))
9840b57cec5SDimitry Andric return false;
9850b57cec5SDimitry Andric
9860b57cec5SDimitry Andric // Don't bother to break this up unless either the LHS is an associable add or
9870b57cec5SDimitry Andric // subtract or if this is only used by one.
9880b57cec5SDimitry Andric Value *V0 = Sub->getOperand(0);
9890b57cec5SDimitry Andric if (isReassociableOp(V0, Instruction::Add, Instruction::FAdd) ||
9900b57cec5SDimitry Andric isReassociableOp(V0, Instruction::Sub, Instruction::FSub))
9910b57cec5SDimitry Andric return true;
9920b57cec5SDimitry Andric Value *V1 = Sub->getOperand(1);
9930b57cec5SDimitry Andric if (isReassociableOp(V1, Instruction::Add, Instruction::FAdd) ||
9940b57cec5SDimitry Andric isReassociableOp(V1, Instruction::Sub, Instruction::FSub))
9950b57cec5SDimitry Andric return true;
9960b57cec5SDimitry Andric Value *VB = Sub->user_back();
9970b57cec5SDimitry Andric if (Sub->hasOneUse() &&
9980b57cec5SDimitry Andric (isReassociableOp(VB, Instruction::Add, Instruction::FAdd) ||
9990b57cec5SDimitry Andric isReassociableOp(VB, Instruction::Sub, Instruction::FSub)))
10000b57cec5SDimitry Andric return true;
10010b57cec5SDimitry Andric
10020b57cec5SDimitry Andric return false;
10030b57cec5SDimitry Andric }
10040b57cec5SDimitry Andric
10050b57cec5SDimitry Andric /// If we have (X-Y), and if either X is an add, or if this is only used by an
10060b57cec5SDimitry Andric /// add, transform this into (X+(0-Y)) to promote better reassociation.
BreakUpSubtract(Instruction * Sub,ReassociatePass::OrderedSet & ToRedo)10070b57cec5SDimitry Andric static BinaryOperator *BreakUpSubtract(Instruction *Sub,
10080b57cec5SDimitry Andric ReassociatePass::OrderedSet &ToRedo) {
10090b57cec5SDimitry Andric // Convert a subtract into an add and a neg instruction. This allows sub
10100b57cec5SDimitry Andric // instructions to be commuted with other add instructions.
10110b57cec5SDimitry Andric //
10120b57cec5SDimitry Andric // Calculate the negative value of Operand 1 of the sub instruction,
10130b57cec5SDimitry Andric // and set it as the RHS of the add instruction we just made.
10140b57cec5SDimitry Andric Value *NegVal = NegateValue(Sub->getOperand(1), Sub, ToRedo);
1015*0fca6ea1SDimitry Andric BinaryOperator *New =
1016*0fca6ea1SDimitry Andric CreateAdd(Sub->getOperand(0), NegVal, "", Sub->getIterator(), Sub);
10170b57cec5SDimitry Andric Sub->setOperand(0, Constant::getNullValue(Sub->getType())); // Drop use of op.
10180b57cec5SDimitry Andric Sub->setOperand(1, Constant::getNullValue(Sub->getType())); // Drop use of op.
10190b57cec5SDimitry Andric New->takeName(Sub);
10200b57cec5SDimitry Andric
10210b57cec5SDimitry Andric // Everyone now refers to the add instruction.
10220b57cec5SDimitry Andric Sub->replaceAllUsesWith(New);
10230b57cec5SDimitry Andric New->setDebugLoc(Sub->getDebugLoc());
10240b57cec5SDimitry Andric
10250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Negated: " << *New << '\n');
10260b57cec5SDimitry Andric return New;
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric
10290b57cec5SDimitry Andric /// If this is a shift of a reassociable multiply or is used by one, change
10300b57cec5SDimitry Andric /// this into a multiply by a constant to assist with further reassociation.
ConvertShiftToMul(Instruction * Shl)10310b57cec5SDimitry Andric static BinaryOperator *ConvertShiftToMul(Instruction *Shl) {
10320b57cec5SDimitry Andric Constant *MulCst = ConstantInt::get(Shl->getType(), 1);
10335ffd83dbSDimitry Andric auto *SA = cast<ConstantInt>(Shl->getOperand(1));
1034*0fca6ea1SDimitry Andric MulCst = ConstantFoldBinaryInstruction(Instruction::Shl, MulCst, SA);
1035*0fca6ea1SDimitry Andric assert(MulCst && "Constant folding of immediate constants failed");
10360b57cec5SDimitry Andric
1037*0fca6ea1SDimitry Andric BinaryOperator *Mul = BinaryOperator::CreateMul(Shl->getOperand(0), MulCst,
1038*0fca6ea1SDimitry Andric "", Shl->getIterator());
103981ad6265SDimitry Andric Shl->setOperand(0, PoisonValue::get(Shl->getType())); // Drop use of op.
10400b57cec5SDimitry Andric Mul->takeName(Shl);
10410b57cec5SDimitry Andric
10420b57cec5SDimitry Andric // Everyone now refers to the mul instruction.
10430b57cec5SDimitry Andric Shl->replaceAllUsesWith(Mul);
10440b57cec5SDimitry Andric Mul->setDebugLoc(Shl->getDebugLoc());
10450b57cec5SDimitry Andric
10460b57cec5SDimitry Andric // We can safely preserve the nuw flag in all cases. It's also safe to turn a
10470b57cec5SDimitry Andric // nuw nsw shl into a nuw nsw mul. However, nsw in isolation requires special
10485ffd83dbSDimitry Andric // handling. It can be preserved as long as we're not left shifting by
10495ffd83dbSDimitry Andric // bitwidth - 1.
10500b57cec5SDimitry Andric bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
10510b57cec5SDimitry Andric bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
10525ffd83dbSDimitry Andric unsigned BitWidth = Shl->getType()->getIntegerBitWidth();
10535ffd83dbSDimitry Andric if (NSW && (NUW || SA->getValue().ult(BitWidth - 1)))
10540b57cec5SDimitry Andric Mul->setHasNoSignedWrap(true);
10550b57cec5SDimitry Andric Mul->setHasNoUnsignedWrap(NUW);
10560b57cec5SDimitry Andric return Mul;
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric
10590b57cec5SDimitry Andric /// Scan backwards and forwards among values with the same rank as element i
10600b57cec5SDimitry Andric /// to see if X exists. If X does not exist, return i. This is useful when
10610b57cec5SDimitry Andric /// scanning for 'x' when we see '-x' because they both get the same rank.
FindInOperandList(const SmallVectorImpl<ValueEntry> & Ops,unsigned i,Value * X)10620b57cec5SDimitry Andric static unsigned FindInOperandList(const SmallVectorImpl<ValueEntry> &Ops,
10630b57cec5SDimitry Andric unsigned i, Value *X) {
10640b57cec5SDimitry Andric unsigned XRank = Ops[i].Rank;
10650b57cec5SDimitry Andric unsigned e = Ops.size();
10660b57cec5SDimitry Andric for (unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
10670b57cec5SDimitry Andric if (Ops[j].Op == X)
10680b57cec5SDimitry Andric return j;
10690b57cec5SDimitry Andric if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
10700b57cec5SDimitry Andric if (Instruction *I2 = dyn_cast<Instruction>(X))
10710b57cec5SDimitry Andric if (I1->isIdenticalTo(I2))
10720b57cec5SDimitry Andric return j;
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric // Scan backwards.
10750b57cec5SDimitry Andric for (unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
10760b57cec5SDimitry Andric if (Ops[j].Op == X)
10770b57cec5SDimitry Andric return j;
10780b57cec5SDimitry Andric if (Instruction *I1 = dyn_cast<Instruction>(Ops[j].Op))
10790b57cec5SDimitry Andric if (Instruction *I2 = dyn_cast<Instruction>(X))
10800b57cec5SDimitry Andric if (I1->isIdenticalTo(I2))
10810b57cec5SDimitry Andric return j;
10820b57cec5SDimitry Andric }
10830b57cec5SDimitry Andric return i;
10840b57cec5SDimitry Andric }
10850b57cec5SDimitry Andric
10860b57cec5SDimitry Andric /// Emit a tree of add instructions, summing Ops together
10870b57cec5SDimitry Andric /// and returning the result. Insert the tree before I.
EmitAddTreeOfValues(BasicBlock::iterator It,SmallVectorImpl<WeakTrackingVH> & Ops)1088*0fca6ea1SDimitry Andric static Value *EmitAddTreeOfValues(BasicBlock::iterator It,
10890b57cec5SDimitry Andric SmallVectorImpl<WeakTrackingVH> &Ops) {
10900b57cec5SDimitry Andric if (Ops.size() == 1) return Ops.back();
10910b57cec5SDimitry Andric
1092e8d8bef9SDimitry Andric Value *V1 = Ops.pop_back_val();
1093*0fca6ea1SDimitry Andric Value *V2 = EmitAddTreeOfValues(It, Ops);
1094*0fca6ea1SDimitry Andric return CreateAdd(V2, V1, "reass.add", It, &*It);
10950b57cec5SDimitry Andric }
10960b57cec5SDimitry Andric
10970b57cec5SDimitry Andric /// If V is an expression tree that is a multiplication sequence,
10980b57cec5SDimitry Andric /// and if this sequence contains a multiply by Factor,
10990b57cec5SDimitry Andric /// remove Factor from the tree and return the new tree.
RemoveFactorFromExpression(Value * V,Value * Factor)11000b57cec5SDimitry Andric Value *ReassociatePass::RemoveFactorFromExpression(Value *V, Value *Factor) {
11010b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
11020b57cec5SDimitry Andric if (!BO)
11030b57cec5SDimitry Andric return nullptr;
11040b57cec5SDimitry Andric
11050b57cec5SDimitry Andric SmallVector<RepeatedValue, 8> Tree;
1106*0fca6ea1SDimitry Andric OverflowTracking Flags;
1107*0fca6ea1SDimitry Andric MadeChange |= LinearizeExprTree(BO, Tree, RedoInsts, Flags);
11080b57cec5SDimitry Andric SmallVector<ValueEntry, 8> Factors;
11090b57cec5SDimitry Andric Factors.reserve(Tree.size());
11100b57cec5SDimitry Andric for (unsigned i = 0, e = Tree.size(); i != e; ++i) {
11110b57cec5SDimitry Andric RepeatedValue E = Tree[i];
1112*0fca6ea1SDimitry Andric Factors.append(E.second, ValueEntry(getRank(E.first), E.first));
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric
11150b57cec5SDimitry Andric bool FoundFactor = false;
11160b57cec5SDimitry Andric bool NeedsNegate = false;
11170b57cec5SDimitry Andric for (unsigned i = 0, e = Factors.size(); i != e; ++i) {
11180b57cec5SDimitry Andric if (Factors[i].Op == Factor) {
11190b57cec5SDimitry Andric FoundFactor = true;
11200b57cec5SDimitry Andric Factors.erase(Factors.begin()+i);
11210b57cec5SDimitry Andric break;
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric
11240b57cec5SDimitry Andric // If this is a negative version of this factor, remove it.
11250b57cec5SDimitry Andric if (ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
11260b57cec5SDimitry Andric if (ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].Op))
11270b57cec5SDimitry Andric if (FC1->getValue() == -FC2->getValue()) {
11280b57cec5SDimitry Andric FoundFactor = NeedsNegate = true;
11290b57cec5SDimitry Andric Factors.erase(Factors.begin()+i);
11300b57cec5SDimitry Andric break;
11310b57cec5SDimitry Andric }
11320b57cec5SDimitry Andric } else if (ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
11330b57cec5SDimitry Andric if (ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].Op)) {
11340b57cec5SDimitry Andric const APFloat &F1 = FC1->getValueAPF();
11350b57cec5SDimitry Andric APFloat F2(FC2->getValueAPF());
11360b57cec5SDimitry Andric F2.changeSign();
11375ffd83dbSDimitry Andric if (F1 == F2) {
11380b57cec5SDimitry Andric FoundFactor = NeedsNegate = true;
11390b57cec5SDimitry Andric Factors.erase(Factors.begin() + i);
11400b57cec5SDimitry Andric break;
11410b57cec5SDimitry Andric }
11420b57cec5SDimitry Andric }
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric
11460b57cec5SDimitry Andric if (!FoundFactor) {
11470b57cec5SDimitry Andric // Make sure to restore the operands to the expression tree.
1148*0fca6ea1SDimitry Andric RewriteExprTree(BO, Factors, Flags);
11490b57cec5SDimitry Andric return nullptr;
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric
11520b57cec5SDimitry Andric BasicBlock::iterator InsertPt = ++BO->getIterator();
11530b57cec5SDimitry Andric
11540b57cec5SDimitry Andric // If this was just a single multiply, remove the multiply and return the only
11550b57cec5SDimitry Andric // remaining operand.
11560b57cec5SDimitry Andric if (Factors.size() == 1) {
11570b57cec5SDimitry Andric RedoInsts.insert(BO);
11580b57cec5SDimitry Andric V = Factors[0].Op;
11590b57cec5SDimitry Andric } else {
1160*0fca6ea1SDimitry Andric RewriteExprTree(BO, Factors, Flags);
11610b57cec5SDimitry Andric V = BO;
11620b57cec5SDimitry Andric }
11630b57cec5SDimitry Andric
11640b57cec5SDimitry Andric if (NeedsNegate)
1165*0fca6ea1SDimitry Andric V = CreateNeg(V, "neg", InsertPt, BO);
11660b57cec5SDimitry Andric
11670b57cec5SDimitry Andric return V;
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric
11700b57cec5SDimitry Andric /// If V is a single-use multiply, recursively add its operands as factors,
11710b57cec5SDimitry Andric /// otherwise add V to the list of factors.
11720b57cec5SDimitry Andric ///
11730b57cec5SDimitry Andric /// Ops is the top-level list of add operands we're trying to factor.
FindSingleUseMultiplyFactors(Value * V,SmallVectorImpl<Value * > & Factors)11740b57cec5SDimitry Andric static void FindSingleUseMultiplyFactors(Value *V,
11750b57cec5SDimitry Andric SmallVectorImpl<Value*> &Factors) {
11760b57cec5SDimitry Andric BinaryOperator *BO = isReassociableOp(V, Instruction::Mul, Instruction::FMul);
11770b57cec5SDimitry Andric if (!BO) {
11780b57cec5SDimitry Andric Factors.push_back(V);
11790b57cec5SDimitry Andric return;
11800b57cec5SDimitry Andric }
11810b57cec5SDimitry Andric
11820b57cec5SDimitry Andric // Otherwise, add the LHS and RHS to the list of factors.
11830b57cec5SDimitry Andric FindSingleUseMultiplyFactors(BO->getOperand(1), Factors);
11840b57cec5SDimitry Andric FindSingleUseMultiplyFactors(BO->getOperand(0), Factors);
11850b57cec5SDimitry Andric }
11860b57cec5SDimitry Andric
11870b57cec5SDimitry Andric /// Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
11880b57cec5SDimitry Andric /// This optimizes based on identities. If it can be reduced to a single Value,
11890b57cec5SDimitry Andric /// it is returned, otherwise the Ops list is mutated as necessary.
OptimizeAndOrXor(unsigned Opcode,SmallVectorImpl<ValueEntry> & Ops)11900b57cec5SDimitry Andric static Value *OptimizeAndOrXor(unsigned Opcode,
11910b57cec5SDimitry Andric SmallVectorImpl<ValueEntry> &Ops) {
11920b57cec5SDimitry Andric // Scan the operand lists looking for X and ~X pairs, along with X,X pairs.
11930b57cec5SDimitry Andric // If we find any, we can simplify the expression. X&~X == 0, X|~X == -1.
11940b57cec5SDimitry Andric for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
11950b57cec5SDimitry Andric // First, check for X and ~X in the operand list.
11960b57cec5SDimitry Andric assert(i < Ops.size());
11970b57cec5SDimitry Andric Value *X;
11980b57cec5SDimitry Andric if (match(Ops[i].Op, m_Not(m_Value(X)))) { // Cannot occur for ^.
11990b57cec5SDimitry Andric unsigned FoundX = FindInOperandList(Ops, i, X);
12000b57cec5SDimitry Andric if (FoundX != i) {
12010b57cec5SDimitry Andric if (Opcode == Instruction::And) // ...&X&~X = 0
12020b57cec5SDimitry Andric return Constant::getNullValue(X->getType());
12030b57cec5SDimitry Andric
12040b57cec5SDimitry Andric if (Opcode == Instruction::Or) // ...|X|~X = -1
12050b57cec5SDimitry Andric return Constant::getAllOnesValue(X->getType());
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric
12090b57cec5SDimitry Andric // Next, check for duplicate pairs of values, which we assume are next to
12100b57cec5SDimitry Andric // each other, due to our sorting criteria.
12110b57cec5SDimitry Andric assert(i < Ops.size());
12120b57cec5SDimitry Andric if (i+1 != Ops.size() && Ops[i+1].Op == Ops[i].Op) {
12130b57cec5SDimitry Andric if (Opcode == Instruction::And || Opcode == Instruction::Or) {
12140b57cec5SDimitry Andric // Drop duplicate values for And and Or.
12150b57cec5SDimitry Andric Ops.erase(Ops.begin()+i);
12160b57cec5SDimitry Andric --i; --e;
12170b57cec5SDimitry Andric ++NumAnnihil;
12180b57cec5SDimitry Andric continue;
12190b57cec5SDimitry Andric }
12200b57cec5SDimitry Andric
12210b57cec5SDimitry Andric // Drop pairs of values for Xor.
12220b57cec5SDimitry Andric assert(Opcode == Instruction::Xor);
12230b57cec5SDimitry Andric if (e == 2)
12240b57cec5SDimitry Andric return Constant::getNullValue(Ops[0].Op->getType());
12250b57cec5SDimitry Andric
12260b57cec5SDimitry Andric // Y ^ X^X -> Y
12270b57cec5SDimitry Andric Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
12280b57cec5SDimitry Andric i -= 1; e -= 2;
12290b57cec5SDimitry Andric ++NumAnnihil;
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric }
12320b57cec5SDimitry Andric return nullptr;
12330b57cec5SDimitry Andric }
12340b57cec5SDimitry Andric
12350b57cec5SDimitry Andric /// Helper function of CombineXorOpnd(). It creates a bitwise-and
12360b57cec5SDimitry Andric /// instruction with the given two operands, and return the resulting
12370b57cec5SDimitry Andric /// instruction. There are two special cases: 1) if the constant operand is 0,
12380b57cec5SDimitry Andric /// it will return NULL. 2) if the constant is ~0, the symbolic operand will
12390b57cec5SDimitry Andric /// be returned.
createAndInstr(BasicBlock::iterator InsertBefore,Value * Opnd,const APInt & ConstOpnd)1240*0fca6ea1SDimitry Andric static Value *createAndInstr(BasicBlock::iterator InsertBefore, Value *Opnd,
12410b57cec5SDimitry Andric const APInt &ConstOpnd) {
1242349cc55cSDimitry Andric if (ConstOpnd.isZero())
12430b57cec5SDimitry Andric return nullptr;
12440b57cec5SDimitry Andric
1245349cc55cSDimitry Andric if (ConstOpnd.isAllOnes())
12460b57cec5SDimitry Andric return Opnd;
12470b57cec5SDimitry Andric
12480b57cec5SDimitry Andric Instruction *I = BinaryOperator::CreateAnd(
12490b57cec5SDimitry Andric Opnd, ConstantInt::get(Opnd->getType(), ConstOpnd), "and.ra",
12500b57cec5SDimitry Andric InsertBefore);
12510b57cec5SDimitry Andric I->setDebugLoc(InsertBefore->getDebugLoc());
12520b57cec5SDimitry Andric return I;
12530b57cec5SDimitry Andric }
12540b57cec5SDimitry Andric
12550b57cec5SDimitry Andric // Helper function of OptimizeXor(). It tries to simplify "Opnd1 ^ ConstOpnd"
12560b57cec5SDimitry Andric // into "R ^ C", where C would be 0, and R is a symbolic value.
12570b57cec5SDimitry Andric //
12580b57cec5SDimitry Andric // If it was successful, true is returned, and the "R" and "C" is returned
12590b57cec5SDimitry Andric // via "Res" and "ConstOpnd", respectively; otherwise, false is returned,
12600b57cec5SDimitry Andric // and both "Res" and "ConstOpnd" remain unchanged.
CombineXorOpnd(BasicBlock::iterator It,XorOpnd * Opnd1,APInt & ConstOpnd,Value * & Res)1261*0fca6ea1SDimitry Andric bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1,
12620b57cec5SDimitry Andric APInt &ConstOpnd, Value *&Res) {
12630b57cec5SDimitry Andric // Xor-Rule 1: (x | c1) ^ c2 = (x | c1) ^ (c1 ^ c1) ^ c2
12640b57cec5SDimitry Andric // = ((x | c1) ^ c1) ^ (c1 ^ c2)
12650b57cec5SDimitry Andric // = (x & ~c1) ^ (c1 ^ c2)
12660b57cec5SDimitry Andric // It is useful only when c1 == c2.
1267349cc55cSDimitry Andric if (!Opnd1->isOrExpr() || Opnd1->getConstPart().isZero())
12680b57cec5SDimitry Andric return false;
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric if (!Opnd1->getValue()->hasOneUse())
12710b57cec5SDimitry Andric return false;
12720b57cec5SDimitry Andric
12730b57cec5SDimitry Andric const APInt &C1 = Opnd1->getConstPart();
12740b57cec5SDimitry Andric if (C1 != ConstOpnd)
12750b57cec5SDimitry Andric return false;
12760b57cec5SDimitry Andric
12770b57cec5SDimitry Andric Value *X = Opnd1->getSymbolicPart();
1278*0fca6ea1SDimitry Andric Res = createAndInstr(It, X, ~C1);
12790b57cec5SDimitry Andric // ConstOpnd was C2, now C1 ^ C2.
12800b57cec5SDimitry Andric ConstOpnd ^= C1;
12810b57cec5SDimitry Andric
12820b57cec5SDimitry Andric if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
12830b57cec5SDimitry Andric RedoInsts.insert(T);
12840b57cec5SDimitry Andric return true;
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric
12870b57cec5SDimitry Andric // Helper function of OptimizeXor(). It tries to simplify
12880b57cec5SDimitry Andric // "Opnd1 ^ Opnd2 ^ ConstOpnd" into "R ^ C", where C would be 0, and R is a
12890b57cec5SDimitry Andric // symbolic value.
12900b57cec5SDimitry Andric //
12910b57cec5SDimitry Andric // If it was successful, true is returned, and the "R" and "C" is returned
12920b57cec5SDimitry Andric // via "Res" and "ConstOpnd", respectively (If the entire expression is
12930b57cec5SDimitry Andric // evaluated to a constant, the Res is set to NULL); otherwise, false is
12940b57cec5SDimitry Andric // returned, and both "Res" and "ConstOpnd" remain unchanged.
CombineXorOpnd(BasicBlock::iterator It,XorOpnd * Opnd1,XorOpnd * Opnd2,APInt & ConstOpnd,Value * & Res)1295*0fca6ea1SDimitry Andric bool ReassociatePass::CombineXorOpnd(BasicBlock::iterator It, XorOpnd *Opnd1,
12960b57cec5SDimitry Andric XorOpnd *Opnd2, APInt &ConstOpnd,
12970b57cec5SDimitry Andric Value *&Res) {
12980b57cec5SDimitry Andric Value *X = Opnd1->getSymbolicPart();
12990b57cec5SDimitry Andric if (X != Opnd2->getSymbolicPart())
13000b57cec5SDimitry Andric return false;
13010b57cec5SDimitry Andric
13020b57cec5SDimitry Andric // This many instruction become dead.(At least "Opnd1 ^ Opnd2" will die.)
13030b57cec5SDimitry Andric int DeadInstNum = 1;
13040b57cec5SDimitry Andric if (Opnd1->getValue()->hasOneUse())
13050b57cec5SDimitry Andric DeadInstNum++;
13060b57cec5SDimitry Andric if (Opnd2->getValue()->hasOneUse())
13070b57cec5SDimitry Andric DeadInstNum++;
13080b57cec5SDimitry Andric
13090b57cec5SDimitry Andric // Xor-Rule 2:
13100b57cec5SDimitry Andric // (x | c1) ^ (x & c2)
13110b57cec5SDimitry Andric // = (x|c1) ^ (x&c2) ^ (c1 ^ c1) = ((x|c1) ^ c1) ^ (x & c2) ^ c1
13120b57cec5SDimitry Andric // = (x & ~c1) ^ (x & c2) ^ c1 // Xor-Rule 1
13130b57cec5SDimitry Andric // = (x & c3) ^ c1, where c3 = ~c1 ^ c2 // Xor-rule 3
13140b57cec5SDimitry Andric //
13150b57cec5SDimitry Andric if (Opnd1->isOrExpr() != Opnd2->isOrExpr()) {
13160b57cec5SDimitry Andric if (Opnd2->isOrExpr())
13170b57cec5SDimitry Andric std::swap(Opnd1, Opnd2);
13180b57cec5SDimitry Andric
13190b57cec5SDimitry Andric const APInt &C1 = Opnd1->getConstPart();
13200b57cec5SDimitry Andric const APInt &C2 = Opnd2->getConstPart();
13210b57cec5SDimitry Andric APInt C3((~C1) ^ C2);
13220b57cec5SDimitry Andric
13230b57cec5SDimitry Andric // Do not increase code size!
1324349cc55cSDimitry Andric if (!C3.isZero() && !C3.isAllOnes()) {
13250b57cec5SDimitry Andric int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
13260b57cec5SDimitry Andric if (NewInstNum > DeadInstNum)
13270b57cec5SDimitry Andric return false;
13280b57cec5SDimitry Andric }
13290b57cec5SDimitry Andric
1330*0fca6ea1SDimitry Andric Res = createAndInstr(It, X, C3);
13310b57cec5SDimitry Andric ConstOpnd ^= C1;
13320b57cec5SDimitry Andric } else if (Opnd1->isOrExpr()) {
13330b57cec5SDimitry Andric // Xor-Rule 3: (x | c1) ^ (x | c2) = (x & c3) ^ c3 where c3 = c1 ^ c2
13340b57cec5SDimitry Andric //
13350b57cec5SDimitry Andric const APInt &C1 = Opnd1->getConstPart();
13360b57cec5SDimitry Andric const APInt &C2 = Opnd2->getConstPart();
13370b57cec5SDimitry Andric APInt C3 = C1 ^ C2;
13380b57cec5SDimitry Andric
13390b57cec5SDimitry Andric // Do not increase code size
1340349cc55cSDimitry Andric if (!C3.isZero() && !C3.isAllOnes()) {
13410b57cec5SDimitry Andric int NewInstNum = ConstOpnd.getBoolValue() ? 1 : 2;
13420b57cec5SDimitry Andric if (NewInstNum > DeadInstNum)
13430b57cec5SDimitry Andric return false;
13440b57cec5SDimitry Andric }
13450b57cec5SDimitry Andric
1346*0fca6ea1SDimitry Andric Res = createAndInstr(It, X, C3);
13470b57cec5SDimitry Andric ConstOpnd ^= C3;
13480b57cec5SDimitry Andric } else {
13490b57cec5SDimitry Andric // Xor-Rule 4: (x & c1) ^ (x & c2) = (x & (c1^c2))
13500b57cec5SDimitry Andric //
13510b57cec5SDimitry Andric const APInt &C1 = Opnd1->getConstPart();
13520b57cec5SDimitry Andric const APInt &C2 = Opnd2->getConstPart();
13530b57cec5SDimitry Andric APInt C3 = C1 ^ C2;
1354*0fca6ea1SDimitry Andric Res = createAndInstr(It, X, C3);
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric
13570b57cec5SDimitry Andric // Put the original operands in the Redo list; hope they will be deleted
13580b57cec5SDimitry Andric // as dead code.
13590b57cec5SDimitry Andric if (Instruction *T = dyn_cast<Instruction>(Opnd1->getValue()))
13600b57cec5SDimitry Andric RedoInsts.insert(T);
13610b57cec5SDimitry Andric if (Instruction *T = dyn_cast<Instruction>(Opnd2->getValue()))
13620b57cec5SDimitry Andric RedoInsts.insert(T);
13630b57cec5SDimitry Andric
13640b57cec5SDimitry Andric return true;
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric
13670b57cec5SDimitry Andric /// Optimize a series of operands to an 'xor' instruction. If it can be reduced
13680b57cec5SDimitry Andric /// to a single Value, it is returned, otherwise the Ops list is mutated as
13690b57cec5SDimitry Andric /// necessary.
OptimizeXor(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)13700b57cec5SDimitry Andric Value *ReassociatePass::OptimizeXor(Instruction *I,
13710b57cec5SDimitry Andric SmallVectorImpl<ValueEntry> &Ops) {
13720b57cec5SDimitry Andric if (Value *V = OptimizeAndOrXor(Instruction::Xor, Ops))
13730b57cec5SDimitry Andric return V;
13740b57cec5SDimitry Andric
13750b57cec5SDimitry Andric if (Ops.size() == 1)
13760b57cec5SDimitry Andric return nullptr;
13770b57cec5SDimitry Andric
13780b57cec5SDimitry Andric SmallVector<XorOpnd, 8> Opnds;
13790b57cec5SDimitry Andric SmallVector<XorOpnd*, 8> OpndPtrs;
13800b57cec5SDimitry Andric Type *Ty = Ops[0].Op->getType();
13810b57cec5SDimitry Andric APInt ConstOpnd(Ty->getScalarSizeInBits(), 0);
13820b57cec5SDimitry Andric
13830b57cec5SDimitry Andric // Step 1: Convert ValueEntry to XorOpnd
13840b57cec5SDimitry Andric for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
13850b57cec5SDimitry Andric Value *V = Ops[i].Op;
13860b57cec5SDimitry Andric const APInt *C;
13870b57cec5SDimitry Andric // TODO: Support non-splat vectors.
13880b57cec5SDimitry Andric if (match(V, m_APInt(C))) {
13890b57cec5SDimitry Andric ConstOpnd ^= *C;
13900b57cec5SDimitry Andric } else {
13910b57cec5SDimitry Andric XorOpnd O(V);
13920b57cec5SDimitry Andric O.setSymbolicRank(getRank(O.getSymbolicPart()));
13930b57cec5SDimitry Andric Opnds.push_back(O);
13940b57cec5SDimitry Andric }
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric
13970b57cec5SDimitry Andric // NOTE: From this point on, do *NOT* add/delete element to/from "Opnds".
13980b57cec5SDimitry Andric // It would otherwise invalidate the "Opnds"'s iterator, and hence invalidate
13990b57cec5SDimitry Andric // the "OpndPtrs" as well. For the similar reason, do not fuse this loop
14000b57cec5SDimitry Andric // with the previous loop --- the iterator of the "Opnds" may be invalidated
14010b57cec5SDimitry Andric // when new elements are added to the vector.
1402*0fca6ea1SDimitry Andric for (XorOpnd &Op : Opnds)
1403*0fca6ea1SDimitry Andric OpndPtrs.push_back(&Op);
14040b57cec5SDimitry Andric
14050b57cec5SDimitry Andric // Step 2: Sort the Xor-Operands in a way such that the operands containing
14060b57cec5SDimitry Andric // the same symbolic value cluster together. For instance, the input operand
14070b57cec5SDimitry Andric // sequence ("x | 123", "y & 456", "x & 789") will be sorted into:
14080b57cec5SDimitry Andric // ("x | 123", "x & 789", "y & 456").
14090b57cec5SDimitry Andric //
14100b57cec5SDimitry Andric // The purpose is twofold:
14110b57cec5SDimitry Andric // 1) Cluster together the operands sharing the same symbolic-value.
14120b57cec5SDimitry Andric // 2) Operand having smaller symbolic-value-rank is permuted earlier, which
14130b57cec5SDimitry Andric // could potentially shorten crital path, and expose more loop-invariants.
14140b57cec5SDimitry Andric // Note that values' rank are basically defined in RPO order (FIXME).
14150b57cec5SDimitry Andric // So, if Rank(X) < Rank(Y) < Rank(Z), it means X is defined earlier
14160b57cec5SDimitry Andric // than Y which is defined earlier than Z. Permute "x | 1", "Y & 2",
14170b57cec5SDimitry Andric // "z" in the order of X-Y-Z is better than any other orders.
14180b57cec5SDimitry Andric llvm::stable_sort(OpndPtrs, [](XorOpnd *LHS, XorOpnd *RHS) {
14190b57cec5SDimitry Andric return LHS->getSymbolicRank() < RHS->getSymbolicRank();
14200b57cec5SDimitry Andric });
14210b57cec5SDimitry Andric
14220b57cec5SDimitry Andric // Step 3: Combine adjacent operands
14230b57cec5SDimitry Andric XorOpnd *PrevOpnd = nullptr;
14240b57cec5SDimitry Andric bool Changed = false;
14250b57cec5SDimitry Andric for (unsigned i = 0, e = Opnds.size(); i < e; i++) {
14260b57cec5SDimitry Andric XorOpnd *CurrOpnd = OpndPtrs[i];
14270b57cec5SDimitry Andric // The combined value
14280b57cec5SDimitry Andric Value *CV;
14290b57cec5SDimitry Andric
14300b57cec5SDimitry Andric // Step 3.1: Try simplifying "CurrOpnd ^ ConstOpnd"
1431*0fca6ea1SDimitry Andric if (!ConstOpnd.isZero() &&
1432*0fca6ea1SDimitry Andric CombineXorOpnd(I->getIterator(), CurrOpnd, ConstOpnd, CV)) {
14330b57cec5SDimitry Andric Changed = true;
14340b57cec5SDimitry Andric if (CV)
14350b57cec5SDimitry Andric *CurrOpnd = XorOpnd(CV);
14360b57cec5SDimitry Andric else {
14370b57cec5SDimitry Andric CurrOpnd->Invalidate();
14380b57cec5SDimitry Andric continue;
14390b57cec5SDimitry Andric }
14400b57cec5SDimitry Andric }
14410b57cec5SDimitry Andric
14420b57cec5SDimitry Andric if (!PrevOpnd || CurrOpnd->getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
14430b57cec5SDimitry Andric PrevOpnd = CurrOpnd;
14440b57cec5SDimitry Andric continue;
14450b57cec5SDimitry Andric }
14460b57cec5SDimitry Andric
14470b57cec5SDimitry Andric // step 3.2: When previous and current operands share the same symbolic
14480b57cec5SDimitry Andric // value, try to simplify "PrevOpnd ^ CurrOpnd ^ ConstOpnd"
1449*0fca6ea1SDimitry Andric if (CombineXorOpnd(I->getIterator(), CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
14500b57cec5SDimitry Andric // Remove previous operand
14510b57cec5SDimitry Andric PrevOpnd->Invalidate();
14520b57cec5SDimitry Andric if (CV) {
14530b57cec5SDimitry Andric *CurrOpnd = XorOpnd(CV);
14540b57cec5SDimitry Andric PrevOpnd = CurrOpnd;
14550b57cec5SDimitry Andric } else {
14560b57cec5SDimitry Andric CurrOpnd->Invalidate();
14570b57cec5SDimitry Andric PrevOpnd = nullptr;
14580b57cec5SDimitry Andric }
14590b57cec5SDimitry Andric Changed = true;
14600b57cec5SDimitry Andric }
14610b57cec5SDimitry Andric }
14620b57cec5SDimitry Andric
14630b57cec5SDimitry Andric // Step 4: Reassemble the Ops
14640b57cec5SDimitry Andric if (Changed) {
14650b57cec5SDimitry Andric Ops.clear();
146606c3fb27SDimitry Andric for (const XorOpnd &O : Opnds) {
14670b57cec5SDimitry Andric if (O.isInvalid())
14680b57cec5SDimitry Andric continue;
14690b57cec5SDimitry Andric ValueEntry VE(getRank(O.getValue()), O.getValue());
14700b57cec5SDimitry Andric Ops.push_back(VE);
14710b57cec5SDimitry Andric }
1472349cc55cSDimitry Andric if (!ConstOpnd.isZero()) {
14730b57cec5SDimitry Andric Value *C = ConstantInt::get(Ty, ConstOpnd);
14740b57cec5SDimitry Andric ValueEntry VE(getRank(C), C);
14750b57cec5SDimitry Andric Ops.push_back(VE);
14760b57cec5SDimitry Andric }
14770b57cec5SDimitry Andric unsigned Sz = Ops.size();
14780b57cec5SDimitry Andric if (Sz == 1)
14790b57cec5SDimitry Andric return Ops.back().Op;
14800b57cec5SDimitry Andric if (Sz == 0) {
1481349cc55cSDimitry Andric assert(ConstOpnd.isZero());
14820b57cec5SDimitry Andric return ConstantInt::get(Ty, ConstOpnd);
14830b57cec5SDimitry Andric }
14840b57cec5SDimitry Andric }
14850b57cec5SDimitry Andric
14860b57cec5SDimitry Andric return nullptr;
14870b57cec5SDimitry Andric }
14880b57cec5SDimitry Andric
14890b57cec5SDimitry Andric /// Optimize a series of operands to an 'add' instruction. This
14900b57cec5SDimitry Andric /// optimizes based on identities. If it can be reduced to a single Value, it
14910b57cec5SDimitry Andric /// is returned, otherwise the Ops list is mutated as necessary.
OptimizeAdd(Instruction * I,SmallVectorImpl<ValueEntry> & Ops)14920b57cec5SDimitry Andric Value *ReassociatePass::OptimizeAdd(Instruction *I,
14930b57cec5SDimitry Andric SmallVectorImpl<ValueEntry> &Ops) {
14940b57cec5SDimitry Andric // Scan the operand lists looking for X and -X pairs. If we find any, we
14950b57cec5SDimitry Andric // can simplify expressions like X+-X == 0 and X+~X ==-1. While we're at it,
14960b57cec5SDimitry Andric // scan for any
14970b57cec5SDimitry Andric // duplicates. We want to canonicalize Y+Y+Y+Z -> 3*Y+Z.
14980b57cec5SDimitry Andric
14990b57cec5SDimitry Andric for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
15000b57cec5SDimitry Andric Value *TheOp = Ops[i].Op;
15010b57cec5SDimitry Andric // Check to see if we've seen this operand before. If so, we factor all
15020b57cec5SDimitry Andric // instances of the operand together. Due to our sorting criteria, we know
15030b57cec5SDimitry Andric // that these need to be next to each other in the vector.
15040b57cec5SDimitry Andric if (i+1 != Ops.size() && Ops[i+1].Op == TheOp) {
15050b57cec5SDimitry Andric // Rescan the list, remove all instances of this operand from the expr.
15060b57cec5SDimitry Andric unsigned NumFound = 0;
15070b57cec5SDimitry Andric do {
15080b57cec5SDimitry Andric Ops.erase(Ops.begin()+i);
15090b57cec5SDimitry Andric ++NumFound;
15100b57cec5SDimitry Andric } while (i != Ops.size() && Ops[i].Op == TheOp);
15110b57cec5SDimitry Andric
15120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nFACTORING [" << NumFound << "]: " << *TheOp
15130b57cec5SDimitry Andric << '\n');
15140b57cec5SDimitry Andric ++NumFactor;
15150b57cec5SDimitry Andric
15160b57cec5SDimitry Andric // Insert a new multiply.
15170b57cec5SDimitry Andric Type *Ty = TheOp->getType();
15180b57cec5SDimitry Andric Constant *C = Ty->isIntOrIntVectorTy() ?
15190b57cec5SDimitry Andric ConstantInt::get(Ty, NumFound) : ConstantFP::get(Ty, NumFound);
1520*0fca6ea1SDimitry Andric Instruction *Mul = CreateMul(TheOp, C, "factor", I->getIterator(), I);
15210b57cec5SDimitry Andric
15220b57cec5SDimitry Andric // Now that we have inserted a multiply, optimize it. This allows us to
15230b57cec5SDimitry Andric // handle cases that require multiple factoring steps, such as this:
15240b57cec5SDimitry Andric // (X*2) + (X*2) + (X*2) -> (X*2)*3 -> X*6
15250b57cec5SDimitry Andric RedoInsts.insert(Mul);
15260b57cec5SDimitry Andric
15270b57cec5SDimitry Andric // If every add operand was a duplicate, return the multiply.
15280b57cec5SDimitry Andric if (Ops.empty())
15290b57cec5SDimitry Andric return Mul;
15300b57cec5SDimitry Andric
15310b57cec5SDimitry Andric // Otherwise, we had some input that didn't have the dupe, such as
15320b57cec5SDimitry Andric // "A + A + B" -> "A*2 + B". Add the new multiply to the list of
15330b57cec5SDimitry Andric // things being added by this operation.
15340b57cec5SDimitry Andric Ops.insert(Ops.begin(), ValueEntry(getRank(Mul), Mul));
15350b57cec5SDimitry Andric
15360b57cec5SDimitry Andric --i;
15370b57cec5SDimitry Andric e = Ops.size();
15380b57cec5SDimitry Andric continue;
15390b57cec5SDimitry Andric }
15400b57cec5SDimitry Andric
15410b57cec5SDimitry Andric // Check for X and -X or X and ~X in the operand list.
15420b57cec5SDimitry Andric Value *X;
15430b57cec5SDimitry Andric if (!match(TheOp, m_Neg(m_Value(X))) && !match(TheOp, m_Not(m_Value(X))) &&
15440b57cec5SDimitry Andric !match(TheOp, m_FNeg(m_Value(X))))
15450b57cec5SDimitry Andric continue;
15460b57cec5SDimitry Andric
15470b57cec5SDimitry Andric unsigned FoundX = FindInOperandList(Ops, i, X);
15480b57cec5SDimitry Andric if (FoundX == i)
15490b57cec5SDimitry Andric continue;
15500b57cec5SDimitry Andric
15510b57cec5SDimitry Andric // Remove X and -X from the operand list.
15520b57cec5SDimitry Andric if (Ops.size() == 2 &&
15530b57cec5SDimitry Andric (match(TheOp, m_Neg(m_Value())) || match(TheOp, m_FNeg(m_Value()))))
15540b57cec5SDimitry Andric return Constant::getNullValue(X->getType());
15550b57cec5SDimitry Andric
15560b57cec5SDimitry Andric // Remove X and ~X from the operand list.
15570b57cec5SDimitry Andric if (Ops.size() == 2 && match(TheOp, m_Not(m_Value())))
15580b57cec5SDimitry Andric return Constant::getAllOnesValue(X->getType());
15590b57cec5SDimitry Andric
15600b57cec5SDimitry Andric Ops.erase(Ops.begin()+i);
15610b57cec5SDimitry Andric if (i < FoundX)
15620b57cec5SDimitry Andric --FoundX;
15630b57cec5SDimitry Andric else
15640b57cec5SDimitry Andric --i; // Need to back up an extra one.
15650b57cec5SDimitry Andric Ops.erase(Ops.begin()+FoundX);
15660b57cec5SDimitry Andric ++NumAnnihil;
15670b57cec5SDimitry Andric --i; // Revisit element.
15680b57cec5SDimitry Andric e -= 2; // Removed two elements.
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric // if X and ~X we append -1 to the operand list.
15710b57cec5SDimitry Andric if (match(TheOp, m_Not(m_Value()))) {
15720b57cec5SDimitry Andric Value *V = Constant::getAllOnesValue(X->getType());
15730b57cec5SDimitry Andric Ops.insert(Ops.end(), ValueEntry(getRank(V), V));
15740b57cec5SDimitry Andric e += 1;
15750b57cec5SDimitry Andric }
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric
15780b57cec5SDimitry Andric // Scan the operand list, checking to see if there are any common factors
15790b57cec5SDimitry Andric // between operands. Consider something like A*A+A*B*C+D. We would like to
15800b57cec5SDimitry Andric // reassociate this to A*(A+B*C)+D, which reduces the number of multiplies.
15810b57cec5SDimitry Andric // To efficiently find this, we count the number of times a factor occurs
15820b57cec5SDimitry Andric // for any ADD operands that are MULs.
15830b57cec5SDimitry Andric DenseMap<Value*, unsigned> FactorOccurrences;
15840b57cec5SDimitry Andric
15850b57cec5SDimitry Andric // Keep track of each multiply we see, to avoid triggering on (X*4)+(X*4)
15860b57cec5SDimitry Andric // where they are actually the same multiply.
15870b57cec5SDimitry Andric unsigned MaxOcc = 0;
15880b57cec5SDimitry Andric Value *MaxOccVal = nullptr;
15890b57cec5SDimitry Andric for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
15900b57cec5SDimitry Andric BinaryOperator *BOp =
15910b57cec5SDimitry Andric isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
15920b57cec5SDimitry Andric if (!BOp)
15930b57cec5SDimitry Andric continue;
15940b57cec5SDimitry Andric
15950b57cec5SDimitry Andric // Compute all of the factors of this added value.
15960b57cec5SDimitry Andric SmallVector<Value*, 8> Factors;
15970b57cec5SDimitry Andric FindSingleUseMultiplyFactors(BOp, Factors);
15980b57cec5SDimitry Andric assert(Factors.size() > 1 && "Bad linearize!");
15990b57cec5SDimitry Andric
16000b57cec5SDimitry Andric // Add one to FactorOccurrences for each unique factor in this op.
16010b57cec5SDimitry Andric SmallPtrSet<Value*, 8> Duplicates;
160206c3fb27SDimitry Andric for (Value *Factor : Factors) {
16030b57cec5SDimitry Andric if (!Duplicates.insert(Factor).second)
16040b57cec5SDimitry Andric continue;
16050b57cec5SDimitry Andric
16060b57cec5SDimitry Andric unsigned Occ = ++FactorOccurrences[Factor];
16070b57cec5SDimitry Andric if (Occ > MaxOcc) {
16080b57cec5SDimitry Andric MaxOcc = Occ;
16090b57cec5SDimitry Andric MaxOccVal = Factor;
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric
16120b57cec5SDimitry Andric // If Factor is a negative constant, add the negated value as a factor
16130b57cec5SDimitry Andric // because we can percolate the negate out. Watch for minint, which
16140b57cec5SDimitry Andric // cannot be positivified.
16150b57cec5SDimitry Andric if (ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
16160b57cec5SDimitry Andric if (CI->isNegative() && !CI->isMinValue(true)) {
16170b57cec5SDimitry Andric Factor = ConstantInt::get(CI->getContext(), -CI->getValue());
16180b57cec5SDimitry Andric if (!Duplicates.insert(Factor).second)
16190b57cec5SDimitry Andric continue;
16200b57cec5SDimitry Andric unsigned Occ = ++FactorOccurrences[Factor];
16210b57cec5SDimitry Andric if (Occ > MaxOcc) {
16220b57cec5SDimitry Andric MaxOcc = Occ;
16230b57cec5SDimitry Andric MaxOccVal = Factor;
16240b57cec5SDimitry Andric }
16250b57cec5SDimitry Andric }
16260b57cec5SDimitry Andric } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
16270b57cec5SDimitry Andric if (CF->isNegative()) {
16280b57cec5SDimitry Andric APFloat F(CF->getValueAPF());
16290b57cec5SDimitry Andric F.changeSign();
16300b57cec5SDimitry Andric Factor = ConstantFP::get(CF->getContext(), F);
16310b57cec5SDimitry Andric if (!Duplicates.insert(Factor).second)
16320b57cec5SDimitry Andric continue;
16330b57cec5SDimitry Andric unsigned Occ = ++FactorOccurrences[Factor];
16340b57cec5SDimitry Andric if (Occ > MaxOcc) {
16350b57cec5SDimitry Andric MaxOcc = Occ;
16360b57cec5SDimitry Andric MaxOccVal = Factor;
16370b57cec5SDimitry Andric }
16380b57cec5SDimitry Andric }
16390b57cec5SDimitry Andric }
16400b57cec5SDimitry Andric }
16410b57cec5SDimitry Andric }
16420b57cec5SDimitry Andric
16430b57cec5SDimitry Andric // If any factor occurred more than one time, we can pull it out.
16440b57cec5SDimitry Andric if (MaxOcc > 1) {
16450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\nFACTORING [" << MaxOcc << "]: " << *MaxOccVal
16460b57cec5SDimitry Andric << '\n');
16470b57cec5SDimitry Andric ++NumFactor;
16480b57cec5SDimitry Andric
16490b57cec5SDimitry Andric // Create a new instruction that uses the MaxOccVal twice. If we don't do
16500b57cec5SDimitry Andric // this, we could otherwise run into situations where removing a factor
16510b57cec5SDimitry Andric // from an expression will drop a use of maxocc, and this can cause
16520b57cec5SDimitry Andric // RemoveFactorFromExpression on successive values to behave differently.
16530b57cec5SDimitry Andric Instruction *DummyInst =
16540b57cec5SDimitry Andric I->getType()->isIntOrIntVectorTy()
16550b57cec5SDimitry Andric ? BinaryOperator::CreateAdd(MaxOccVal, MaxOccVal)
16560b57cec5SDimitry Andric : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
16570b57cec5SDimitry Andric
16580b57cec5SDimitry Andric SmallVector<WeakTrackingVH, 4> NewMulOps;
16590b57cec5SDimitry Andric for (unsigned i = 0; i != Ops.size(); ++i) {
16600b57cec5SDimitry Andric // Only try to remove factors from expressions we're allowed to.
16610b57cec5SDimitry Andric BinaryOperator *BOp =
16620b57cec5SDimitry Andric isReassociableOp(Ops[i].Op, Instruction::Mul, Instruction::FMul);
16630b57cec5SDimitry Andric if (!BOp)
16640b57cec5SDimitry Andric continue;
16650b57cec5SDimitry Andric
16660b57cec5SDimitry Andric if (Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
16670b57cec5SDimitry Andric // The factorized operand may occur several times. Convert them all in
16680b57cec5SDimitry Andric // one fell swoop.
16690b57cec5SDimitry Andric for (unsigned j = Ops.size(); j != i;) {
16700b57cec5SDimitry Andric --j;
16710b57cec5SDimitry Andric if (Ops[j].Op == Ops[i].Op) {
16720b57cec5SDimitry Andric NewMulOps.push_back(V);
16730b57cec5SDimitry Andric Ops.erase(Ops.begin()+j);
16740b57cec5SDimitry Andric }
16750b57cec5SDimitry Andric }
16760b57cec5SDimitry Andric --i;
16770b57cec5SDimitry Andric }
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric
16800b57cec5SDimitry Andric // No need for extra uses anymore.
16810b57cec5SDimitry Andric DummyInst->deleteValue();
16820b57cec5SDimitry Andric
16830b57cec5SDimitry Andric unsigned NumAddedValues = NewMulOps.size();
1684*0fca6ea1SDimitry Andric Value *V = EmitAddTreeOfValues(I->getIterator(), NewMulOps);
16850b57cec5SDimitry Andric
16860b57cec5SDimitry Andric // Now that we have inserted the add tree, optimize it. This allows us to
16870b57cec5SDimitry Andric // handle cases that require multiple factoring steps, such as this:
16880b57cec5SDimitry Andric // A*A*B + A*A*C --> A*(A*B+A*C) --> A*(A*(B+C))
16890b57cec5SDimitry Andric assert(NumAddedValues > 1 && "Each occurrence should contribute a value");
16900b57cec5SDimitry Andric (void)NumAddedValues;
16910b57cec5SDimitry Andric if (Instruction *VI = dyn_cast<Instruction>(V))
16920b57cec5SDimitry Andric RedoInsts.insert(VI);
16930b57cec5SDimitry Andric
16940b57cec5SDimitry Andric // Create the multiply.
1695*0fca6ea1SDimitry Andric Instruction *V2 = CreateMul(V, MaxOccVal, "reass.mul", I->getIterator(), I);
16960b57cec5SDimitry Andric
16970b57cec5SDimitry Andric // Rerun associate on the multiply in case the inner expression turned into
16980b57cec5SDimitry Andric // a multiply. We want to make sure that we keep things in canonical form.
16990b57cec5SDimitry Andric RedoInsts.insert(V2);
17000b57cec5SDimitry Andric
17010b57cec5SDimitry Andric // If every add operand included the factor (e.g. "A*B + A*C"), then the
17020b57cec5SDimitry Andric // entire result expression is just the multiply "A*(B+C)".
17030b57cec5SDimitry Andric if (Ops.empty())
17040b57cec5SDimitry Andric return V2;
17050b57cec5SDimitry Andric
17060b57cec5SDimitry Andric // Otherwise, we had some input that didn't have the factor, such as
17070b57cec5SDimitry Andric // "A*B + A*C + D" -> "A*(B+C) + D". Add the new multiply to the list of
17080b57cec5SDimitry Andric // things being added by this operation.
17090b57cec5SDimitry Andric Ops.insert(Ops.begin(), ValueEntry(getRank(V2), V2));
17100b57cec5SDimitry Andric }
17110b57cec5SDimitry Andric
17120b57cec5SDimitry Andric return nullptr;
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric
17150b57cec5SDimitry Andric /// Build up a vector of value/power pairs factoring a product.
17160b57cec5SDimitry Andric ///
17170b57cec5SDimitry Andric /// Given a series of multiplication operands, build a vector of factors and
17180b57cec5SDimitry Andric /// the powers each is raised to when forming the final product. Sort them in
17190b57cec5SDimitry Andric /// the order of descending power.
17200b57cec5SDimitry Andric ///
17210b57cec5SDimitry Andric /// (x*x) -> [(x, 2)]
17220b57cec5SDimitry Andric /// ((x*x)*x) -> [(x, 3)]
17230b57cec5SDimitry Andric /// ((((x*y)*x)*y)*x) -> [(x, 3), (y, 2)]
17240b57cec5SDimitry Andric ///
17250b57cec5SDimitry Andric /// \returns Whether any factors have a power greater than one.
collectMultiplyFactors(SmallVectorImpl<ValueEntry> & Ops,SmallVectorImpl<Factor> & Factors)17260b57cec5SDimitry Andric static bool collectMultiplyFactors(SmallVectorImpl<ValueEntry> &Ops,
17270b57cec5SDimitry Andric SmallVectorImpl<Factor> &Factors) {
17280b57cec5SDimitry Andric // FIXME: Have Ops be (ValueEntry, Multiplicity) pairs, simplifying this.
17290b57cec5SDimitry Andric // Compute the sum of powers of simplifiable factors.
17300b57cec5SDimitry Andric unsigned FactorPowerSum = 0;
17310b57cec5SDimitry Andric for (unsigned Idx = 1, Size = Ops.size(); Idx < Size; ++Idx) {
17320b57cec5SDimitry Andric Value *Op = Ops[Idx-1].Op;
17330b57cec5SDimitry Andric
17340b57cec5SDimitry Andric // Count the number of occurrences of this value.
17350b57cec5SDimitry Andric unsigned Count = 1;
17360b57cec5SDimitry Andric for (; Idx < Size && Ops[Idx].Op == Op; ++Idx)
17370b57cec5SDimitry Andric ++Count;
17380b57cec5SDimitry Andric // Track for simplification all factors which occur 2 or more times.
17390b57cec5SDimitry Andric if (Count > 1)
17400b57cec5SDimitry Andric FactorPowerSum += Count;
17410b57cec5SDimitry Andric }
17420b57cec5SDimitry Andric
17430b57cec5SDimitry Andric // We can only simplify factors if the sum of the powers of our simplifiable
17440b57cec5SDimitry Andric // factors is 4 or higher. When that is the case, we will *always* have
17450b57cec5SDimitry Andric // a simplification. This is an important invariant to prevent cyclicly
17460b57cec5SDimitry Andric // trying to simplify already minimal formations.
17470b57cec5SDimitry Andric if (FactorPowerSum < 4)
17480b57cec5SDimitry Andric return false;
17490b57cec5SDimitry Andric
17500b57cec5SDimitry Andric // Now gather the simplifiable factors, removing them from Ops.
17510b57cec5SDimitry Andric FactorPowerSum = 0;
17520b57cec5SDimitry Andric for (unsigned Idx = 1; Idx < Ops.size(); ++Idx) {
17530b57cec5SDimitry Andric Value *Op = Ops[Idx-1].Op;
17540b57cec5SDimitry Andric
17550b57cec5SDimitry Andric // Count the number of occurrences of this value.
17560b57cec5SDimitry Andric unsigned Count = 1;
17570b57cec5SDimitry Andric for (; Idx < Ops.size() && Ops[Idx].Op == Op; ++Idx)
17580b57cec5SDimitry Andric ++Count;
17590b57cec5SDimitry Andric if (Count == 1)
17600b57cec5SDimitry Andric continue;
17610b57cec5SDimitry Andric // Move an even number of occurrences to Factors.
17620b57cec5SDimitry Andric Count &= ~1U;
17630b57cec5SDimitry Andric Idx -= Count;
17640b57cec5SDimitry Andric FactorPowerSum += Count;
17650b57cec5SDimitry Andric Factors.push_back(Factor(Op, Count));
17660b57cec5SDimitry Andric Ops.erase(Ops.begin()+Idx, Ops.begin()+Idx+Count);
17670b57cec5SDimitry Andric }
17680b57cec5SDimitry Andric
17690b57cec5SDimitry Andric // None of the adjustments above should have reduced the sum of factor powers
17700b57cec5SDimitry Andric // below our mininum of '4'.
17710b57cec5SDimitry Andric assert(FactorPowerSum >= 4);
17720b57cec5SDimitry Andric
17730b57cec5SDimitry Andric llvm::stable_sort(Factors, [](const Factor &LHS, const Factor &RHS) {
17740b57cec5SDimitry Andric return LHS.Power > RHS.Power;
17750b57cec5SDimitry Andric });
17760b57cec5SDimitry Andric return true;
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric
17790b57cec5SDimitry Andric /// Build a tree of multiplies, computing the product of Ops.
buildMultiplyTree(IRBuilderBase & Builder,SmallVectorImpl<Value * > & Ops)17805ffd83dbSDimitry Andric static Value *buildMultiplyTree(IRBuilderBase &Builder,
17810b57cec5SDimitry Andric SmallVectorImpl<Value*> &Ops) {
17820b57cec5SDimitry Andric if (Ops.size() == 1)
17830b57cec5SDimitry Andric return Ops.back();
17840b57cec5SDimitry Andric
17850b57cec5SDimitry Andric Value *LHS = Ops.pop_back_val();
17860b57cec5SDimitry Andric do {
17870b57cec5SDimitry Andric if (LHS->getType()->isIntOrIntVectorTy())
17880b57cec5SDimitry Andric LHS = Builder.CreateMul(LHS, Ops.pop_back_val());
17890b57cec5SDimitry Andric else
17900b57cec5SDimitry Andric LHS = Builder.CreateFMul(LHS, Ops.pop_back_val());
17910b57cec5SDimitry Andric } while (!Ops.empty());
17920b57cec5SDimitry Andric
17930b57cec5SDimitry Andric return LHS;
17940b57cec5SDimitry Andric }
17950b57cec5SDimitry Andric
17960b57cec5SDimitry Andric /// Build a minimal multiplication DAG for (a^x)*(b^y)*(c^z)*...
17970b57cec5SDimitry Andric ///
17980b57cec5SDimitry Andric /// Given a vector of values raised to various powers, where no two values are
17990b57cec5SDimitry Andric /// equal and the powers are sorted in decreasing order, compute the minimal
18000b57cec5SDimitry Andric /// DAG of multiplies to compute the final product, and return that product
18010b57cec5SDimitry Andric /// value.
18020b57cec5SDimitry Andric Value *
buildMinimalMultiplyDAG(IRBuilderBase & Builder,SmallVectorImpl<Factor> & Factors)18035ffd83dbSDimitry Andric ReassociatePass::buildMinimalMultiplyDAG(IRBuilderBase &Builder,
18040b57cec5SDimitry Andric SmallVectorImpl<Factor> &Factors) {
18050b57cec5SDimitry Andric assert(Factors[0].Power);
18060b57cec5SDimitry Andric SmallVector<Value *, 4> OuterProduct;
18070b57cec5SDimitry Andric for (unsigned LastIdx = 0, Idx = 1, Size = Factors.size();
18080b57cec5SDimitry Andric Idx < Size && Factors[Idx].Power > 0; ++Idx) {
18090b57cec5SDimitry Andric if (Factors[Idx].Power != Factors[LastIdx].Power) {
18100b57cec5SDimitry Andric LastIdx = Idx;
18110b57cec5SDimitry Andric continue;
18120b57cec5SDimitry Andric }
18130b57cec5SDimitry Andric
18140b57cec5SDimitry Andric // We want to multiply across all the factors with the same power so that
18150b57cec5SDimitry Andric // we can raise them to that power as a single entity. Build a mini tree
18160b57cec5SDimitry Andric // for that.
18170b57cec5SDimitry Andric SmallVector<Value *, 4> InnerProduct;
18180b57cec5SDimitry Andric InnerProduct.push_back(Factors[LastIdx].Base);
18190b57cec5SDimitry Andric do {
18200b57cec5SDimitry Andric InnerProduct.push_back(Factors[Idx].Base);
18210b57cec5SDimitry Andric ++Idx;
18220b57cec5SDimitry Andric } while (Idx < Size && Factors[Idx].Power == Factors[LastIdx].Power);
18230b57cec5SDimitry Andric
18240b57cec5SDimitry Andric // Reset the base value of the first factor to the new expression tree.
18250b57cec5SDimitry Andric // We'll remove all the factors with the same power in a second pass.
18260b57cec5SDimitry Andric Value *M = Factors[LastIdx].Base = buildMultiplyTree(Builder, InnerProduct);
18270b57cec5SDimitry Andric if (Instruction *MI = dyn_cast<Instruction>(M))
18280b57cec5SDimitry Andric RedoInsts.insert(MI);
18290b57cec5SDimitry Andric
18300b57cec5SDimitry Andric LastIdx = Idx;
18310b57cec5SDimitry Andric }
18320b57cec5SDimitry Andric // Unique factors with equal powers -- we've folded them into the first one's
18330b57cec5SDimitry Andric // base.
1834*0fca6ea1SDimitry Andric Factors.erase(llvm::unique(Factors,
18350b57cec5SDimitry Andric [](const Factor &LHS, const Factor &RHS) {
18360b57cec5SDimitry Andric return LHS.Power == RHS.Power;
18370b57cec5SDimitry Andric }),
18380b57cec5SDimitry Andric Factors.end());
18390b57cec5SDimitry Andric
18400b57cec5SDimitry Andric // Iteratively collect the base of each factor with an add power into the
18410b57cec5SDimitry Andric // outer product, and halve each power in preparation for squaring the
18420b57cec5SDimitry Andric // expression.
1843bdd1243dSDimitry Andric for (Factor &F : Factors) {
1844bdd1243dSDimitry Andric if (F.Power & 1)
1845bdd1243dSDimitry Andric OuterProduct.push_back(F.Base);
1846bdd1243dSDimitry Andric F.Power >>= 1;
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric if (Factors[0].Power) {
18490b57cec5SDimitry Andric Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
18500b57cec5SDimitry Andric OuterProduct.push_back(SquareRoot);
18510b57cec5SDimitry Andric OuterProduct.push_back(SquareRoot);
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric if (OuterProduct.size() == 1)
18540b57cec5SDimitry Andric return OuterProduct.front();
18550b57cec5SDimitry Andric
18560b57cec5SDimitry Andric Value *V = buildMultiplyTree(Builder, OuterProduct);
18570b57cec5SDimitry Andric return V;
18580b57cec5SDimitry Andric }
18590b57cec5SDimitry Andric
OptimizeMul(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)18600b57cec5SDimitry Andric Value *ReassociatePass::OptimizeMul(BinaryOperator *I,
18610b57cec5SDimitry Andric SmallVectorImpl<ValueEntry> &Ops) {
18620b57cec5SDimitry Andric // We can only optimize the multiplies when there is a chain of more than
18630b57cec5SDimitry Andric // three, such that a balanced tree might require fewer total multiplies.
18640b57cec5SDimitry Andric if (Ops.size() < 4)
18650b57cec5SDimitry Andric return nullptr;
18660b57cec5SDimitry Andric
18670b57cec5SDimitry Andric // Try to turn linear trees of multiplies without other uses of the
18680b57cec5SDimitry Andric // intermediate stages into minimal multiply DAGs with perfect sub-expression
18690b57cec5SDimitry Andric // re-use.
18700b57cec5SDimitry Andric SmallVector<Factor, 4> Factors;
18710b57cec5SDimitry Andric if (!collectMultiplyFactors(Ops, Factors))
18720b57cec5SDimitry Andric return nullptr; // All distinct factors, so nothing left for us to do.
18730b57cec5SDimitry Andric
18740b57cec5SDimitry Andric IRBuilder<> Builder(I);
18750b57cec5SDimitry Andric // The reassociate transformation for FP operations is performed only
18760b57cec5SDimitry Andric // if unsafe algebra is permitted by FastMathFlags. Propagate those flags
18770b57cec5SDimitry Andric // to the newly generated operations.
18780b57cec5SDimitry Andric if (auto FPI = dyn_cast<FPMathOperator>(I))
18790b57cec5SDimitry Andric Builder.setFastMathFlags(FPI->getFastMathFlags());
18800b57cec5SDimitry Andric
18810b57cec5SDimitry Andric Value *V = buildMinimalMultiplyDAG(Builder, Factors);
18820b57cec5SDimitry Andric if (Ops.empty())
18830b57cec5SDimitry Andric return V;
18840b57cec5SDimitry Andric
18850b57cec5SDimitry Andric ValueEntry NewEntry = ValueEntry(getRank(V), V);
18860b57cec5SDimitry Andric Ops.insert(llvm::lower_bound(Ops, NewEntry), NewEntry);
18870b57cec5SDimitry Andric return nullptr;
18880b57cec5SDimitry Andric }
18890b57cec5SDimitry Andric
OptimizeExpression(BinaryOperator * I,SmallVectorImpl<ValueEntry> & Ops)18900b57cec5SDimitry Andric Value *ReassociatePass::OptimizeExpression(BinaryOperator *I,
18910b57cec5SDimitry Andric SmallVectorImpl<ValueEntry> &Ops) {
18920b57cec5SDimitry Andric // Now that we have the linearized expression tree, try to optimize it.
18930b57cec5SDimitry Andric // Start by folding any constants that we found.
1894*0fca6ea1SDimitry Andric const DataLayout &DL = I->getDataLayout();
18950b57cec5SDimitry Andric Constant *Cst = nullptr;
18960b57cec5SDimitry Andric unsigned Opcode = I->getOpcode();
1897753f127fSDimitry Andric while (!Ops.empty()) {
1898753f127fSDimitry Andric if (auto *C = dyn_cast<Constant>(Ops.back().Op)) {
1899753f127fSDimitry Andric if (!Cst) {
1900753f127fSDimitry Andric Ops.pop_back();
1901753f127fSDimitry Andric Cst = C;
1902753f127fSDimitry Andric continue;
1903753f127fSDimitry Andric }
1904753f127fSDimitry Andric if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, C, Cst, DL)) {
1905753f127fSDimitry Andric Ops.pop_back();
1906753f127fSDimitry Andric Cst = Res;
1907753f127fSDimitry Andric continue;
1908753f127fSDimitry Andric }
1909753f127fSDimitry Andric }
1910753f127fSDimitry Andric break;
19110b57cec5SDimitry Andric }
19120b57cec5SDimitry Andric // If there was nothing but constants then we are done.
19130b57cec5SDimitry Andric if (Ops.empty())
19140b57cec5SDimitry Andric return Cst;
19150b57cec5SDimitry Andric
19160b57cec5SDimitry Andric // Put the combined constant back at the end of the operand list, except if
19170b57cec5SDimitry Andric // there is no point. For example, an add of 0 gets dropped here, while a
19180b57cec5SDimitry Andric // multiplication by zero turns the whole expression into zero.
19190b57cec5SDimitry Andric if (Cst && Cst != ConstantExpr::getBinOpIdentity(Opcode, I->getType())) {
19200b57cec5SDimitry Andric if (Cst == ConstantExpr::getBinOpAbsorber(Opcode, I->getType()))
19210b57cec5SDimitry Andric return Cst;
19220b57cec5SDimitry Andric Ops.push_back(ValueEntry(0, Cst));
19230b57cec5SDimitry Andric }
19240b57cec5SDimitry Andric
19250b57cec5SDimitry Andric if (Ops.size() == 1) return Ops[0].Op;
19260b57cec5SDimitry Andric
19270b57cec5SDimitry Andric // Handle destructive annihilation due to identities between elements in the
19280b57cec5SDimitry Andric // argument list here.
19290b57cec5SDimitry Andric unsigned NumOps = Ops.size();
19300b57cec5SDimitry Andric switch (Opcode) {
19310b57cec5SDimitry Andric default: break;
19320b57cec5SDimitry Andric case Instruction::And:
19330b57cec5SDimitry Andric case Instruction::Or:
19340b57cec5SDimitry Andric if (Value *Result = OptimizeAndOrXor(Opcode, Ops))
19350b57cec5SDimitry Andric return Result;
19360b57cec5SDimitry Andric break;
19370b57cec5SDimitry Andric
19380b57cec5SDimitry Andric case Instruction::Xor:
19390b57cec5SDimitry Andric if (Value *Result = OptimizeXor(I, Ops))
19400b57cec5SDimitry Andric return Result;
19410b57cec5SDimitry Andric break;
19420b57cec5SDimitry Andric
19430b57cec5SDimitry Andric case Instruction::Add:
19440b57cec5SDimitry Andric case Instruction::FAdd:
19450b57cec5SDimitry Andric if (Value *Result = OptimizeAdd(I, Ops))
19460b57cec5SDimitry Andric return Result;
19470b57cec5SDimitry Andric break;
19480b57cec5SDimitry Andric
19490b57cec5SDimitry Andric case Instruction::Mul:
19500b57cec5SDimitry Andric case Instruction::FMul:
19510b57cec5SDimitry Andric if (Value *Result = OptimizeMul(I, Ops))
19520b57cec5SDimitry Andric return Result;
19530b57cec5SDimitry Andric break;
19540b57cec5SDimitry Andric }
19550b57cec5SDimitry Andric
19560b57cec5SDimitry Andric if (Ops.size() != NumOps)
19570b57cec5SDimitry Andric return OptimizeExpression(I, Ops);
19580b57cec5SDimitry Andric return nullptr;
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric
19610b57cec5SDimitry Andric // Remove dead instructions and if any operands are trivially dead add them to
19620b57cec5SDimitry Andric // Insts so they will be removed as well.
RecursivelyEraseDeadInsts(Instruction * I,OrderedSet & Insts)19630b57cec5SDimitry Andric void ReassociatePass::RecursivelyEraseDeadInsts(Instruction *I,
19640b57cec5SDimitry Andric OrderedSet &Insts) {
19650b57cec5SDimitry Andric assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
1966e8d8bef9SDimitry Andric SmallVector<Value *, 4> Ops(I->operands());
19670b57cec5SDimitry Andric ValueRankMap.erase(I);
19680b57cec5SDimitry Andric Insts.remove(I);
19690b57cec5SDimitry Andric RedoInsts.remove(I);
19705ffd83dbSDimitry Andric llvm::salvageDebugInfo(*I);
19710b57cec5SDimitry Andric I->eraseFromParent();
1972bdd1243dSDimitry Andric for (auto *Op : Ops)
19730b57cec5SDimitry Andric if (Instruction *OpInst = dyn_cast<Instruction>(Op))
19740b57cec5SDimitry Andric if (OpInst->use_empty())
19750b57cec5SDimitry Andric Insts.insert(OpInst);
19760b57cec5SDimitry Andric }
19770b57cec5SDimitry Andric
19780b57cec5SDimitry Andric /// Zap the given instruction, adding interesting operands to the work list.
EraseInst(Instruction * I)19790b57cec5SDimitry Andric void ReassociatePass::EraseInst(Instruction *I) {
19800b57cec5SDimitry Andric assert(isInstructionTriviallyDead(I) && "Trivially dead instructions only!");
19810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Erasing dead inst: "; I->dump());
19820b57cec5SDimitry Andric
1983e8d8bef9SDimitry Andric SmallVector<Value *, 8> Ops(I->operands());
19840b57cec5SDimitry Andric // Erase the dead instruction.
19850b57cec5SDimitry Andric ValueRankMap.erase(I);
19860b57cec5SDimitry Andric RedoInsts.remove(I);
19875ffd83dbSDimitry Andric llvm::salvageDebugInfo(*I);
19880b57cec5SDimitry Andric I->eraseFromParent();
19890b57cec5SDimitry Andric // Optimize its operands.
19900b57cec5SDimitry Andric SmallPtrSet<Instruction *, 8> Visited; // Detect self-referential nodes.
1991*0fca6ea1SDimitry Andric for (Value *V : Ops)
1992*0fca6ea1SDimitry Andric if (Instruction *Op = dyn_cast<Instruction>(V)) {
19930b57cec5SDimitry Andric // If this is a node in an expression tree, climb to the expression root
19940b57cec5SDimitry Andric // and add that since that's where optimization actually happens.
19950b57cec5SDimitry Andric unsigned Opcode = Op->getOpcode();
19960b57cec5SDimitry Andric while (Op->hasOneUse() && Op->user_back()->getOpcode() == Opcode &&
19970b57cec5SDimitry Andric Visited.insert(Op).second)
19980b57cec5SDimitry Andric Op = Op->user_back();
19990b57cec5SDimitry Andric
20000b57cec5SDimitry Andric // The instruction we're going to push may be coming from a
20010b57cec5SDimitry Andric // dead block, and Reassociate skips the processing of unreachable
20020b57cec5SDimitry Andric // blocks because it's a waste of time and also because it can
20030b57cec5SDimitry Andric // lead to infinite loop due to LLVM's non-standard definition
20040b57cec5SDimitry Andric // of dominance.
200506c3fb27SDimitry Andric if (ValueRankMap.contains(Op))
20060b57cec5SDimitry Andric RedoInsts.insert(Op);
20070b57cec5SDimitry Andric }
20080b57cec5SDimitry Andric
20090b57cec5SDimitry Andric MadeChange = true;
20100b57cec5SDimitry Andric }
20110b57cec5SDimitry Andric
20128bcb0991SDimitry Andric /// Recursively analyze an expression to build a list of instructions that have
20138bcb0991SDimitry Andric /// negative floating-point constant operands. The caller can then transform
20148bcb0991SDimitry Andric /// the list to create positive constants for better reassociation and CSE.
getNegatibleInsts(Value * V,SmallVectorImpl<Instruction * > & Candidates)20158bcb0991SDimitry Andric static void getNegatibleInsts(Value *V,
20168bcb0991SDimitry Andric SmallVectorImpl<Instruction *> &Candidates) {
20178bcb0991SDimitry Andric // Handle only one-use instructions. Combining negations does not justify
20188bcb0991SDimitry Andric // replicating instructions.
20198bcb0991SDimitry Andric Instruction *I;
20208bcb0991SDimitry Andric if (!match(V, m_OneUse(m_Instruction(I))))
20218bcb0991SDimitry Andric return;
20220b57cec5SDimitry Andric
20238bcb0991SDimitry Andric // Handle expressions of multiplications and divisions.
20248bcb0991SDimitry Andric // TODO: This could look through floating-point casts.
20258bcb0991SDimitry Andric const APFloat *C;
20268bcb0991SDimitry Andric switch (I->getOpcode()) {
20278bcb0991SDimitry Andric case Instruction::FMul:
20288bcb0991SDimitry Andric // Not expecting non-canonical code here. Bail out and wait.
20298bcb0991SDimitry Andric if (match(I->getOperand(0), m_Constant()))
20308bcb0991SDimitry Andric break;
20310b57cec5SDimitry Andric
20328bcb0991SDimitry Andric if (match(I->getOperand(1), m_APFloat(C)) && C->isNegative()) {
20338bcb0991SDimitry Andric Candidates.push_back(I);
20348bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "FMul with negative constant: " << *I << '\n');
20358bcb0991SDimitry Andric }
20368bcb0991SDimitry Andric getNegatibleInsts(I->getOperand(0), Candidates);
20378bcb0991SDimitry Andric getNegatibleInsts(I->getOperand(1), Candidates);
20388bcb0991SDimitry Andric break;
20398bcb0991SDimitry Andric case Instruction::FDiv:
20408bcb0991SDimitry Andric // Not expecting non-canonical code here. Bail out and wait.
20418bcb0991SDimitry Andric if (match(I->getOperand(0), m_Constant()) &&
20428bcb0991SDimitry Andric match(I->getOperand(1), m_Constant()))
20438bcb0991SDimitry Andric break;
20440b57cec5SDimitry Andric
20458bcb0991SDimitry Andric if ((match(I->getOperand(0), m_APFloat(C)) && C->isNegative()) ||
20468bcb0991SDimitry Andric (match(I->getOperand(1), m_APFloat(C)) && C->isNegative())) {
20478bcb0991SDimitry Andric Candidates.push_back(I);
20488bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "FDiv with negative constant: " << *I << '\n');
20498bcb0991SDimitry Andric }
20508bcb0991SDimitry Andric getNegatibleInsts(I->getOperand(0), Candidates);
20518bcb0991SDimitry Andric getNegatibleInsts(I->getOperand(1), Candidates);
20528bcb0991SDimitry Andric break;
20538bcb0991SDimitry Andric default:
20548bcb0991SDimitry Andric break;
20558bcb0991SDimitry Andric }
20568bcb0991SDimitry Andric }
20570b57cec5SDimitry Andric
20588bcb0991SDimitry Andric /// Given an fadd/fsub with an operand that is a one-use instruction
20598bcb0991SDimitry Andric /// (the fadd/fsub), try to change negative floating-point constants into
20608bcb0991SDimitry Andric /// positive constants to increase potential for reassociation and CSE.
canonicalizeNegFPConstantsForOp(Instruction * I,Instruction * Op,Value * OtherOp)20618bcb0991SDimitry Andric Instruction *ReassociatePass::canonicalizeNegFPConstantsForOp(Instruction *I,
20628bcb0991SDimitry Andric Instruction *Op,
20638bcb0991SDimitry Andric Value *OtherOp) {
20648bcb0991SDimitry Andric assert((I->getOpcode() == Instruction::FAdd ||
20658bcb0991SDimitry Andric I->getOpcode() == Instruction::FSub) && "Expected fadd/fsub");
20660b57cec5SDimitry Andric
20678bcb0991SDimitry Andric // Collect instructions with negative FP constants from the subtree that ends
20688bcb0991SDimitry Andric // in Op.
20698bcb0991SDimitry Andric SmallVector<Instruction *, 4> Candidates;
20708bcb0991SDimitry Andric getNegatibleInsts(Op, Candidates);
20718bcb0991SDimitry Andric if (Candidates.empty())
20720b57cec5SDimitry Andric return nullptr;
20730b57cec5SDimitry Andric
20740b57cec5SDimitry Andric // Don't canonicalize x + (-Constant * y) -> x - (Constant * y), if the
20750b57cec5SDimitry Andric // resulting subtract will be broken up later. This can get us into an
20760b57cec5SDimitry Andric // infinite loop during reassociation.
20778bcb0991SDimitry Andric bool IsFSub = I->getOpcode() == Instruction::FSub;
20788bcb0991SDimitry Andric bool NeedsSubtract = !IsFSub && Candidates.size() % 2 == 1;
20798bcb0991SDimitry Andric if (NeedsSubtract && ShouldBreakUpSubtract(I))
20800b57cec5SDimitry Andric return nullptr;
20810b57cec5SDimitry Andric
20828bcb0991SDimitry Andric for (Instruction *Negatible : Candidates) {
20838bcb0991SDimitry Andric const APFloat *C;
20848bcb0991SDimitry Andric if (match(Negatible->getOperand(0), m_APFloat(C))) {
20858bcb0991SDimitry Andric assert(!match(Negatible->getOperand(1), m_Constant()) &&
20868bcb0991SDimitry Andric "Expecting only 1 constant operand");
20878bcb0991SDimitry Andric assert(C->isNegative() && "Expected negative FP constant");
20888bcb0991SDimitry Andric Negatible->setOperand(0, ConstantFP::get(Negatible->getType(), abs(*C)));
20898bcb0991SDimitry Andric MadeChange = true;
20908bcb0991SDimitry Andric }
20918bcb0991SDimitry Andric if (match(Negatible->getOperand(1), m_APFloat(C))) {
20928bcb0991SDimitry Andric assert(!match(Negatible->getOperand(0), m_Constant()) &&
20938bcb0991SDimitry Andric "Expecting only 1 constant operand");
20948bcb0991SDimitry Andric assert(C->isNegative() && "Expected negative FP constant");
20958bcb0991SDimitry Andric Negatible->setOperand(1, ConstantFP::get(Negatible->getType(), abs(*C)));
20968bcb0991SDimitry Andric MadeChange = true;
20978bcb0991SDimitry Andric }
20988bcb0991SDimitry Andric }
20998bcb0991SDimitry Andric assert(MadeChange == true && "Negative constant candidate was not changed");
21000b57cec5SDimitry Andric
21018bcb0991SDimitry Andric // Negations cancelled out.
21028bcb0991SDimitry Andric if (Candidates.size() % 2 == 0)
21038bcb0991SDimitry Andric return I;
21040b57cec5SDimitry Andric
21058bcb0991SDimitry Andric // Negate the final operand in the expression by flipping the opcode of this
21068bcb0991SDimitry Andric // fadd/fsub.
21078bcb0991SDimitry Andric assert(Candidates.size() % 2 == 1 && "Expected odd number");
21088bcb0991SDimitry Andric IRBuilder<> Builder(I);
21098bcb0991SDimitry Andric Value *NewInst = IsFSub ? Builder.CreateFAddFMF(OtherOp, Op, I)
21108bcb0991SDimitry Andric : Builder.CreateFSubFMF(OtherOp, Op, I);
21118bcb0991SDimitry Andric I->replaceAllUsesWith(NewInst);
21128bcb0991SDimitry Andric RedoInsts.insert(I);
21138bcb0991SDimitry Andric return dyn_cast<Instruction>(NewInst);
21140b57cec5SDimitry Andric }
21150b57cec5SDimitry Andric
21168bcb0991SDimitry Andric /// Canonicalize expressions that contain a negative floating-point constant
21178bcb0991SDimitry Andric /// of the following form:
21188bcb0991SDimitry Andric /// OtherOp + (subtree) -> OtherOp {+/-} (canonical subtree)
21198bcb0991SDimitry Andric /// (subtree) + OtherOp -> OtherOp {+/-} (canonical subtree)
21208bcb0991SDimitry Andric /// OtherOp - (subtree) -> OtherOp {+/-} (canonical subtree)
21218bcb0991SDimitry Andric ///
21228bcb0991SDimitry Andric /// The fadd/fsub opcode may be switched to allow folding a negation into the
21238bcb0991SDimitry Andric /// input instruction.
canonicalizeNegFPConstants(Instruction * I)21248bcb0991SDimitry Andric Instruction *ReassociatePass::canonicalizeNegFPConstants(Instruction *I) {
21258bcb0991SDimitry Andric LLVM_DEBUG(dbgs() << "Combine negations for: " << *I << '\n');
21268bcb0991SDimitry Andric Value *X;
21278bcb0991SDimitry Andric Instruction *Op;
21288bcb0991SDimitry Andric if (match(I, m_FAdd(m_Value(X), m_OneUse(m_Instruction(Op)))))
21298bcb0991SDimitry Andric if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
21308bcb0991SDimitry Andric I = R;
21318bcb0991SDimitry Andric if (match(I, m_FAdd(m_OneUse(m_Instruction(Op)), m_Value(X))))
21328bcb0991SDimitry Andric if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
21338bcb0991SDimitry Andric I = R;
21348bcb0991SDimitry Andric if (match(I, m_FSub(m_Value(X), m_OneUse(m_Instruction(Op)))))
21358bcb0991SDimitry Andric if (Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
21368bcb0991SDimitry Andric I = R;
21378bcb0991SDimitry Andric return I;
21380b57cec5SDimitry Andric }
21390b57cec5SDimitry Andric
21400b57cec5SDimitry Andric /// Inspect and optimize the given instruction. Note that erasing
21410b57cec5SDimitry Andric /// instructions is not allowed.
OptimizeInst(Instruction * I)21420b57cec5SDimitry Andric void ReassociatePass::OptimizeInst(Instruction *I) {
21430b57cec5SDimitry Andric // Only consider operations that we understand.
21440b57cec5SDimitry Andric if (!isa<UnaryOperator>(I) && !isa<BinaryOperator>(I))
21450b57cec5SDimitry Andric return;
21460b57cec5SDimitry Andric
21470b57cec5SDimitry Andric if (I->getOpcode() == Instruction::Shl && isa<ConstantInt>(I->getOperand(1)))
21480b57cec5SDimitry Andric // If an operand of this shift is a reassociable multiply, or if the shift
21490b57cec5SDimitry Andric // is used by a reassociable multiply or add, turn into a multiply.
21500b57cec5SDimitry Andric if (isReassociableOp(I->getOperand(0), Instruction::Mul) ||
21510b57cec5SDimitry Andric (I->hasOneUse() &&
21520b57cec5SDimitry Andric (isReassociableOp(I->user_back(), Instruction::Mul) ||
21530b57cec5SDimitry Andric isReassociableOp(I->user_back(), Instruction::Add)))) {
21540b57cec5SDimitry Andric Instruction *NI = ConvertShiftToMul(I);
21550b57cec5SDimitry Andric RedoInsts.insert(I);
21560b57cec5SDimitry Andric MadeChange = true;
21570b57cec5SDimitry Andric I = NI;
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric
21600b57cec5SDimitry Andric // Commute binary operators, to canonicalize the order of their operands.
21610b57cec5SDimitry Andric // This can potentially expose more CSE opportunities, and makes writing other
21620b57cec5SDimitry Andric // transformations simpler.
21630b57cec5SDimitry Andric if (I->isCommutative())
21640b57cec5SDimitry Andric canonicalizeOperands(I);
21650b57cec5SDimitry Andric
21668bcb0991SDimitry Andric // Canonicalize negative constants out of expressions.
21678bcb0991SDimitry Andric if (Instruction *Res = canonicalizeNegFPConstants(I))
21688bcb0991SDimitry Andric I = Res;
21698bcb0991SDimitry Andric
2170fcaf7f86SDimitry Andric // Don't optimize floating-point instructions unless they have the
2171fcaf7f86SDimitry Andric // appropriate FastMathFlags for reassociation enabled.
2172972a253aSDimitry Andric if (isa<FPMathOperator>(I) && !hasFPAssociativeFlags(I))
21730b57cec5SDimitry Andric return;
21740b57cec5SDimitry Andric
21750b57cec5SDimitry Andric // Do not reassociate boolean (i1) expressions. We want to preserve the
21760b57cec5SDimitry Andric // original order of evaluation for short-circuited comparisons that
21770b57cec5SDimitry Andric // SimplifyCFG has folded to AND/OR expressions. If the expression
21780b57cec5SDimitry Andric // is not further optimized, it is likely to be transformed back to a
21790b57cec5SDimitry Andric // short-circuited form for code gen, and the source order may have been
21800b57cec5SDimitry Andric // optimized for the most likely conditions.
21810b57cec5SDimitry Andric if (I->getType()->isIntegerTy(1))
21820b57cec5SDimitry Andric return;
21830b57cec5SDimitry Andric
2184e8d8bef9SDimitry Andric // If this is a bitwise or instruction of operands
2185e8d8bef9SDimitry Andric // with no common bits set, convert it to X+Y.
2186e8d8bef9SDimitry Andric if (I->getOpcode() == Instruction::Or &&
2187fe6060f1SDimitry Andric shouldConvertOrWithNoCommonBitsToAdd(I) && !isLoadCombineCandidate(I) &&
21885f757f3fSDimitry Andric (cast<PossiblyDisjointInst>(I)->isDisjoint() ||
2189e8d8bef9SDimitry Andric haveNoCommonBitsSet(I->getOperand(0), I->getOperand(1),
2190*0fca6ea1SDimitry Andric SimplifyQuery(I->getDataLayout(),
21915f757f3fSDimitry Andric /*DT=*/nullptr, /*AC=*/nullptr, I)))) {
2192fe6060f1SDimitry Andric Instruction *NI = convertOrWithNoCommonBitsToAdd(I);
2193e8d8bef9SDimitry Andric RedoInsts.insert(I);
2194e8d8bef9SDimitry Andric MadeChange = true;
2195e8d8bef9SDimitry Andric I = NI;
2196e8d8bef9SDimitry Andric }
2197e8d8bef9SDimitry Andric
21980b57cec5SDimitry Andric // If this is a subtract instruction which is not already in negate form,
21990b57cec5SDimitry Andric // see if we can convert it to X+-Y.
22000b57cec5SDimitry Andric if (I->getOpcode() == Instruction::Sub) {
22010b57cec5SDimitry Andric if (ShouldBreakUpSubtract(I)) {
22020b57cec5SDimitry Andric Instruction *NI = BreakUpSubtract(I, RedoInsts);
22030b57cec5SDimitry Andric RedoInsts.insert(I);
22040b57cec5SDimitry Andric MadeChange = true;
22050b57cec5SDimitry Andric I = NI;
22060b57cec5SDimitry Andric } else if (match(I, m_Neg(m_Value()))) {
22070b57cec5SDimitry Andric // Otherwise, this is a negation. See if the operand is a multiply tree
22080b57cec5SDimitry Andric // and if this is not an inner node of a multiply tree.
22090b57cec5SDimitry Andric if (isReassociableOp(I->getOperand(1), Instruction::Mul) &&
22100b57cec5SDimitry Andric (!I->hasOneUse() ||
22110b57cec5SDimitry Andric !isReassociableOp(I->user_back(), Instruction::Mul))) {
22120b57cec5SDimitry Andric Instruction *NI = LowerNegateToMultiply(I);
22130b57cec5SDimitry Andric // If the negate was simplified, revisit the users to see if we can
22140b57cec5SDimitry Andric // reassociate further.
22150b57cec5SDimitry Andric for (User *U : NI->users()) {
22160b57cec5SDimitry Andric if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
22170b57cec5SDimitry Andric RedoInsts.insert(Tmp);
22180b57cec5SDimitry Andric }
22190b57cec5SDimitry Andric RedoInsts.insert(I);
22200b57cec5SDimitry Andric MadeChange = true;
22210b57cec5SDimitry Andric I = NI;
22220b57cec5SDimitry Andric }
22230b57cec5SDimitry Andric }
22240b57cec5SDimitry Andric } else if (I->getOpcode() == Instruction::FNeg ||
22250b57cec5SDimitry Andric I->getOpcode() == Instruction::FSub) {
22260b57cec5SDimitry Andric if (ShouldBreakUpSubtract(I)) {
22270b57cec5SDimitry Andric Instruction *NI = BreakUpSubtract(I, RedoInsts);
22280b57cec5SDimitry Andric RedoInsts.insert(I);
22290b57cec5SDimitry Andric MadeChange = true;
22300b57cec5SDimitry Andric I = NI;
22310b57cec5SDimitry Andric } else if (match(I, m_FNeg(m_Value()))) {
22320b57cec5SDimitry Andric // Otherwise, this is a negation. See if the operand is a multiply tree
22330b57cec5SDimitry Andric // and if this is not an inner node of a multiply tree.
22340b57cec5SDimitry Andric Value *Op = isa<BinaryOperator>(I) ? I->getOperand(1) :
22350b57cec5SDimitry Andric I->getOperand(0);
22360b57cec5SDimitry Andric if (isReassociableOp(Op, Instruction::FMul) &&
22370b57cec5SDimitry Andric (!I->hasOneUse() ||
22380b57cec5SDimitry Andric !isReassociableOp(I->user_back(), Instruction::FMul))) {
22390b57cec5SDimitry Andric // If the negate was simplified, revisit the users to see if we can
22400b57cec5SDimitry Andric // reassociate further.
22410b57cec5SDimitry Andric Instruction *NI = LowerNegateToMultiply(I);
22420b57cec5SDimitry Andric for (User *U : NI->users()) {
22430b57cec5SDimitry Andric if (BinaryOperator *Tmp = dyn_cast<BinaryOperator>(U))
22440b57cec5SDimitry Andric RedoInsts.insert(Tmp);
22450b57cec5SDimitry Andric }
22460b57cec5SDimitry Andric RedoInsts.insert(I);
22470b57cec5SDimitry Andric MadeChange = true;
22480b57cec5SDimitry Andric I = NI;
22490b57cec5SDimitry Andric }
22500b57cec5SDimitry Andric }
22510b57cec5SDimitry Andric }
22520b57cec5SDimitry Andric
22530b57cec5SDimitry Andric // If this instruction is an associative binary operator, process it.
22540b57cec5SDimitry Andric if (!I->isAssociative()) return;
22550b57cec5SDimitry Andric BinaryOperator *BO = cast<BinaryOperator>(I);
22560b57cec5SDimitry Andric
22570b57cec5SDimitry Andric // If this is an interior node of a reassociable tree, ignore it until we
22580b57cec5SDimitry Andric // get to the root of the tree, to avoid N^2 analysis.
22590b57cec5SDimitry Andric unsigned Opcode = BO->getOpcode();
22600b57cec5SDimitry Andric if (BO->hasOneUse() && BO->user_back()->getOpcode() == Opcode) {
22610b57cec5SDimitry Andric // During the initial run we will get to the root of the tree.
22620b57cec5SDimitry Andric // But if we get here while we are redoing instructions, there is no
22630b57cec5SDimitry Andric // guarantee that the root will be visited. So Redo later
22640b57cec5SDimitry Andric if (BO->user_back() != BO &&
22650b57cec5SDimitry Andric BO->getParent() == BO->user_back()->getParent())
22660b57cec5SDimitry Andric RedoInsts.insert(BO->user_back());
22670b57cec5SDimitry Andric return;
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric
22700b57cec5SDimitry Andric // If this is an add tree that is used by a sub instruction, ignore it
22710b57cec5SDimitry Andric // until we process the subtract.
22720b57cec5SDimitry Andric if (BO->hasOneUse() && BO->getOpcode() == Instruction::Add &&
22730b57cec5SDimitry Andric cast<Instruction>(BO->user_back())->getOpcode() == Instruction::Sub)
22740b57cec5SDimitry Andric return;
22750b57cec5SDimitry Andric if (BO->hasOneUse() && BO->getOpcode() == Instruction::FAdd &&
22760b57cec5SDimitry Andric cast<Instruction>(BO->user_back())->getOpcode() == Instruction::FSub)
22770b57cec5SDimitry Andric return;
22780b57cec5SDimitry Andric
22790b57cec5SDimitry Andric ReassociateExpression(BO);
22800b57cec5SDimitry Andric }
22810b57cec5SDimitry Andric
ReassociateExpression(BinaryOperator * I)22820b57cec5SDimitry Andric void ReassociatePass::ReassociateExpression(BinaryOperator *I) {
22830b57cec5SDimitry Andric // First, walk the expression tree, linearizing the tree, collecting the
22840b57cec5SDimitry Andric // operand information.
22850b57cec5SDimitry Andric SmallVector<RepeatedValue, 8> Tree;
2286*0fca6ea1SDimitry Andric OverflowTracking Flags;
2287*0fca6ea1SDimitry Andric MadeChange |= LinearizeExprTree(I, Tree, RedoInsts, Flags);
22880b57cec5SDimitry Andric SmallVector<ValueEntry, 8> Ops;
22890b57cec5SDimitry Andric Ops.reserve(Tree.size());
22904824e7fdSDimitry Andric for (const RepeatedValue &E : Tree)
2291*0fca6ea1SDimitry Andric Ops.append(E.second, ValueEntry(getRank(E.first), E.first));
22920b57cec5SDimitry Andric
22930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RAIn:\t"; PrintOps(I, Ops); dbgs() << '\n');
22940b57cec5SDimitry Andric
22950b57cec5SDimitry Andric // Now that we have linearized the tree to a list and have gathered all of
22960b57cec5SDimitry Andric // the operands and their ranks, sort the operands by their rank. Use a
22970b57cec5SDimitry Andric // stable_sort so that values with equal ranks will have their relative
22980b57cec5SDimitry Andric // positions maintained (and so the compiler is deterministic). Note that
22990b57cec5SDimitry Andric // this sorts so that the highest ranking values end up at the beginning of
23000b57cec5SDimitry Andric // the vector.
23010b57cec5SDimitry Andric llvm::stable_sort(Ops);
23020b57cec5SDimitry Andric
23030b57cec5SDimitry Andric // Now that we have the expression tree in a convenient
23040b57cec5SDimitry Andric // sorted form, optimize it globally if possible.
23050b57cec5SDimitry Andric if (Value *V = OptimizeExpression(I, Ops)) {
23060b57cec5SDimitry Andric if (V == I)
23070b57cec5SDimitry Andric // Self-referential expression in unreachable code.
23080b57cec5SDimitry Andric return;
23090b57cec5SDimitry Andric // This expression tree simplified to something that isn't a tree,
23100b57cec5SDimitry Andric // eliminate it.
23110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Reassoc to scalar: " << *V << '\n');
23120b57cec5SDimitry Andric I->replaceAllUsesWith(V);
23130b57cec5SDimitry Andric if (Instruction *VI = dyn_cast<Instruction>(V))
23140b57cec5SDimitry Andric if (I->getDebugLoc())
23150b57cec5SDimitry Andric VI->setDebugLoc(I->getDebugLoc());
23160b57cec5SDimitry Andric RedoInsts.insert(I);
23170b57cec5SDimitry Andric ++NumAnnihil;
23180b57cec5SDimitry Andric return;
23190b57cec5SDimitry Andric }
23200b57cec5SDimitry Andric
23210b57cec5SDimitry Andric // We want to sink immediates as deeply as possible except in the case where
23220b57cec5SDimitry Andric // this is a multiply tree used only by an add, and the immediate is a -1.
23230b57cec5SDimitry Andric // In this case we reassociate to put the negation on the outside so that we
23240b57cec5SDimitry Andric // can fold the negation into the add: (-X)*Y + Z -> Z-X*Y
23250b57cec5SDimitry Andric if (I->hasOneUse()) {
23260b57cec5SDimitry Andric if (I->getOpcode() == Instruction::Mul &&
23270b57cec5SDimitry Andric cast<Instruction>(I->user_back())->getOpcode() == Instruction::Add &&
23280b57cec5SDimitry Andric isa<ConstantInt>(Ops.back().Op) &&
23290b57cec5SDimitry Andric cast<ConstantInt>(Ops.back().Op)->isMinusOne()) {
23300b57cec5SDimitry Andric ValueEntry Tmp = Ops.pop_back_val();
23310b57cec5SDimitry Andric Ops.insert(Ops.begin(), Tmp);
23320b57cec5SDimitry Andric } else if (I->getOpcode() == Instruction::FMul &&
23330b57cec5SDimitry Andric cast<Instruction>(I->user_back())->getOpcode() ==
23340b57cec5SDimitry Andric Instruction::FAdd &&
23350b57cec5SDimitry Andric isa<ConstantFP>(Ops.back().Op) &&
23360b57cec5SDimitry Andric cast<ConstantFP>(Ops.back().Op)->isExactlyValue(-1.0)) {
23370b57cec5SDimitry Andric ValueEntry Tmp = Ops.pop_back_val();
23380b57cec5SDimitry Andric Ops.insert(Ops.begin(), Tmp);
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric
23420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RAOut:\t"; PrintOps(I, Ops); dbgs() << '\n');
23430b57cec5SDimitry Andric
23440b57cec5SDimitry Andric if (Ops.size() == 1) {
23450b57cec5SDimitry Andric if (Ops[0].Op == I)
23460b57cec5SDimitry Andric // Self-referential expression in unreachable code.
23470b57cec5SDimitry Andric return;
23480b57cec5SDimitry Andric
23490b57cec5SDimitry Andric // This expression tree simplified to something that isn't a tree,
23500b57cec5SDimitry Andric // eliminate it.
23510b57cec5SDimitry Andric I->replaceAllUsesWith(Ops[0].Op);
23520b57cec5SDimitry Andric if (Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
23530b57cec5SDimitry Andric OI->setDebugLoc(I->getDebugLoc());
23540b57cec5SDimitry Andric RedoInsts.insert(I);
23550b57cec5SDimitry Andric return;
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric
23580b57cec5SDimitry Andric if (Ops.size() > 2 && Ops.size() <= GlobalReassociateLimit) {
23590b57cec5SDimitry Andric // Find the pair with the highest count in the pairmap and move it to the
23600b57cec5SDimitry Andric // back of the list so that it can later be CSE'd.
23610b57cec5SDimitry Andric // example:
23620b57cec5SDimitry Andric // a*b*c*d*e
23630b57cec5SDimitry Andric // if c*e is the most "popular" pair, we can express this as
23640b57cec5SDimitry Andric // (((c*e)*d)*b)*a
23650b57cec5SDimitry Andric unsigned Max = 1;
23660b57cec5SDimitry Andric unsigned BestRank = 0;
23670b57cec5SDimitry Andric std::pair<unsigned, unsigned> BestPair;
23680b57cec5SDimitry Andric unsigned Idx = I->getOpcode() - Instruction::BinaryOpsBegin;
236906c3fb27SDimitry Andric unsigned LimitIdx = 0;
237006c3fb27SDimitry Andric // With the CSE-driven heuristic, we are about to slap two values at the
237106c3fb27SDimitry Andric // beginning of the expression whereas they could live very late in the CFG.
237206c3fb27SDimitry Andric // When using the CSE-local heuristic we avoid creating dependences from
237306c3fb27SDimitry Andric // completely unrelated part of the CFG by limiting the expression
237406c3fb27SDimitry Andric // reordering on the values that live in the first seen basic block.
237506c3fb27SDimitry Andric // The main idea is that we want to avoid forming expressions that would
237606c3fb27SDimitry Andric // become loop dependent.
237706c3fb27SDimitry Andric if (UseCSELocalOpt) {
237806c3fb27SDimitry Andric const BasicBlock *FirstSeenBB = nullptr;
237906c3fb27SDimitry Andric int StartIdx = Ops.size() - 1;
238006c3fb27SDimitry Andric // Skip the first value of the expression since we need at least two
238106c3fb27SDimitry Andric // values to materialize an expression. I.e., even if this value is
238206c3fb27SDimitry Andric // anchored in a different basic block, the actual first sub expression
238306c3fb27SDimitry Andric // will be anchored on the second value.
238406c3fb27SDimitry Andric for (int i = StartIdx - 1; i != -1; --i) {
238506c3fb27SDimitry Andric const Value *Val = Ops[i].Op;
238606c3fb27SDimitry Andric const auto *CurrLeafInstr = dyn_cast<Instruction>(Val);
238706c3fb27SDimitry Andric const BasicBlock *SeenBB = nullptr;
238806c3fb27SDimitry Andric if (!CurrLeafInstr) {
238906c3fb27SDimitry Andric // The value is free of any CFG dependencies.
239006c3fb27SDimitry Andric // Do as if it lives in the entry block.
239106c3fb27SDimitry Andric //
239206c3fb27SDimitry Andric // We do this to make sure all the values falling on this path are
239306c3fb27SDimitry Andric // seen through the same anchor point. The rationale is these values
239406c3fb27SDimitry Andric // can be combined together to from a sub expression free of any CFG
239506c3fb27SDimitry Andric // dependencies so we want them to stay together.
239606c3fb27SDimitry Andric // We could be cleverer and postpone the anchor down to the first
239706c3fb27SDimitry Andric // anchored value, but that's likely complicated to get right.
239806c3fb27SDimitry Andric // E.g., we wouldn't want to do that if that means being stuck in a
239906c3fb27SDimitry Andric // loop.
240006c3fb27SDimitry Andric //
240106c3fb27SDimitry Andric // For instance, we wouldn't want to change:
240206c3fb27SDimitry Andric // res = arg1 op arg2 op arg3 op ... op loop_val1 op loop_val2 ...
240306c3fb27SDimitry Andric // into
240406c3fb27SDimitry Andric // res = loop_val1 op arg1 op arg2 op arg3 op ... op loop_val2 ...
240506c3fb27SDimitry Andric // Because all the sub expressions with arg2..N would be stuck between
240606c3fb27SDimitry Andric // two loop dependent values.
240706c3fb27SDimitry Andric SeenBB = &I->getParent()->getParent()->getEntryBlock();
240806c3fb27SDimitry Andric } else {
240906c3fb27SDimitry Andric SeenBB = CurrLeafInstr->getParent();
241006c3fb27SDimitry Andric }
241106c3fb27SDimitry Andric
241206c3fb27SDimitry Andric if (!FirstSeenBB) {
241306c3fb27SDimitry Andric FirstSeenBB = SeenBB;
241406c3fb27SDimitry Andric continue;
241506c3fb27SDimitry Andric }
241606c3fb27SDimitry Andric if (FirstSeenBB != SeenBB) {
241706c3fb27SDimitry Andric // ith value is in a different basic block.
241806c3fb27SDimitry Andric // Rewind the index once to point to the last value on the same basic
241906c3fb27SDimitry Andric // block.
242006c3fb27SDimitry Andric LimitIdx = i + 1;
242106c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "CSE reordering: Consider values between ["
242206c3fb27SDimitry Andric << LimitIdx << ", " << StartIdx << "]\n");
242306c3fb27SDimitry Andric break;
242406c3fb27SDimitry Andric }
242506c3fb27SDimitry Andric }
242606c3fb27SDimitry Andric }
242706c3fb27SDimitry Andric for (unsigned i = Ops.size() - 1; i > LimitIdx; --i) {
242806c3fb27SDimitry Andric // We must use int type to go below zero when LimitIdx is 0.
242906c3fb27SDimitry Andric for (int j = i - 1; j >= (int)LimitIdx; --j) {
24300b57cec5SDimitry Andric unsigned Score = 0;
24310b57cec5SDimitry Andric Value *Op0 = Ops[i].Op;
24320b57cec5SDimitry Andric Value *Op1 = Ops[j].Op;
24330b57cec5SDimitry Andric if (std::less<Value *>()(Op1, Op0))
24340b57cec5SDimitry Andric std::swap(Op0, Op1);
24350b57cec5SDimitry Andric auto it = PairMap[Idx].find({Op0, Op1});
24360b57cec5SDimitry Andric if (it != PairMap[Idx].end()) {
24370b57cec5SDimitry Andric // Functions like BreakUpSubtract() can erase the Values we're using
24380b57cec5SDimitry Andric // as keys and create new Values after we built the PairMap. There's a
24390b57cec5SDimitry Andric // small chance that the new nodes can have the same address as
24400b57cec5SDimitry Andric // something already in the table. We shouldn't accumulate the stored
24410b57cec5SDimitry Andric // score in that case as it refers to the wrong Value.
24420b57cec5SDimitry Andric if (it->second.isValid())
24430b57cec5SDimitry Andric Score += it->second.Score;
24440b57cec5SDimitry Andric }
24450b57cec5SDimitry Andric
24460b57cec5SDimitry Andric unsigned MaxRank = std::max(Ops[i].Rank, Ops[j].Rank);
244706c3fb27SDimitry Andric
244806c3fb27SDimitry Andric // By construction, the operands are sorted in reverse order of their
244906c3fb27SDimitry Andric // topological order.
245006c3fb27SDimitry Andric // So we tend to form (sub) expressions with values that are close to
245106c3fb27SDimitry Andric // each other.
245206c3fb27SDimitry Andric //
245306c3fb27SDimitry Andric // Now to expose more CSE opportunities we want to expose the pair of
245406c3fb27SDimitry Andric // operands that occur the most (as statically computed in
245506c3fb27SDimitry Andric // BuildPairMap.) as the first sub-expression.
245606c3fb27SDimitry Andric //
245706c3fb27SDimitry Andric // If two pairs occur as many times, we pick the one with the
245806c3fb27SDimitry Andric // lowest rank, meaning the one with both operands appearing first in
245906c3fb27SDimitry Andric // the topological order.
24600b57cec5SDimitry Andric if (Score > Max || (Score == Max && MaxRank < BestRank)) {
246106c3fb27SDimitry Andric BestPair = {j, i};
24620b57cec5SDimitry Andric Max = Score;
24630b57cec5SDimitry Andric BestRank = MaxRank;
24640b57cec5SDimitry Andric }
24650b57cec5SDimitry Andric }
246606c3fb27SDimitry Andric }
24670b57cec5SDimitry Andric if (Max > 1) {
24680b57cec5SDimitry Andric auto Op0 = Ops[BestPair.first];
24690b57cec5SDimitry Andric auto Op1 = Ops[BestPair.second];
24700b57cec5SDimitry Andric Ops.erase(&Ops[BestPair.second]);
24710b57cec5SDimitry Andric Ops.erase(&Ops[BestPair.first]);
24720b57cec5SDimitry Andric Ops.push_back(Op0);
24730b57cec5SDimitry Andric Ops.push_back(Op1);
24740b57cec5SDimitry Andric }
24750b57cec5SDimitry Andric }
247606c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "RAOut after CSE reorder:\t"; PrintOps(I, Ops);
247706c3fb27SDimitry Andric dbgs() << '\n');
24780b57cec5SDimitry Andric // Now that we ordered and optimized the expressions, splat them back into
24790b57cec5SDimitry Andric // the expression tree, removing any unneeded nodes.
2480*0fca6ea1SDimitry Andric RewriteExprTree(I, Ops, Flags);
24810b57cec5SDimitry Andric }
24820b57cec5SDimitry Andric
24830b57cec5SDimitry Andric void
BuildPairMap(ReversePostOrderTraversal<Function * > & RPOT)24840b57cec5SDimitry Andric ReassociatePass::BuildPairMap(ReversePostOrderTraversal<Function *> &RPOT) {
24850b57cec5SDimitry Andric // Make a "pairmap" of how often each operand pair occurs.
24860b57cec5SDimitry Andric for (BasicBlock *BI : RPOT) {
24870b57cec5SDimitry Andric for (Instruction &I : *BI) {
24885f757f3fSDimitry Andric if (!I.isAssociative() || !I.isBinaryOp())
24890b57cec5SDimitry Andric continue;
24900b57cec5SDimitry Andric
24910b57cec5SDimitry Andric // Ignore nodes that aren't at the root of trees.
24920b57cec5SDimitry Andric if (I.hasOneUse() && I.user_back()->getOpcode() == I.getOpcode())
24930b57cec5SDimitry Andric continue;
24940b57cec5SDimitry Andric
24950b57cec5SDimitry Andric // Collect all operands in a single reassociable expression.
24960b57cec5SDimitry Andric // Since Reassociate has already been run once, we can assume things
24970b57cec5SDimitry Andric // are already canonical according to Reassociation's regime.
24980b57cec5SDimitry Andric SmallVector<Value *, 8> Worklist = { I.getOperand(0), I.getOperand(1) };
24990b57cec5SDimitry Andric SmallVector<Value *, 8> Ops;
25000b57cec5SDimitry Andric while (!Worklist.empty() && Ops.size() <= GlobalReassociateLimit) {
25010b57cec5SDimitry Andric Value *Op = Worklist.pop_back_val();
25020b57cec5SDimitry Andric Instruction *OpI = dyn_cast<Instruction>(Op);
25030b57cec5SDimitry Andric if (!OpI || OpI->getOpcode() != I.getOpcode() || !OpI->hasOneUse()) {
25040b57cec5SDimitry Andric Ops.push_back(Op);
25050b57cec5SDimitry Andric continue;
25060b57cec5SDimitry Andric }
25070b57cec5SDimitry Andric // Be paranoid about self-referencing expressions in unreachable code.
25080b57cec5SDimitry Andric if (OpI->getOperand(0) != OpI)
25090b57cec5SDimitry Andric Worklist.push_back(OpI->getOperand(0));
25100b57cec5SDimitry Andric if (OpI->getOperand(1) != OpI)
25110b57cec5SDimitry Andric Worklist.push_back(OpI->getOperand(1));
25120b57cec5SDimitry Andric }
25130b57cec5SDimitry Andric // Skip extremely long expressions.
25140b57cec5SDimitry Andric if (Ops.size() > GlobalReassociateLimit)
25150b57cec5SDimitry Andric continue;
25160b57cec5SDimitry Andric
25170b57cec5SDimitry Andric // Add all pairwise combinations of operands to the pair map.
25180b57cec5SDimitry Andric unsigned BinaryIdx = I.getOpcode() - Instruction::BinaryOpsBegin;
25190b57cec5SDimitry Andric SmallSet<std::pair<Value *, Value*>, 32> Visited;
25200b57cec5SDimitry Andric for (unsigned i = 0; i < Ops.size() - 1; ++i) {
25210b57cec5SDimitry Andric for (unsigned j = i + 1; j < Ops.size(); ++j) {
25220b57cec5SDimitry Andric // Canonicalize operand orderings.
25230b57cec5SDimitry Andric Value *Op0 = Ops[i];
25240b57cec5SDimitry Andric Value *Op1 = Ops[j];
25250b57cec5SDimitry Andric if (std::less<Value *>()(Op1, Op0))
25260b57cec5SDimitry Andric std::swap(Op0, Op1);
25270b57cec5SDimitry Andric if (!Visited.insert({Op0, Op1}).second)
25280b57cec5SDimitry Andric continue;
25290b57cec5SDimitry Andric auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, {Op0, Op1, 1}});
25300b57cec5SDimitry Andric if (!res.second) {
25310b57cec5SDimitry Andric // If either key value has been erased then we've got the same
25320b57cec5SDimitry Andric // address by coincidence. That can't happen here because nothing is
25330b57cec5SDimitry Andric // erasing values but it can happen by the time we're querying the
25340b57cec5SDimitry Andric // map.
25350b57cec5SDimitry Andric assert(res.first->second.isValid() && "WeakVH invalidated");
25360b57cec5SDimitry Andric ++res.first->second.Score;
25370b57cec5SDimitry Andric }
25380b57cec5SDimitry Andric }
25390b57cec5SDimitry Andric }
25400b57cec5SDimitry Andric }
25410b57cec5SDimitry Andric }
25420b57cec5SDimitry Andric }
25430b57cec5SDimitry Andric
run(Function & F,FunctionAnalysisManager &)25440b57cec5SDimitry Andric PreservedAnalyses ReassociatePass::run(Function &F, FunctionAnalysisManager &) {
25450b57cec5SDimitry Andric // Get the functions basic blocks in Reverse Post Order. This order is used by
25460b57cec5SDimitry Andric // BuildRankMap to pre calculate ranks correctly. It also excludes dead basic
25470b57cec5SDimitry Andric // blocks (it has been seen that the analysis in this pass could hang when
25480b57cec5SDimitry Andric // analysing dead basic blocks).
25490b57cec5SDimitry Andric ReversePostOrderTraversal<Function *> RPOT(&F);
25500b57cec5SDimitry Andric
25510b57cec5SDimitry Andric // Calculate the rank map for F.
25520b57cec5SDimitry Andric BuildRankMap(F, RPOT);
25530b57cec5SDimitry Andric
25540b57cec5SDimitry Andric // Build the pair map before running reassociate.
25550b57cec5SDimitry Andric // Technically this would be more accurate if we did it after one round
25560b57cec5SDimitry Andric // of reassociation, but in practice it doesn't seem to help much on
25570b57cec5SDimitry Andric // real-world code, so don't waste the compile time running reassociate
25580b57cec5SDimitry Andric // twice.
25590b57cec5SDimitry Andric // If a user wants, they could expicitly run reassociate twice in their
25600b57cec5SDimitry Andric // pass pipeline for further potential gains.
25610b57cec5SDimitry Andric // It might also be possible to update the pair map during runtime, but the
25620b57cec5SDimitry Andric // overhead of that may be large if there's many reassociable chains.
25630b57cec5SDimitry Andric BuildPairMap(RPOT);
25640b57cec5SDimitry Andric
25650b57cec5SDimitry Andric MadeChange = false;
25660b57cec5SDimitry Andric
25670b57cec5SDimitry Andric // Traverse the same blocks that were analysed by BuildRankMap.
25680b57cec5SDimitry Andric for (BasicBlock *BI : RPOT) {
25690b57cec5SDimitry Andric assert(RankMap.count(&*BI) && "BB should be ranked.");
25700b57cec5SDimitry Andric // Optimize every instruction in the basic block.
25710b57cec5SDimitry Andric for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;)
25720b57cec5SDimitry Andric if (isInstructionTriviallyDead(&*II)) {
25730b57cec5SDimitry Andric EraseInst(&*II++);
25740b57cec5SDimitry Andric } else {
25750b57cec5SDimitry Andric OptimizeInst(&*II);
25760b57cec5SDimitry Andric assert(II->getParent() == &*BI && "Moved to a different block!");
25770b57cec5SDimitry Andric ++II;
25780b57cec5SDimitry Andric }
25790b57cec5SDimitry Andric
25800b57cec5SDimitry Andric // Make a copy of all the instructions to be redone so we can remove dead
25810b57cec5SDimitry Andric // instructions.
25820b57cec5SDimitry Andric OrderedSet ToRedo(RedoInsts);
25830b57cec5SDimitry Andric // Iterate over all instructions to be reevaluated and remove trivially dead
25840b57cec5SDimitry Andric // instructions. If any operand of the trivially dead instruction becomes
25850b57cec5SDimitry Andric // dead mark it for deletion as well. Continue this process until all
25860b57cec5SDimitry Andric // trivially dead instructions have been removed.
25870b57cec5SDimitry Andric while (!ToRedo.empty()) {
25880b57cec5SDimitry Andric Instruction *I = ToRedo.pop_back_val();
25890b57cec5SDimitry Andric if (isInstructionTriviallyDead(I)) {
25900b57cec5SDimitry Andric RecursivelyEraseDeadInsts(I, ToRedo);
25910b57cec5SDimitry Andric MadeChange = true;
25920b57cec5SDimitry Andric }
25930b57cec5SDimitry Andric }
25940b57cec5SDimitry Andric
25950b57cec5SDimitry Andric // Now that we have removed dead instructions, we can reoptimize the
25960b57cec5SDimitry Andric // remaining instructions.
25970b57cec5SDimitry Andric while (!RedoInsts.empty()) {
25980b57cec5SDimitry Andric Instruction *I = RedoInsts.front();
25990b57cec5SDimitry Andric RedoInsts.erase(RedoInsts.begin());
26000b57cec5SDimitry Andric if (isInstructionTriviallyDead(I))
26010b57cec5SDimitry Andric EraseInst(I);
26020b57cec5SDimitry Andric else
26030b57cec5SDimitry Andric OptimizeInst(I);
26040b57cec5SDimitry Andric }
26050b57cec5SDimitry Andric }
26060b57cec5SDimitry Andric
26070b57cec5SDimitry Andric // We are done with the rank map and pair map.
26080b57cec5SDimitry Andric RankMap.clear();
26090b57cec5SDimitry Andric ValueRankMap.clear();
26100b57cec5SDimitry Andric for (auto &Entry : PairMap)
26110b57cec5SDimitry Andric Entry.clear();
26120b57cec5SDimitry Andric
26130b57cec5SDimitry Andric if (MadeChange) {
26140b57cec5SDimitry Andric PreservedAnalyses PA;
26150b57cec5SDimitry Andric PA.preserveSet<CFGAnalyses>();
26160b57cec5SDimitry Andric return PA;
26170b57cec5SDimitry Andric }
26180b57cec5SDimitry Andric
26190b57cec5SDimitry Andric return PreservedAnalyses::all();
26200b57cec5SDimitry Andric }
26210b57cec5SDimitry Andric
26220b57cec5SDimitry Andric namespace {
26230b57cec5SDimitry Andric
26240b57cec5SDimitry Andric class ReassociateLegacyPass : public FunctionPass {
26250b57cec5SDimitry Andric ReassociatePass Impl;
26260b57cec5SDimitry Andric
26270b57cec5SDimitry Andric public:
26280b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid
26290b57cec5SDimitry Andric
ReassociateLegacyPass()26300b57cec5SDimitry Andric ReassociateLegacyPass() : FunctionPass(ID) {
26310b57cec5SDimitry Andric initializeReassociateLegacyPassPass(*PassRegistry::getPassRegistry());
26320b57cec5SDimitry Andric }
26330b57cec5SDimitry Andric
runOnFunction(Function & F)26340b57cec5SDimitry Andric bool runOnFunction(Function &F) override {
26350b57cec5SDimitry Andric if (skipFunction(F))
26360b57cec5SDimitry Andric return false;
26370b57cec5SDimitry Andric
26380b57cec5SDimitry Andric FunctionAnalysisManager DummyFAM;
26390b57cec5SDimitry Andric auto PA = Impl.run(F, DummyFAM);
26400b57cec5SDimitry Andric return !PA.areAllPreserved();
26410b57cec5SDimitry Andric }
26420b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const26430b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
26440b57cec5SDimitry Andric AU.setPreservesCFG();
26455ffd83dbSDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
26465ffd83dbSDimitry Andric AU.addPreserved<BasicAAWrapperPass>();
26470b57cec5SDimitry Andric AU.addPreserved<GlobalsAAWrapperPass>();
26480b57cec5SDimitry Andric }
26490b57cec5SDimitry Andric };
26500b57cec5SDimitry Andric
26510b57cec5SDimitry Andric } // end anonymous namespace
26520b57cec5SDimitry Andric
26530b57cec5SDimitry Andric char ReassociateLegacyPass::ID = 0;
26540b57cec5SDimitry Andric
26550b57cec5SDimitry Andric INITIALIZE_PASS(ReassociateLegacyPass, "reassociate",
26560b57cec5SDimitry Andric "Reassociate expressions", false, false)
26570b57cec5SDimitry Andric
26580b57cec5SDimitry Andric // Public interface to the Reassociate pass
createReassociatePass()26590b57cec5SDimitry Andric FunctionPass *llvm::createReassociatePass() {
26600b57cec5SDimitry Andric return new ReassociateLegacyPass();
26610b57cec5SDimitry Andric }
2662