68 #define DEBUG_TYPE "reassociate" 70 STATISTIC(NumChanged,
"Number of insts reassociated");
71 STATISTIC(NumAnnihil,
"Number of expr tree annihilated");
72 STATISTIC(NumFactor ,
"Number of multiplies factored");
79 << *Ops[0].
Op->getType() <<
'\t';
80 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
82 Ops[i].Op->printAsOperand(
dbgs(),
false, M);
83 dbgs() <<
", #" << Ops[i].Rank <<
"] ";
100 bool isInvalid()
const {
return SymbolicPart ==
nullptr; }
114 unsigned SymbolicRank;
119 assert(!isa<ConstantInt>(V) &&
"No ConstantInt");
124 if (I && (I->
getOpcode() == Instruction::Or ||
135 isOr = (I->
getOpcode() == Instruction::Or);
150 if (
I &&
I->hasOneUse() &&
I->getOpcode() == Opcode)
151 if (!isa<FPMathOperator>(
I) ||
I->isFast())
152 return cast<BinaryOperator>(
I);
159 if (
I &&
I->hasOneUse() &&
160 (
I->getOpcode() == Opcode1 ||
I->getOpcode() == Opcode2))
161 if (!isa<FPMathOperator>(
I) ||
I->isFast())
162 return cast<BinaryOperator>(
I);
166 void ReassociatePass::BuildRankMap(
Function &
F,
172 ValueRankMap[&
Arg] = ++Rank;
179 unsigned BBRank = RankMap[BB] = ++Rank << 16;
186 ValueRankMap[&
I] = ++BBRank;
190 unsigned ReassociatePass::getRank(
Value *V) {
193 if (isa<Argument>(V))
return ValueRankMap[V];
197 if (
unsigned Rank = ValueRankMap[I])
204 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
205 for (
unsigned i = 0,
e = I->getNumOperands(); i !=
e && Rank != MaxRank; ++i)
206 Rank =
std::max(Rank, getRank(I->getOperand(i)));
217 return ValueRankMap[
I] = Rank;
221 void ReassociatePass::canonicalizeOperands(
Instruction *
I) {
222 assert(isa<BinaryOperator>(I) &&
"Expected binary operator.");
227 if (LHS == RHS || isa<Constant>(RHS))
229 if (isa<Constant>(LHS) || getRank(RHS) < getRank(LHS))
230 cast<BinaryOperator>(
I)->swapOperands();
239 BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
251 BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
270 assert((isa<UnaryOperator>(Neg) || isa<BinaryOperator>(Neg)) &&
271 "Expected a Negate!");
273 unsigned OpNo = isa<BinaryOperator>(Neg) ? 1 : 0;
275 Constant *NegOne = Ty->isIntOrIntVectorTy() ?
281 Neg->replaceAllUsesWith(Res);
326 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
331 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
341 assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
342 "Unknown associative operation!");
358 assert(LHS.
ult(Threshold) && RHS.
ult(Threshold) &&
"Weights not reduced!");
361 while (LHS.uge(Threshold))
369 "Weights not reduced!");
371 while (Total >= Threshold)
454 assert((isa<UnaryOperator>(I) || isa<BinaryOperator>(I)) &&
455 "Expected a UnaryOperator or BinaryOperator!");
460 "Expected an associative and commutative operation!");
474 bool Changed =
false;
498 while (!Worklist.empty()) {
499 std::pair<Instruction*, APInt>
P = Worklist.pop_back_val();
504 APInt Weight = P.second;
505 LLVM_DEBUG(
dbgs() <<
"OPERAND: " << *Op <<
" (" << Weight <<
")\n");
511 assert(Visited.
insert(Op).second &&
"Not first visit!");
512 LLVM_DEBUG(
dbgs() <<
"DIRECT ADD: " << *Op <<
" (" << Weight <<
")\n");
513 Worklist.push_back(std::make_pair(BO, Weight));
518 LeafMap::iterator It = Leaves.find(Op);
519 if (It == Leaves.end()) {
521 assert(Visited.
insert(Op).second &&
"Not first visit!");
526 <<
"ADD USES LEAF: " << *Op <<
" (" << Weight <<
")\n");
535 "In leaf map but not visited!");
540 #if 0 // TODO: Re-enable once PR13021 is fixed. 552 LLVM_DEBUG(
dbgs() <<
"UNLEAF: " << *Op <<
" (" << It->second <<
")\n");
553 Worklist.push_back(std::make_pair(BO, It->second));
573 assert((!isa<Instruction>(Op) ||
574 cast<Instruction>(Op)->
getOpcode() != Opcode
575 || (isa<FPMathOperator>(Op) &&
576 !cast<Instruction>(Op)->isFast())) &&
577 "Should have been handled above!");
586 <<
"MORPH LEAF: " << *Op <<
" (" << Weight <<
") TO ");
589 Worklist.push_back(std::make_pair(Tmp, Weight));
596 LLVM_DEBUG(
dbgs() <<
"ADD LEAF: " << *Op <<
" (" << Weight <<
")\n");
605 for (
unsigned i = 0,
e = LeafOrder.
size(); i !=
e; ++i) {
606 Value *V = LeafOrder[i];
607 LeafMap::iterator It = Leaves.find(V);
608 if (It == Leaves.end())
612 APInt Weight = It->second;
618 Ops.
push_back(std::make_pair(V, Weight));
626 assert(Identity &&
"Associative operation without identity!");
637 assert(Ops.
size() > 1 &&
"Single values should be used directly!");
665 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
666 NotRewritable.
insert(Ops[i].Op);
672 for (
unsigned i = 0; ; ++i) {
676 if (i+2 == Ops.
size()) {
677 Value *NewLHS = Ops[i].Op;
678 Value *NewRHS = Ops[i+1].Op;
682 if (NewLHS == OldLHS && NewRHS == OldRHS)
686 if (NewLHS == OldRHS && NewRHS == OldLHS) {
699 if (NewLHS != OldLHS) {
701 if (BO && !NotRewritable.
count(BO))
702 NodesToRewrite.push_back(BO);
705 if (NewRHS != OldRHS) {
707 if (BO && !NotRewritable.
count(BO))
708 NodesToRewrite.push_back(BO);
713 ExpressionChanged =
Op;
722 Value *NewRHS = Ops[i].Op;
732 if (BO && !NotRewritable.
count(BO))
733 NodesToRewrite.push_back(BO);
735 ExpressionChanged =
Op;
746 if (BO && !NotRewritable.
count(BO)) {
759 if (NodesToRewrite.empty()) {
762 Undef, Undef,
"", I);
763 if (NewOp->getType()->isFPOrFPVectorTy())
766 NewOp = NodesToRewrite.pop_back_val();
772 ExpressionChanged =
Op;
782 if (ExpressionChanged)
785 if (isa<FPMathOperator>(I)) {
792 if (ExpressionChanged == I)
801 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->
user_begin());
805 for (
unsigned i = 0,
e = NodesToRewrite.size(); i !=
e; ++i)
806 RedoInsts.insert(NodesToRewrite[i]);
818 if (
auto *
C = dyn_cast<Constant>(V))
871 bool FoundCatchSwitch =
false;
874 if (
Instruction *InstInput = dyn_cast<Instruction>(V)) {
875 if (
InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
876 InsertPt = II->getNormalDest()->begin();
878 InsertPt = ++InstInput->getIterator();
885 while (InsertPt != BB->
end() && (isa<PHINode>(InsertPt) ||
886 InsertPt->isEHPad())) {
887 if (isa<CatchSwitchInst>(InsertPt))
890 FoundCatchSwitch =
true;
901 if (FoundCatchSwitch)
905 if (TheNeg->
getOpcode() == Instruction::Sub) {
911 ToRedo.insert(TheNeg);
918 ToRedo.insert(NewNeg);
967 Sub->replaceAllUsesWith(New);
968 New->setDebugLoc(Sub->getDebugLoc());
1005 unsigned XRank = Ops[i].Rank;
1006 unsigned e = Ops.
size();
1007 for (
unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
1012 if (I1->isIdenticalTo(I2))
1016 for (
unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
1021 if (I1->isIdenticalTo(I2))
1031 if (Ops.
size() == 1)
return Ops.
back();
1036 return CreateAdd(V2, V1,
"reass.add", I, I);
1051 for (
unsigned i = 0,
e = Tree.
size(); i !=
e; ++i) {
1053 Factors.
append(E.second.getZExtValue(),
1057 bool FoundFactor =
false;
1058 bool NeedsNegate =
false;
1059 for (
unsigned i = 0,
e = Factors.
size(); i !=
e; ++i) {
1060 if (Factors[i].
Op == Factor) {
1067 if (
ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1068 if (
ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].
Op))
1069 if (FC1->getValue() == -FC2->getValue()) {
1070 FoundFactor = NeedsNegate =
true;
1074 }
else if (
ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1075 if (
ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].
Op)) {
1076 const APFloat &F1 = FC1->getValueAPF();
1077 APFloat F2(FC2->getValueAPF());
1080 FoundFactor = NeedsNegate =
true;
1090 RewriteExprTree(BO, Factors);
1098 if (Factors.
size() == 1) {
1099 RedoInsts.insert(BO);
1102 RewriteExprTree(BO, Factors);
1107 V =
CreateNeg(V,
"neg", &*InsertPt, BO);
1136 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
1143 if (Opcode == Instruction::And)
1146 if (Opcode == Instruction::Or)
1154 if (i+1 != Ops.
size() && Ops[i+1].Op == Ops[i].Op) {
1155 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1164 assert(Opcode == Instruction::Xor);
1183 const APInt &ConstOpnd) {
1216 if (C1 != ConstOpnd)
1225 RedoInsts.insert(
T);
1245 int DeadInstNum = 1;
1263 APInt C3((~C1) ^ C2);
1268 if (NewInstNum > DeadInstNum)
1284 if (NewInstNum > DeadInstNum)
1302 RedoInsts.insert(
T);
1304 RedoInsts.insert(
T);
1317 if (Ops.
size() == 1)
1322 Type *Ty = Ops[0].Op->getType();
1326 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
1327 Value *V = Ops[i].Op;
1344 for (
unsigned i = 0,
e = Opnds.
size(); i !=
e; ++i)
1366 bool Changed =
false;
1367 for (
unsigned i = 0,
e = Opnds.
size(); i <
e; i++) {
1368 XorOpnd *CurrOpnd = OpndPtrs[i];
1374 CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1384 if (!PrevOpnd || CurrOpnd->
getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1385 PrevOpnd = CurrOpnd;
1391 if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1396 PrevOpnd = CurrOpnd;
1408 for (
unsigned int i = 0, e = Opnds.
size(); i <
e; i++) {
1420 unsigned Sz = Ops.
size();
1422 return Ops.
back().Op;
1442 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
1443 Value *TheOp = Ops[i].Op;
1447 if (i+1 != Ops.
size() && Ops[i+1].Op == TheOp) {
1449 unsigned NumFound = 0;
1453 }
while (i != Ops.
size() && Ops[i].Op == TheOp);
1455 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << NumFound <<
"]: " << *TheOp
1468 RedoInsts.insert(Mul);
1495 if (Ops.
size() == 2 &&
1530 unsigned MaxOcc = 0;
1531 Value *MaxOccVal =
nullptr;
1532 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i) {
1541 assert(Factors.
size() > 1 &&
"Bad linearize!");
1545 for (
unsigned i = 0,
e = Factors.
size(); i !=
e; ++i) {
1546 Value *Factor = Factors[i];
1547 if (!Duplicates.insert(Factor).second)
1550 unsigned Occ = ++FactorOccurrences[Factor];
1559 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1560 if (CI->isNegative() && !CI->isMinValue(
true)) {
1562 if (!Duplicates.insert(Factor).second)
1564 unsigned Occ = ++FactorOccurrences[Factor];
1570 }
else if (
ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1571 if (CF->isNegative()) {
1575 if (!Duplicates.insert(Factor).second)
1577 unsigned Occ = ++FactorOccurrences[Factor];
1589 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << MaxOcc <<
"]: " << *MaxOccVal
1600 : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
1603 for (
unsigned i = 0; i != Ops.
size(); ++i) {
1610 if (
Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1613 for (
unsigned j = Ops.
size(); j != i;) {
1615 if (Ops[j].Op == Ops[i].Op) {
1627 unsigned NumAddedValues = NewMulOps.
size();
1633 assert(NumAddedValues > 1 &&
"Each occurrence should contribute a value");
1634 (void)NumAddedValues;
1636 RedoInsts.insert(
VI);
1643 RedoInsts.insert(V2);
1674 unsigned FactorPowerSum = 0;
1675 for (
unsigned Idx = 1,
Size = Ops.
size(); Idx <
Size; ++Idx) {
1680 for (; Idx < Size && Ops[Idx].Op ==
Op; ++Idx)
1684 FactorPowerSum += Count;
1691 if (FactorPowerSum < 4)
1696 for (
unsigned Idx = 1; Idx < Ops.
size(); ++Idx) {
1701 for (; Idx < Ops.
size() && Ops[Idx].Op ==
Op; ++Idx)
1708 FactorPowerSum += Count;
1715 assert(FactorPowerSum >= 4);
1726 if (Ops.
size() == 1)
1735 }
while (!Ops.
empty());
1747 ReassociatePass::buildMinimalMultiplyDAG(
IRBuilder<> &Builder,
1749 assert(Factors[0].Power);
1751 for (
unsigned LastIdx = 0, Idx = 1,
Size = Factors.
size();
1752 Idx <
Size && Factors[Idx].Power > 0; ++Idx) {
1753 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1764 InnerProduct.
push_back(Factors[Idx].Base);
1766 }
while (Idx <
Size && Factors[Idx].Power == Factors[LastIdx].Power);
1772 RedoInsts.insert(
MI);
1779 [](
const Factor &LHS,
const Factor &RHS) {
1780 return LHS.
Power == RHS.Power;
1787 for (
unsigned Idx = 0,
Size = Factors.
size(); Idx !=
Size; ++Idx) {
1788 if (Factors[Idx].Power & 1)
1790 Factors[Idx].Power >>= 1;
1792 if (Factors[0].Power) {
1793 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1797 if (OuterProduct.
size() == 1)
1798 return OuterProduct.
front();
1822 if (
auto FPI = dyn_cast<FPMathOperator>(I))
1825 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1840 while (!Ops.
empty() && isa<Constant>(Ops.
back().Op)) {
1857 if (Ops.
size() == 1)
return Ops[0].
Op;
1861 unsigned NumOps = Ops.
size();
1864 case Instruction::And:
1865 case Instruction::Or:
1870 case Instruction::Xor:
1871 if (
Value *Result = OptimizeXor(I, Ops))
1876 case Instruction::FAdd:
1877 if (
Value *Result = OptimizeAdd(I, Ops))
1881 case Instruction::Mul:
1882 case Instruction::FMul:
1883 if (
Value *Result = OptimizeMul(I, Ops))
1888 if (Ops.
size() != NumOps)
1889 return OptimizeExpression(I, Ops);
1895 void ReassociatePass::RecursivelyEraseDeadInsts(
Instruction *I,
1896 OrderedSet &Insts) {
1899 ValueRankMap.
erase(I);
1901 RedoInsts.remove(I);
1906 if (OpInst->use_empty())
1917 ValueRankMap.
erase(I);
1918 RedoInsts.remove(I);
1923 for (
unsigned i = 0,
e = Ops.
size(); i !=
e; ++i)
1927 unsigned Opcode =
Op->getOpcode();
1928 while (
Op->hasOneUse() &&
Op->user_back()->getOpcode() == Opcode &&
1930 Op =
Op->user_back();
1937 if (ValueRankMap.find(
Op) != ValueRankMap.end())
1938 RedoInsts.insert(
Op);
1959 case Instruction::FMul:
1966 LLVM_DEBUG(
dbgs() <<
"FMul with negative constant: " << *I <<
'\n');
1971 case Instruction::FDiv:
1980 LLVM_DEBUG(
dbgs() <<
"FDiv with negative constant: " << *I <<
'\n');
1997 I->
getOpcode() == Instruction::FSub) &&
"Expected fadd/fsub");
2003 if (Candidates.
empty())
2009 bool IsFSub = I->
getOpcode() == Instruction::FSub;
2010 bool NeedsSubtract = !IsFSub && Candidates.
size() % 2 == 1;
2018 "Expecting only 1 constant operand");
2025 "Expecting only 1 constant operand");
2031 assert(MadeChange ==
true &&
"Negative constant candidate was not changed");
2034 if (Candidates.size() % 2 == 0)
2039 assert(Candidates.size() % 2 == 1 &&
"Expected odd number");
2041 Value *NewInst = IsFSub ? Builder.CreateFAddFMF(OtherOp, Op, I)
2042 : Builder.CreateFSubFMF(OtherOp, Op, I);
2044 RedoInsts.insert(I);
2061 if (
Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2064 if (
Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2067 if (
Instruction *R = canonicalizeNegFPConstantsForOp(I, Op, X))
2074 void ReassociatePass::OptimizeInst(
Instruction *I) {
2076 if (!isa<UnaryOperator>(I) && !isa<BinaryOperator>(I))
2087 RedoInsts.insert(I);
2096 canonicalizeOperands(I);
2099 if (
Instruction *Res = canonicalizeNegFPConstants(I))
2117 if (I->
getOpcode() == Instruction::Sub) {
2120 RedoInsts.insert(I);
2134 RedoInsts.insert(Tmp);
2136 RedoInsts.insert(I);
2141 }
else if (I->
getOpcode() == Instruction::FNeg ||
2145 RedoInsts.insert(I);
2161 RedoInsts.insert(Tmp);
2163 RedoInsts.insert(I);
2196 ReassociateExpression(BO);
2206 for (
unsigned i = 0,
e = Tree.
size(); i !=
e; ++i) {
2208 Ops.
append(E.second.getZExtValue(),
2224 if (
Value *V = OptimizeExpression(I, Ops)) {
2235 RedoInsts.insert(I);
2245 if (I->
getOpcode() == Instruction::Mul &&
2247 isa<ConstantInt>(Ops.
back().Op) &&
2248 cast<ConstantInt>(Ops.
back().Op)->isMinusOne()) {
2251 }
else if (I->
getOpcode() == Instruction::FMul &&
2253 Instruction::FAdd &&
2254 isa<ConstantFP>(Ops.
back().Op) &&
2255 cast<ConstantFP>(Ops.
back().Op)->isExactlyValue(-1.0)) {
2263 if (Ops.
size() == 1) {
2271 if (
Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2273 RedoInsts.insert(I);
2277 if (Ops.
size() > 2 && Ops.
size() <= GlobalReassociateLimit) {
2285 unsigned BestRank = 0;
2286 std::pair<unsigned, unsigned> BestPair;
2287 unsigned Idx = I->
getOpcode() - Instruction::BinaryOpsBegin;
2288 for (
unsigned i = 0; i < Ops.
size() - 1; ++i)
2289 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2291 Value *Op0 = Ops[i].Op;
2292 Value *Op1 = Ops[j].Op;
2293 if (std::less<Value *>()(Op1, Op0))
2295 auto it = PairMap[Idx].find({Op0, Op1});
2296 if (it != PairMap[Idx].
end()) {
2302 if (it->second.isValid())
2303 Score += it->second.Score;
2306 unsigned MaxRank =
std::max(Ops[i].Rank, Ops[j].Rank);
2307 if (Score > Max || (Score == Max && MaxRank < BestRank)) {
2314 auto Op0 = Ops[BestPair.first];
2315 auto Op1 = Ops[BestPair.second];
2316 Ops.
erase(&Ops[BestPair.second]);
2317 Ops.
erase(&Ops[BestPair.first]);
2324 RewriteExprTree(I, Ops);
2344 while (!Worklist.
empty() && Ops.
size() <= GlobalReassociateLimit) {
2358 if (Ops.
size() > GlobalReassociateLimit)
2362 unsigned BinaryIdx = I.
getOpcode() - Instruction::BinaryOpsBegin;
2364 for (
unsigned i = 0; i < Ops.
size() - 1; ++i) {
2365 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2367 Value *Op0 = Ops[i];
2368 Value *Op1 = Ops[j];
2369 if (std::less<Value *>()(Op1, Op0))
2371 if (!Visited.
insert({Op0, Op1}).second)
2373 auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, {Op0, Op1, 1}});
2379 assert(res.first->second.isValid() &&
"WeakVH invalidated");
2380 ++res.first->second.Score;
2396 BuildRankMap(F, RPOT);
2413 assert(RankMap.count(&*BI) &&
"BB should be ranked.");
2420 assert(II->getParent() == &*BI &&
"Moved to a different block!");
2431 while (!ToRedo.empty()) {
2434 RecursivelyEraseDeadInsts(I, ToRedo);
2441 while (!RedoInsts.empty()) {
2443 RedoInsts.erase(RedoInsts.begin());
2453 ValueRankMap.clear();
2454 for (
auto &
Entry : PairMap)
2480 if (skipFunction(F))
2484 auto PA = Impl.
run(F, DummyFAM);
2499 "Reassociate expressions",
false,
false)
2503 return new ReassociateLegacyPass();
Legacy wrapper pass to provide the GlobalsAAResult object.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const_iterator end(StringRef path)
Get end iterator over path.
reference emplace_back(ArgTypes &&... Args)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static BinaryOperator * BreakUpSubtract(Instruction *Sub, ReassociatePass::OrderedSet &ToRedo)
If we have (X-Y), and if either X is an add, or if this is only used by an add, transform this into (...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
static BinaryOperator * LowerNegateToMultiply(Instruction *Neg)
Replace 0-X with X*-1.
This class represents lattice values for constants.
BinaryOps getOpcode() const
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
INITIALIZE_PASS(ReassociateLegacyPass, "reassociate", "Reassociate expressions", false, false) FunctionPass *llvm
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool isIdempotent() const
Return true if the instruction is idempotent:
void push_back(const T &Elt)
Utility class representing a non-constant Xor-operand.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Utility class representing a base and exponent pair which form one factor of some product...
void deleteValue()
Delete a pointer to a generic Value.
bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in .dbg intrinsics with undef.
STATISTIC(NumFunctions, "Total number of functions")
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
static unsigned FindInOperandList(const SmallVectorImpl< ValueEntry > &Ops, unsigned i, Value *X)
Scan backwards and forwards among values with the same rank as element i to see if X exists...
std::pair< Value *, APInt > RepeatedValue
void reserve(size_type N)
Reassociate commutative expressions.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
bool swapOperands()
Exchange the two operands to this instruction.
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool isNilpotent() const
Return true if the instruction is nilpotent:
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static bool collectMultiplyFactors(SmallVectorImpl< ValueEntry > &Ops, SmallVectorImpl< Factor > &Factors)
Build up a vector of value/power pairs factoring a product.
bool isIntegerTy() const
True if this is an instance of IntegerType.
FunctionPass * createReassociatePass()
void setName(const Twine &Name)
Change the name of the value.
This file implements a class to represent arbitrary precision integral constant values and operations...
static Value * OptimizeAndOrXor(unsigned Opcode, SmallVectorImpl< ValueEntry > &Ops)
Optimize a series of operands to an 'and', 'or', or 'xor' instruction.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
bool getBoolValue() const
Convert APInt to a boolean value.
apfloat_match m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
void salvageDebugInfoOrMarkUndef(Instruction &I)
Salvage all debug users of the instruction I or mark it as undef if it cannot be salvaged.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
static Value * createAndInstr(Instruction *InsertBefore, Value *Opnd, const APInt &ConstOpnd)
Helper function of CombineXorOpnd().
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static bool hasNoSignedWrap(BinaryOperator &I)
void takeName(Value *V)
Transfer the name from V to this value.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
static Constant * getFNeg(Constant *C)
bool isAllOnesValue() const
Determine if all bits are set.
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
A set of analyses that are preserved following a run of a transformation pass.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
The instances of the Type class are immutable: once they are created, they are never changed...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
const char * getOpcodeName() const
static Value * EmitAddTreeOfValues(Instruction *I, SmallVectorImpl< WeakTrackingVH > &Ops)
Emit a tree of add instructions, summing Ops together and returning the result.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SetVector< AssertingVH< Instruction >, std::deque< AssertingVH< Instruction > >> OrderedSet
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool isFast() const
Determine whether all fast-math-flags are set.
Analysis pass providing a never-invalidated alias analysis result.
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
Value * getSymbolicPart() const
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static Constant * getAllOnesValue(Type *Ty)
static bool hasNoUnsignedWrap(BinaryOperator &I)
NUW NUW NUW NUW Exact static Exact BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static unsigned CarmichaelShift(unsigned Bitwidth)
Returns k such that lambda(2^Bitwidth) = 2^k, where lambda is the Carmichael function.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
const APInt & getConstPart() const
static BinaryOperator * CreateFNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static void getNegatibleInsts(Value *V, SmallVectorImpl< Instruction *> &Candidates)
Recursively analyze an expression to build a list of instructions that have negative floating-point c...
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
unsigned getSymbolicRank() const
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setSymbolicRank(unsigned R)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
static bool LinearizeExprTree(Instruction *I, SmallVectorImpl< RepeatedValue > &Ops)
Given an associative binary expression, return the leaf nodes in Ops along with their weights (how ma...
bool isCommutative() const
Return true if the instruction is commutative:
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static Value * buildMultiplyTree(IRBuilder<> &Builder, SmallVectorImpl< Value *> &Ops)
Build a tree of multiplies, computing the product of Ops.
static Value * NegateValue(Value *V, Instruction *BI, ReassociatePass::OrderedSet &ToRedo)
Insert instructions before the instruction pointed to by BI, that computes the negative version of th...
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
Represents analyses that only rely on functions' control flow.
iterator insert(iterator I, T &&Elt)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static void FindSingleUseMultiplyFactors(Value *V, SmallVectorImpl< Value *> &Factors)
If V is a single-use multiply, recursively add its operands as factors, otherwise add V to the list o...
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool mayBeMemoryDependent(const Instruction &I)
Returns true if the result or effects of the given instructions I depend on or influence global memor...
LLVM_NODISCARD bool empty() const
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
static void PrintOps(Instruction *I, const SmallVectorImpl< ValueEntry > &Ops)
Print out the expression identified in the Ops list.
static void IncorporateWeight(APInt &LHS, const APInt &RHS, unsigned Opcode)
Add the extra weight 'RHS' to the existing weight 'LHS', reducing the combined weight using any speci...
APFloat abs(APFloat X)
Returns the absolute value of the argument.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
void preserve()
Mark an analysis as preserved.
static BinaryOperator * CreateNeg(Value *S1, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
static BinaryOperator * ConvertShiftToMul(Instruction *Shl)
If this is a shift of a reassociable multiply or is used by one, change this into a multiply by a con...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
void stable_sort(R &&Range)
void initializeReassociateLegacyPassPass(PassRegistry &)
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
void clearSubclassOptionalData()
Clear the optional flags contained in this value.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static BinaryOperator * isReassociableOp(Value *V, unsigned Opcode)
Return true if V is an instruction of the specified opcode and if it only has one use...
bool hasOneUse() const
Return true if there is exactly one user of this value.
Convenience struct for specifying and reasoning about fast-math flags.
A container for analyses that lazily runs them and caches their results.
static bool ShouldBreakUpSubtract(Instruction *Sub)
Return true if we should break up this subtract of X-Y into (X + -Y).
static APInt getNullValue(unsigned numBits)
Get the '0' value.
This header defines various interfaces for pass management in LLVM.
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty)
Return the absorbing element for the given binary operation, i.e.
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
iterator_range< arg_iterator > args()
bool isNullValue() const
Determine if all bits are clear.
cmpResult compare(const APFloat &RHS) const
const BasicBlock * getParent() const
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)