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);
277 Neg->replaceAllUsesWith(Res);
322 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
327 assert(LHS == 1 && RHS == 1 &&
"Weights not reduced!");
337 assert((Opcode == Instruction::Mul || Opcode == Instruction::FMul) &&
338 "Unknown associative operation!");
354 assert(LHS.
ult(Threshold) && RHS.
ult(Threshold) &&
"Weights not reduced!");
357 while (LHS.uge(Threshold))
365 "Weights not reduced!");
367 while (Total >= Threshold)
454 "Expected an associative and commutative operation!");
468 bool Changed =
false;
492 while (!Worklist.empty()) {
493 std::pair<BinaryOperator*, APInt>
P = Worklist.pop_back_val();
496 for (
unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) {
498 APInt Weight = P.second;
499 LLVM_DEBUG(
dbgs() <<
"OPERAND: " << *Op <<
" (" << Weight <<
")\n");
505 assert(Visited.
insert(Op).second &&
"Not first visit!");
506 LLVM_DEBUG(
dbgs() <<
"DIRECT ADD: " << *Op <<
" (" << Weight <<
")\n");
507 Worklist.push_back(std::make_pair(BO, Weight));
512 LeafMap::iterator It = Leaves.find(Op);
513 if (It == Leaves.end()) {
515 assert(Visited.
insert(Op).second &&
"Not first visit!");
520 <<
"ADD USES LEAF: " << *Op <<
" (" << Weight <<
")\n");
529 "In leaf map but not visited!");
534 #if 0 // TODO: Re-enable once PR13021 is fixed. 546 LLVM_DEBUG(
dbgs() <<
"UNLEAF: " << *Op <<
" (" << It->second <<
")\n");
547 Worklist.push_back(std::make_pair(BO, It->second));
567 assert((!isa<Instruction>(Op) ||
568 cast<Instruction>(Op)->
getOpcode() != Opcode
569 || (isa<FPMathOperator>(Op) &&
570 !cast<Instruction>(Op)->isFast())) &&
571 "Should have been handled above!");
580 <<
"MORPH LEAF: " << *Op <<
" (" << Weight <<
") TO ");
583 Worklist.push_back(std::make_pair(BO, Weight));
590 LLVM_DEBUG(
dbgs() <<
"ADD LEAF: " << *Op <<
" (" << Weight <<
")\n");
599 for (
unsigned i = 0, e = LeafOrder.
size(); i != e; ++i) {
600 Value *V = LeafOrder[i];
601 LeafMap::iterator It = Leaves.find(V);
602 if (It == Leaves.end())
606 APInt Weight = It->second;
612 Ops.
push_back(std::make_pair(V, Weight));
620 assert(Identity &&
"Associative operation without identity!");
631 assert(Ops.
size() > 1 &&
"Single values should be used directly!");
659 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
660 NotRewritable.
insert(Ops[i].Op);
666 for (
unsigned i = 0; ; ++i) {
670 if (i+2 == Ops.
size()) {
671 Value *NewLHS = Ops[i].Op;
672 Value *NewRHS = Ops[i+1].Op;
676 if (NewLHS == OldLHS && NewRHS == OldRHS)
680 if (NewLHS == OldRHS && NewRHS == OldLHS) {
693 if (NewLHS != OldLHS) {
695 if (BO && !NotRewritable.
count(BO))
696 NodesToRewrite.push_back(BO);
699 if (NewRHS != OldRHS) {
701 if (BO && !NotRewritable.
count(BO))
702 NodesToRewrite.push_back(BO);
707 ExpressionChanged =
Op;
716 Value *NewRHS = Ops[i].Op;
726 if (BO && !NotRewritable.
count(BO))
727 NodesToRewrite.push_back(BO);
729 ExpressionChanged =
Op;
740 if (BO && !NotRewritable.
count(BO)) {
753 if (NodesToRewrite.empty()) {
756 Undef, Undef,
"", I);
757 if (NewOp->getType()->isFPOrFPVectorTy())
760 NewOp = NodesToRewrite.pop_back_val();
766 ExpressionChanged =
Op;
776 if (ExpressionChanged)
779 if (isa<FPMathOperator>(I)) {
786 if (ExpressionChanged == I)
795 ExpressionChanged = cast<BinaryOperator>(*ExpressionChanged->
user_begin());
799 for (
unsigned i = 0, e = NodesToRewrite.size(); i != e; ++i)
800 RedoInsts.insert(NodesToRewrite[i]);
812 if (
auto *
C = dyn_cast<Constant>(V))
866 if (
Instruction *InstInput = dyn_cast<Instruction>(V)) {
867 if (
InvokeInst *II = dyn_cast<InvokeInst>(InstInput)) {
868 InsertPt = II->getNormalDest()->begin();
870 InsertPt = ++InstInput->getIterator();
872 while (isa<PHINode>(InsertPt)) ++InsertPt;
877 if (TheNeg->
getOpcode() == Instruction::Sub) {
883 ToRedo.insert(TheNeg);
890 ToRedo.insert(NewNeg);
939 Sub->replaceAllUsesWith(New);
940 New->setDebugLoc(Sub->getDebugLoc());
964 bool NSW = cast<BinaryOperator>(Shl)->hasNoSignedWrap();
965 bool NUW = cast<BinaryOperator>(Shl)->hasNoUnsignedWrap();
977 unsigned XRank = Ops[i].Rank;
978 unsigned e = Ops.
size();
979 for (
unsigned j = i+1; j != e && Ops[j].Rank == XRank; ++j) {
984 if (I1->isIdenticalTo(I2))
988 for (
unsigned j = i-1; j != ~0U && Ops[j].Rank == XRank; --j) {
993 if (I1->isIdenticalTo(I2))
1003 if (Ops.
size() == 1)
return Ops.
back();
1008 return CreateAdd(V2, V1,
"reass.add", I, I);
1023 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
1025 Factors.
append(E.second.getZExtValue(),
1029 bool FoundFactor =
false;
1030 bool NeedsNegate =
false;
1031 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1032 if (Factors[i].
Op == Factor) {
1039 if (
ConstantInt *FC1 = dyn_cast<ConstantInt>(Factor)) {
1040 if (
ConstantInt *FC2 = dyn_cast<ConstantInt>(Factors[i].
Op))
1041 if (FC1->getValue() == -FC2->getValue()) {
1042 FoundFactor = NeedsNegate =
true;
1046 }
else if (
ConstantFP *FC1 = dyn_cast<ConstantFP>(Factor)) {
1047 if (
ConstantFP *FC2 = dyn_cast<ConstantFP>(Factors[i].
Op)) {
1048 const APFloat &F1 = FC1->getValueAPF();
1049 APFloat F2(FC2->getValueAPF());
1052 FoundFactor = NeedsNegate =
true;
1062 RewriteExprTree(BO, Factors);
1070 if (Factors.
size() == 1) {
1071 RedoInsts.insert(BO);
1074 RewriteExprTree(BO, Factors);
1079 V =
CreateNeg(V,
"neg", &*InsertPt, BO);
1108 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1115 if (Opcode == Instruction::And)
1118 if (Opcode == Instruction::Or)
1126 if (i+1 != Ops.
size() && Ops[i+1].Op == Ops[i].Op) {
1127 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
1136 assert(Opcode == Instruction::Xor);
1155 const APInt &ConstOpnd) {
1188 if (C1 != ConstOpnd)
1197 RedoInsts.insert(
T);
1217 int DeadInstNum = 1;
1235 APInt C3((~C1) ^ C2);
1240 if (NewInstNum > DeadInstNum)
1256 if (NewInstNum > DeadInstNum)
1274 RedoInsts.insert(
T);
1276 RedoInsts.insert(
T);
1289 if (Ops.
size() == 1)
1294 Type *Ty = Ops[0].Op->getType();
1298 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1299 Value *V = Ops[i].Op;
1316 for (
unsigned i = 0, e = Opnds.
size(); i != e; ++i)
1332 std::stable_sort(OpndPtrs.
begin(), OpndPtrs.
end(),
1339 bool Changed =
false;
1340 for (
unsigned i = 0, e = Opnds.
size(); i < e; i++) {
1341 XorOpnd *CurrOpnd = OpndPtrs[i];
1347 CombineXorOpnd(I, CurrOpnd, ConstOpnd, CV)) {
1357 if (!PrevOpnd || CurrOpnd->
getSymbolicPart() != PrevOpnd->getSymbolicPart()) {
1358 PrevOpnd = CurrOpnd;
1364 if (CombineXorOpnd(I, CurrOpnd, PrevOpnd, ConstOpnd, CV)) {
1369 PrevOpnd = CurrOpnd;
1381 for (
unsigned int i = 0, e = Opnds.
size(); i < e; i++) {
1393 unsigned Sz = Ops.
size();
1415 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1416 Value *TheOp = Ops[i].Op;
1420 if (i+1 != Ops.
size() && Ops[i+1].Op == TheOp) {
1422 unsigned NumFound = 0;
1426 }
while (i != Ops.
size() && Ops[i].Op == TheOp);
1428 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << NumFound <<
"]: " << *TheOp
1441 RedoInsts.insert(Mul);
1468 if (Ops.
size() == 2 &&
1503 unsigned MaxOcc = 0;
1504 Value *MaxOccVal =
nullptr;
1505 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1514 assert(Factors.
size() > 1 &&
"Bad linearize!");
1518 for (
unsigned i = 0, e = Factors.
size(); i != e; ++i) {
1519 Value *Factor = Factors[i];
1520 if (!Duplicates.insert(Factor).second)
1523 unsigned Occ = ++FactorOccurrences[Factor];
1532 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Factor)) {
1533 if (CI->isNegative() && !CI->isMinValue(
true)) {
1535 if (!Duplicates.insert(Factor).second)
1537 unsigned Occ = ++FactorOccurrences[Factor];
1543 }
else if (
ConstantFP *CF = dyn_cast<ConstantFP>(Factor)) {
1544 if (CF->isNegative()) {
1548 if (!Duplicates.insert(Factor).second)
1550 unsigned Occ = ++FactorOccurrences[Factor];
1562 LLVM_DEBUG(
dbgs() <<
"\nFACTORING [" << MaxOcc <<
"]: " << *MaxOccVal
1573 : BinaryOperator::CreateFAdd(MaxOccVal, MaxOccVal);
1576 for (
unsigned i = 0; i != Ops.
size(); ++i) {
1583 if (
Value *V = RemoveFactorFromExpression(Ops[i].Op, MaxOccVal)) {
1586 for (
unsigned j = Ops.
size(); j != i;) {
1588 if (Ops[j].Op == Ops[i].Op) {
1600 unsigned NumAddedValues = NewMulOps.
size();
1606 assert(NumAddedValues > 1 &&
"Each occurrence should contribute a value");
1607 (void)NumAddedValues;
1609 RedoInsts.insert(
VI);
1616 RedoInsts.insert(V2);
1647 unsigned FactorPowerSum = 0;
1648 for (
unsigned Idx = 1,
Size = Ops.
size(); Idx <
Size; ++Idx) {
1653 for (; Idx < Size && Ops[Idx].Op ==
Op; ++Idx)
1657 FactorPowerSum += Count;
1664 if (FactorPowerSum < 4)
1669 for (
unsigned Idx = 1; Idx < Ops.
size(); ++Idx) {
1674 for (; Idx < Ops.
size() && Ops[Idx].Op ==
Op; ++Idx)
1681 FactorPowerSum += Count;
1688 assert(FactorPowerSum >= 4);
1690 std::stable_sort(Factors.
begin(), Factors.
end(),
1691 [](
const Factor &LHS,
const Factor &RHS) {
1692 return LHS.
Power > RHS.Power;
1700 if (Ops.
size() == 1)
1709 }
while (!Ops.
empty());
1721 ReassociatePass::buildMinimalMultiplyDAG(
IRBuilder<> &Builder,
1723 assert(Factors[0].Power);
1725 for (
unsigned LastIdx = 0, Idx = 1,
Size = Factors.
size();
1726 Idx <
Size && Factors[Idx].Power > 0; ++Idx) {
1727 if (Factors[Idx].Power != Factors[LastIdx].Power) {
1738 InnerProduct.
push_back(Factors[Idx].Base);
1740 }
while (Idx <
Size && Factors[Idx].Power == Factors[LastIdx].Power);
1746 RedoInsts.insert(
MI);
1753 [](
const Factor &LHS,
const Factor &RHS) {
1754 return LHS.
Power == RHS.Power;
1761 for (
unsigned Idx = 0,
Size = Factors.
size(); Idx !=
Size; ++Idx) {
1762 if (Factors[Idx].Power & 1)
1764 Factors[Idx].Power >>= 1;
1766 if (Factors[0].Power) {
1767 Value *SquareRoot = buildMinimalMultiplyDAG(Builder, Factors);
1771 if (OuterProduct.
size() == 1)
1772 return OuterProduct.
front();
1796 if (
auto FPI = dyn_cast<FPMathOperator>(I))
1799 Value *V = buildMinimalMultiplyDAG(Builder, Factors);
1814 while (!Ops.
empty() && isa<Constant>(Ops.
back().
Op)) {
1831 if (Ops.
size() == 1)
return Ops[0].
Op;
1835 unsigned NumOps = Ops.
size();
1838 case Instruction::And:
1839 case Instruction::Or:
1844 case Instruction::Xor:
1845 if (
Value *Result = OptimizeXor(I, Ops))
1850 case Instruction::FAdd:
1851 if (
Value *Result = OptimizeAdd(I, Ops))
1855 case Instruction::Mul:
1856 case Instruction::FMul:
1857 if (
Value *Result = OptimizeMul(I, Ops))
1862 if (Ops.
size() != NumOps)
1863 return OptimizeExpression(I, Ops);
1869 void ReassociatePass::RecursivelyEraseDeadInsts(
Instruction *I,
1870 OrderedSet &Insts) {
1873 ValueRankMap.
erase(I);
1875 RedoInsts.remove(I);
1879 if (OpInst->use_empty())
1890 ValueRankMap.
erase(I);
1891 RedoInsts.remove(I);
1895 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i)
1899 unsigned Opcode =
Op->getOpcode();
1900 while (
Op->hasOneUse() &&
Op->user_back()->getOpcode() == Opcode &&
1902 Op =
Op->user_back();
1909 if (ValueRankMap.find(
Op) != ValueRankMap.end())
1910 RedoInsts.insert(
Op);
1925 if (Opcode != Instruction::FMul && Opcode != Instruction::FDiv)
1947 if (!isa<BinaryOperator>(User) || User->
use_empty())
1950 unsigned UserOpcode = User->
getOpcode();
1951 if (UserOpcode != Instruction::FAdd && UserOpcode != Instruction::FSub)
1973 cast<BinaryOperator>(User)->swapOperands();
1978 switch (UserOpcode) {
1981 case Instruction::FAdd:
1982 NI = BinaryOperator::CreateFSub(Op0, Op1);
1985 case Instruction::FSub:
1986 NI = BinaryOperator::CreateFAdd(Op0, Op1);
1995 RedoInsts.insert(I);
2002 void ReassociatePass::OptimizeInst(
Instruction *I) {
2004 if (!isa<BinaryOperator>(I))
2015 RedoInsts.insert(I);
2021 if (
Instruction *Res = canonicalizeNegConstExpr(I))
2028 canonicalizeOperands(I);
2045 if (I->
getOpcode() == Instruction::Sub) {
2048 RedoInsts.insert(I);
2062 RedoInsts.insert(Tmp);
2064 RedoInsts.insert(I);
2069 }
else if (I->
getOpcode() == Instruction::FSub) {
2072 RedoInsts.insert(I);
2086 RedoInsts.insert(Tmp);
2088 RedoInsts.insert(I);
2121 ReassociateExpression(BO);
2131 for (
unsigned i = 0, e = Tree.
size(); i != e; ++i) {
2133 Ops.
append(E.second.getZExtValue(),
2145 std::stable_sort(Ops.
begin(), Ops.
end());
2149 if (
Value *V = OptimizeExpression(I, Ops)) {
2160 RedoInsts.insert(I);
2170 if (I->
getOpcode() == Instruction::Mul &&
2172 isa<ConstantInt>(Ops.
back().
Op) &&
2173 cast<ConstantInt>(Ops.
back().
Op)->isMinusOne()) {
2176 }
else if (I->
getOpcode() == Instruction::FMul &&
2178 Instruction::FAdd &&
2179 isa<ConstantFP>(Ops.
back().
Op) &&
2180 cast<ConstantFP>(Ops.
back().
Op)->isExactlyValue(-1.0)) {
2188 if (Ops.
size() == 1) {
2196 if (
Instruction *OI = dyn_cast<Instruction>(Ops[0].Op))
2198 RedoInsts.insert(I);
2202 if (Ops.
size() > 2 && Ops.
size() <= GlobalReassociateLimit) {
2210 unsigned BestRank = 0;
2211 std::pair<unsigned, unsigned> BestPair;
2212 unsigned Idx = I->
getOpcode() - Instruction::BinaryOpsBegin;
2213 for (
unsigned i = 0; i < Ops.
size() - 1; ++i)
2214 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2216 Value *Op0 = Ops[i].Op;
2217 Value *Op1 = Ops[j].Op;
2218 if (std::less<Value *>()(Op1, Op0))
2220 auto it = PairMap[Idx].find({Op0, Op1});
2221 if (it != PairMap[Idx].
end())
2222 Score += it->second;
2224 unsigned MaxRank =
std::max(Ops[i].Rank, Ops[j].Rank);
2225 if (Score > Max || (Score == Max && MaxRank < BestRank)) {
2232 auto Op0 = Ops[BestPair.first];
2233 auto Op1 = Ops[BestPair.second];
2234 Ops.
erase(&Ops[BestPair.second]);
2235 Ops.
erase(&Ops[BestPair.first]);
2242 RewriteExprTree(I, Ops);
2262 while (!Worklist.
empty() && Ops.
size() <= GlobalReassociateLimit) {
2276 if (Ops.
size() > GlobalReassociateLimit)
2280 unsigned BinaryIdx = I.
getOpcode() - Instruction::BinaryOpsBegin;
2282 for (
unsigned i = 0; i < Ops.
size() - 1; ++i) {
2283 for (
unsigned j = i + 1; j < Ops.
size(); ++j) {
2285 Value *Op0 = Ops[i];
2286 Value *Op1 = Ops[j];
2287 if (std::less<Value *>()(Op1, Op0))
2289 if (!Visited.
insert({Op0, Op1}).second)
2291 auto res = PairMap[BinaryIdx].insert({{Op0, Op1}, 1});
2293 ++res.first->second;
2308 BuildRankMap(F, RPOT);
2325 assert(RankMap.count(&*BI) &&
"BB should be ranked.");
2332 assert(II->getParent() == &*BI &&
"Moved to a different block!");
2343 while (!ToRedo.empty()) {
2346 RecursivelyEraseDeadInsts(I, ToRedo);
2353 while (!RedoInsts.empty()) {
2355 RedoInsts.erase(RedoInsts.begin());
2365 ValueRankMap.clear();
2366 for (
auto &Entry : PairMap)
2392 if (skipFunction(F))
2396 auto PA = Impl.
run(F, DummyFAM);
2411 "Reassociate expressions",
false,
false)
2415 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.
const_iterator end(StringRef path)
Get end iterator over path.
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.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static BinaryOperator * LowerNegateToMultiply(Instruction *Neg)
Replace 0-X with X*-1.
This class represents lattice values for constants.
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:
void push_back(const T &Elt)
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.
bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in .dbg intrinsics with undef.
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)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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.
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 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)
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.
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.
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.
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)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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...
void emplace_back(ArgTypes &&... Args)
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...
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 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.
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...
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 &)