67 #define DEBUG_TYPE "reassociate" 69 STATISTIC(NumChanged,
"Number of insts reassociated");
70 STATISTIC(NumAnnihil,
"Number of expr tree annihilated");
71 STATISTIC(NumFactor ,
"Number of multiplies factored");
78 << *Ops[0].
Op->getType() <<
'\t';
79 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
81 Ops[i].Op->printAsOperand(
dbgs(),
false, M);
82 dbgs() <<
", #" << Ops[i].Rank <<
"] ";
99 bool isInvalid()
const {
return SymbolicPart ==
nullptr; }
113 unsigned SymbolicRank;
118 assert(!isa<ConstantInt>(V) &&
"No ConstantInt");
123 if (I && (I->
getOpcode() == Instruction::Or ||
134 isOr = (I->
getOpcode() == Instruction::Or);
149 if (
I &&
I->hasOneUse() &&
I->getOpcode() == Opcode)
150 if (!isa<FPMathOperator>(
I) ||
I->isFast())
151 return cast<BinaryOperator>(
I);
158 if (
I &&
I->hasOneUse() &&
159 (
I->getOpcode() == Opcode1 ||
I->getOpcode() == Opcode2))
160 if (!isa<FPMathOperator>(
I) ||
I->isFast())
161 return cast<BinaryOperator>(
I);
165 void ReassociatePass::BuildRankMap(
Function &
F,
171 ValueRankMap[&
Arg] = ++Rank;
178 unsigned BBRank = RankMap[BB] = ++Rank << 16;
185 ValueRankMap[&
I] = ++BBRank;
189 unsigned ReassociatePass::getRank(
Value *V) {
192 if (isa<Argument>(V))
return ValueRankMap[V];
196 if (
unsigned Rank = ValueRankMap[I])
203 unsigned Rank = 0, MaxRank = RankMap[I->getParent()];
204 for (
unsigned i = 0, e = I->getNumOperands(); i != e && Rank != MaxRank; ++i)
205 Rank =
std::max(Rank, getRank(I->getOperand(i)));
216 return ValueRankMap[
I] = Rank;
220 void ReassociatePass::canonicalizeOperands(
Instruction *
I) {
221 assert(isa<BinaryOperator>(I) &&
"Expected binary operator.");
226 if (LHS == RHS || isa<Constant>(RHS))
228 if (isa<Constant>(LHS) || getRank(RHS) < getRank(LHS))
229 cast<BinaryOperator>(
I)->swapOperands();
238 BinaryOperator::CreateFAdd(S1, S2, Name, InsertBefore);
250 BinaryOperator::CreateFMul(S1, S2, Name, InsertBefore);
276 Neg->replaceAllUsesWith(Res);
321 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
326 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
336 assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
337 "Unknown associative operation!");
353 assert(LHS.
ult(Threshold) && RHS.
ult(Threshold) &&
"Weights not reduced!");
356 while (LHS.uge(Threshold))
364 "Weights not reduced!");
366 while (Total >= Threshold)
453 "Expected an associative and commutative operation!");
467 bool Changed =
false;
491 while (!Worklist.empty()) {
492 std::pair<BinaryOperator*, APInt>
P = Worklist.pop_back_val();
495 for (
unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) {
497 APInt Weight = P.second;
498 LLVM_DEBUG(
dbgs() <<
"OPERAND: " << *Op <<
" (" << Weight <<
")\n");
504 assert(Visited.
insert(Op).second &&
"Not first visit!");
505 LLVM_DEBUG(
dbgs() <<
"DIRECT ADD: " << *Op <<
" (" << Weight <<
")\n");
506 Worklist.push_back(std::make_pair(BO, Weight));
511 LeafMap::iterator It = Leaves.find(Op);
512 if (It == Leaves.end()) {
514 assert(Visited.
insert(Op).second &&
"Not first visit!");
519 <<
"ADD USES LEAF: " << *Op <<
" (" << Weight <<
")\n");
528 "In leaf map but not visited!");
533 #if 0 // TODO: Re-enable once PR13021 is fixed. 545 LLVM_DEBUG(
dbgs() <<
"UNLEAF: " << *Op <<
" (" << It->second <<
")\n");
546 Worklist.push_back(std::make_pair(BO, It->second));
566 assert((!isa<Instruction>(Op) ||
567 cast<Instruction>(Op)->getOpcode() != Opcode
568 || (isa<FPMathOperator>(Op) &&
569 !cast<Instruction>(Op)->isFast())) &&
570 "Should have been handled above!");
579 <<
"MORPH LEAF: " << *Op <<
" (" << Weight <<
") TO ");
582 Worklist.push_back(std::make_pair(BO, Weight));
589 LLVM_DEBUG(
dbgs() <<
"ADD LEAF: " << *Op <<
" (" << Weight <<
")\n");
598 for (
unsigned i = 0, e = LeafOrder.
size(); i != e; ++i) {
599 Value *V = LeafOrder[i];
600 LeafMap::iterator It = Leaves.find(V);
601 if (It == Leaves.end())
605 APInt Weight = It->second;
611 Ops.
push_back(std::make_pair(V, Weight));
619 assert(Identity &&
"Associative operation without identity!");
630 assert(Ops.
size() > 1 &&
"Single values should be used directly!");
658 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
659 NotRewritable.
insert(Ops[i].Op);
665 for (
unsigned i = 0; ; ++i) {
669 if (i+2 == Ops.
size()) {
670 Value *NewLHS = Ops[i].Op;
671 Value *NewRHS = Ops[i+1].Op;
675 if (NewLHS == OldLHS && NewRHS == OldRHS)
679 if (NewLHS == OldRHS && NewRHS == OldLHS) {
692 if (NewLHS != OldLHS) {
694 if (BO && !NotRewritable.
count(BO))
695 NodesToRewrite.push_back(BO);
698 if (NewRHS != OldRHS) {
700 if (BO && !NotRewritable.
count(BO))
701 NodesToRewrite.push_back(BO);
706 ExpressionChanged =
Op;
715 Value *NewRHS = Ops[i].Op;
725 if (BO && !NotRewritable.
count(BO))
726 NodesToRewrite.push_back(BO);
728 ExpressionChanged =
Op;
739 if (BO && !NotRewritable.
count(BO)) {
752 if (NodesToRewrite.empty()) {
755 Undef, Undef,
"", I);
756 if (NewOp->getType()->isFPOrFPVectorTy())
759 NewOp = NodesToRewrite.pop_back_val();
765 ExpressionChanged =
Op;
775 if (ExpressionChanged)
778 if (isa<FPMathOperator>(I)) {
785 if (ExpressionChanged == I)
793 for (
auto *DII : DbgUsers) {
800 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->
user_begin());
804 for (
unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
805 RedoInsts.insert(NodesToRewrite[i]);
817 if (
auto *
C = dyn_cast<Constant>(V))
871 if (
Instruction *InstInput = dyn_cast<Instruction>(V)) {
872 if (
InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
873 InsertPt = II->getNormalDest()->begin();
875 InsertPt = ++InstInput->getIterator();
877 while (isa<PHINode>(InsertPt)) ++InsertPt;
882 if (TheNeg->
getOpcode() == Instruction::Sub) {
888 ToRedo.insert(TheNeg);
895 ToRedo.insert(NewNeg);
944 Sub->replaceAllUsesWith(New);
945 New->setDebugLoc(Sub->getDebugLoc());
969 bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
970 bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
982 unsigned XRank = Ops[i].Rank;
983 unsigned e = Ops.
size();
984 for (
unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
989 if (I1->isIdenticalTo(I2))
993 for (
unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
998 if (I1->isIdenticalTo(I2))
1008 if (Ops.
size() == 1)
return Ops.
back();
1013 return CreateAdd(V2, V1,
"reass.add", I, I);
1028 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
1030 Factors.
append(E.second.getZExtValue(),
1034 bool FoundFactor =
false;
1035 bool NeedsNegate =
false;
1036 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1037 if (Factors[i].
Op == Factor) {
1044 if (
ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1045 if (
ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].
Op))
1046 if (FC1->getValue() == -FC2->getValue()) {
1047 FoundFactor = NeedsNegate =
true;
1051 }
else if (
ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1052 if (
ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].
Op)) {
1053 const APFloat &F1 = FC1->getValueAPF();
1054 APFloat F2(FC2->getValueAPF());
1057 FoundFactor = NeedsNegate =
true;
1067 RewriteExprTree(BO, Factors);
1075 if (Factors.
size() == 1) {
1076 RedoInsts.insert(BO);
1079 RewriteExprTree(BO, Factors);
1084 V =
CreateNeg(V,
"neg", &*InsertPt, BO);
1113 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1120 if (Opcode == Instruction::And)
1123 if (Opcode == Instruction::Or)
1131 if (i+1 != Ops.
size() && Ops[i+1].Op == Ops[i].Op) {
1132 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1141 assert(Opcode == Instruction::Xor);
1160 const APInt &ConstOpnd) {
1193 if (C1 != ConstOpnd)
1202 RedoInsts.insert(
T);
1222 int DeadInstNum = 1;
1240 APInt C3((~C1) ^ C2);
1245 if (NewInstNum > DeadInstNum)
1261 if (NewInstNum > DeadInstNum)
1279 RedoInsts.insert(
T);
1281 RedoInsts.insert(
T);
1294 if (Ops.
size() == 1)
1299 Type *Ty = Ops[0].Op->getType();
1303 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1304 Value *V = Ops[i].Op;
1321 for (
unsigned i = 0, e = Opnds.
size(); i != e; ++i)
1337 std::stable_sort(OpndPtrs.
begin(), OpndPtrs.
end(),
1344 bool Changed =
false;
1345 for (
unsigned i = 0, e = Opnds.
size(); i < e; i++) {
1346 XorOpnd *CurrOpnd = OpndPtrs[i];
1352 CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1362 if (!PrevOpnd || CurrOpnd->
getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1363 PrevOpnd = CurrOpnd;
1369 if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1374 PrevOpnd = CurrOpnd;
1386 for (
unsigned int i = 0, e = Opnds.
size(); i < e; i++) {
1398 unsigned Sz = Ops.
size();
1420 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1421 Value *TheOp = Ops[i].Op;
1425 if (i+1 != Ops.
size() && Ops[i+1].Op == TheOp) {
1427 unsigned NumFound = 0;
1431 }
while (i != Ops.
size() && Ops[i].Op == TheOp);
1433 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << NumFound <<
"]: " << *TheOp
1446 RedoInsts.insert(Mul);
1478 if (Ops.
size() == 2 &&
1513 unsigned MaxOcc = 0;
1514 Value *MaxOccVal =
nullptr;
1515 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1524 assert(Factors.
size() > 1 &&
"Bad linearize!");
1528 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1529 Value *Factor = Factors[i];
1530 if (!Duplicates.insert(Factor).second)
1533 unsigned Occ = ++FactorOccurrences[Factor];
1542 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1543 if (CI->isNegative() && !CI->isMinValue(
true)) {
1545 if (!Duplicates.insert(Factor).second)
1547 unsigned Occ = ++FactorOccurrences[Factor];
1553 }
else if (
ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1554 if (CF->isNegative()) {
1558 if (!Duplicates.insert(Factor).second)
1560 unsigned Occ = ++FactorOccurrences[Factor];
1572 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << MaxOcc <<
"]: " << *MaxOccVal
1583 : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
1586 for (
unsigned i = 0; i != Ops.
size(); ++i) {
1593 if (
Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1596 for (
unsigned j = Ops.
size(); j != i;) {
1598 if (Ops[j].Op == Ops[i].Op) {
1610 unsigned NumAddedValues = NewMulOps.
size();
1616 assert(NumAddedValues > 1 &&
"Each occurrence should contribute a value");
1617 (void)NumAddedValues;
1619 RedoInsts.insert(
VI);
1626 RedoInsts.insert(V2);
1657 unsigned FactorPowerSum = 0;
1658 for (
unsigned Idx = 1,
Size = Ops.
size(); Idx <
Size; ++Idx) {
1663 for (; Idx < Size && Ops[Idx].Op ==
Op; ++Idx)
1667 FactorPowerSum += Count;
1674 if (FactorPowerSum < 4)
1679 for (
unsigned Idx = 1; Idx < Ops.
size(); ++Idx) {
1684 for (; Idx < Ops.
size() && Ops[Idx].Op ==
Op; ++Idx)
1691 FactorPowerSum += Count;
1698 assert(FactorPowerSum >= 4);
1700 std::stable_sort(Factors.
begin(), Factors.
end(),
1701 [](
const Factor &LHS,
const Factor &RHS) {
1702 return LHS.
Power > RHS.Power;
1710 if (Ops.
size() == 1)
1719 }
while (!Ops.
empty());
1731 ReassociatePass::buildMinimalMultiplyDAG(
IRBuilder<> &Builder,
1733 assert(Factors[0].Power);
1735 for (
unsigned LastIdx = 0, Idx = 1,
Size = Factors.
size();
1736 Idx <
Size && Factors[Idx].Power > 0; ++Idx) {
1737 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1748 InnerProduct.
push_back(Factors[Idx].Base);
1750 }
while (Idx <
Size && Factors[Idx].Power == Factors[LastIdx].Power);
1756 RedoInsts.insert(
MI);
1763 [](
const Factor &LHS,
const Factor &RHS) {
1764 return LHS.
Power == RHS.Power;
1771 for (
unsigned Idx = 0,
Size = Factors.
size(); Idx !=
Size; ++Idx) {
1772 if (Factors[Idx].Power & 1)
1774 Factors[Idx].Power >>= 1;
1776 if (Factors[0].Power) {
1777 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1781 if (OuterProduct.
size() == 1)
1782 return OuterProduct.
front();
1806 if (
auto FPI = dyn_cast<FPMathOperator>(I))
1809 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1824 while (!Ops.
empty() && isa<Constant>(Ops.
back().
Op)) {
1841 if (Ops.
size() == 1)
return Ops[0].
Op;
1845 unsigned NumOps = Ops.
size();
1848 case Instruction::And:
1849 case Instruction::Or:
1854 case Instruction::Xor:
1860 case Instruction::FAdd:
1865 case Instruction::Mul:
1866 case Instruction::FMul:
1872 if (Ops.
size() != NumOps)
1873 return OptimizeExpression(I, Ops);
1879 void ReassociatePass::RecursivelyEraseDeadInsts(
Instruction *I,
1880 OrderedSet &Insts) {
1883 ValueRankMap.
erase(I);
1885 RedoInsts.remove(I);
1889 if (OpInst->use_empty())
1900 ValueRankMap.
erase(I);
1901 RedoInsts.remove(I);
1905 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
1909 unsigned Opcode =
Op->getOpcode();
1910 while (
Op->hasOneUse() &&
Op->user_back()->getOpcode() == Opcode &&
1912 Op =
Op->user_back();
1919 if (ValueRankMap.find(
Op) != ValueRankMap.end())
1920 RedoInsts.insert(
Op);
1935 if (Opcode != Instruction::FMul && Opcode != Instruction::FDiv)
1957 if (!isa<BinaryOperator>(User) || User->
use_empty())
1960 unsigned UserOpcode = User->
getOpcode();
1961 if (UserOpcode != Instruction::FAdd && UserOpcode != Instruction::FSub)
1983 cast<BinaryOperator>(User)->swapOperands();
1988 switch (UserOpcode) {
1991 case Instruction::FAdd:
1992 NI = BinaryOperator::CreateFSub(Op0, Op1);
1995 case Instruction::FSub:
1996 NI = BinaryOperator::CreateFAdd(Op0, Op1);
2005 RedoInsts.insert(I);
2012 void ReassociatePass::OptimizeInst(
Instruction *I) {
2014 if (!isa<BinaryOperator>(I))
2025 RedoInsts.insert(I);
2031 if (
Instruction *Res = canonicalizeNegConstExpr(I))
2038 canonicalizeOperands(I);
2055 if (I->
getOpcode() == Instruction::Sub) {
2058 RedoInsts.insert(I);
2072 RedoInsts.insert(Tmp);
2074 RedoInsts.insert(I);
2079 }
else if (I->
getOpcode() == Instruction::FSub) {
2082 RedoInsts.insert(I);
2096 RedoInsts.insert(Tmp);
2098 RedoInsts.insert(I);
2125 cast<Instruction>(BO->
user_back())->getOpcode() == Instruction::Sub)
2128 cast<Instruction>(BO->
user_back())->getOpcode() == Instruction::FSub)
2131 ReassociateExpression(BO);
2141 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
2143 Ops.
append(E.second.getZExtValue(),
2155 std::stable_sort(Ops.
begin(), Ops.
end());
2159 if (
Value *V = OptimizeExpression(I, Ops)) {
2170 RedoInsts.insert(I);
2180 if (I->
getOpcode() == Instruction::Mul &&
2182 isa<ConstantInt>(Ops.
back().
Op) &&
2183 cast<ConstantInt>(Ops.
back().
Op)->isMinusOne()) {
2186 }
else if (I->
getOpcode() == Instruction::FMul &&
2187 cast<Instruction>(I->
user_back())->getOpcode() ==
2188 Instruction::FAdd &&
2189 isa<ConstantFP>(Ops.
back().
Op) &&
2190 cast<ConstantFP>(Ops.
back().
Op)->isExactlyValue(-1.0)) {
2198 if (Ops.
size() == 1) {
2206 if (
Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2208 RedoInsts.insert(I);
2212 if (Ops.
size() > 2 && Ops.
size() <= GlobalReassociateLimit) {
2220 unsigned BestRank = 0;
2221 std::pair<unsigned, unsigned> BestPair;
2222 unsigned Idx = I->
getOpcode() - Instruction::BinaryOpsBegin;
2223 for (
unsigned i = 0; i < Ops.
size() - 1; ++i)
2224 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2226 Value *Op0 = Ops[i].Op;
2227 Value *Op1 = Ops[j].Op;
2228 if (std::less<Value *>()(Op1, Op0))
2230 auto it = PairMap[Idx].find({Op0, Op1});
2231 if (it != PairMap[Idx].
end())
2232 Score += it->second;
2234 unsigned MaxRank =
std::max(Ops[i].Rank, Ops[j].Rank);
2235 if (Score > Max || (Score == Max && MaxRank < BestRank)) {
2242 auto Op0 = Ops[BestPair.first];
2243 auto Op1 = Ops[BestPair.second];
2244 Ops.
erase(&Ops[BestPair.second]);
2245 Ops.
erase(&Ops[BestPair.first]);
2252 RewriteExprTree(I, Ops);
2272 while (!Worklist.
empty() && Ops.
size() <= GlobalReassociateLimit) {
2286 if (Ops.
size() > GlobalReassociateLimit)
2290 unsigned BinaryIdx = I.
getOpcode() - Instruction::BinaryOpsBegin;
2292 for (
unsigned i = 0; i < Ops.
size() - 1; ++i) {
2293 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2295 Value *Op0 = Ops[i];
2296 Value *Op1 = Ops[j];
2297 if (std::less<Value *>()(Op1, Op0))
2299 if (!Visited.
insert({Op0, Op1}).second)
2301 auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, 1});
2303 ++res.first->second;
2318 BuildRankMap(F, RPOT);
2335 assert(RankMap.count(&*BI) &&
"BB should be ranked.");
2342 assert(II->getParent() == &*BI &&
"Moved to a different block!");
2353 while (!ToRedo.empty()) {
2356 RecursivelyEraseDeadInsts(I, ToRedo);
2363 while (!RedoInsts.empty()) {
2365 RedoInsts.erase(RedoInsts.begin());
2375 ValueRankMap.clear();
2376 for (
auto &Entry : PairMap)
2402 if (skipFunction(F))
2406 auto PA = Impl.
run(F, DummyFAM);
2421 "Reassociate expressions",
false,
false)
2425 return new ReassociateLegacyPass();
Legacy wrapper pass to provide the GlobalsAAResult object.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
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.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static BinaryOperator * LowerNegateToMultiply(Instruction *Neg)
Replace 0-X with X*-1.
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
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. ...
bool isIdempotent() const
Return true if the instruction is idempotent:
Utility class representing a non-constant Xor-operand.
Utility class representing a base and exponent pair which form one factor of some product...
LLVMContext & getContext() const
All values hold a context through their type.
void deleteValue()
Delete a pointer to a generic Value.
STATISTIC(NumFunctions, "Total number of functions")
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
bool isVectorTy() const
True if this is an instance of VectorType.
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)
static const Value * getNegArgument(const Value *BinOp)
Helper functions to extract the unary argument of a NEG, FNEG or NOT operation implemented via Sub...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
bool isNilpotent() const
Return true if the instruction is nilpotent:
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.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
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 Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
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.
bool isNegative() const
Return true if the sign bit is set.
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.
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
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.
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)
static const Value * getNotArgument(const Value *BinOp)
Value * getOperand(unsigned i) const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
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).
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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.
static bool isNot(const Value *V)
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)
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
const APInt & getConstPart() const
const APFloat & getValueAPF() const
static BinaryOperator * CreateFNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
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.
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.
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...
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.
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...
static bool isNeg(const Value *V)
Check if the given Value is a NEG, FNeg, or NOT instruction.
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()
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.
amdgpu Simplify well known AMD library false Value Value * Arg
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)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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...
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false)
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...
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)
void findDbgUsers(SmallVectorImpl< DbgInfoIntrinsic *> &DbgInsts, Value *V)
Finds the debug info intrinsics describing a value.
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.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
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 initializeReassociateLegacyPassPass(PassRegistry &)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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.
static bool LinearizeExprTree(BinaryOperator *I, SmallVectorImpl< RepeatedValue > &Ops)
Given an associative binary expression, return the leaf nodes in Ops along with their weights (how ma...
iterator_range< arg_iterator > args()
bool isNullValue() const
Determine if all bits are clear.
cmpResult compare(const APFloat &RHS) const
const BasicBlock * getParent() const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)