1 //===-- ConstraintElimination.cpp - Eliminate conds using constraints. ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Eliminate conditions based on constraints collected from dominating 10 // conditions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/ConstraintElimination.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/ScopeExit.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/ConstraintSystem.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/Instructions.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/DebugCounter.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Transforms/Scalar.h" 33 34 #include <string> 35 36 using namespace llvm; 37 using namespace PatternMatch; 38 39 #define DEBUG_TYPE "constraint-elimination" 40 41 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 42 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 43 "Controls which conditions are eliminated"); 44 45 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 46 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 47 48 namespace { 49 50 class ConstraintInfo; 51 52 struct StackEntry { 53 unsigned NumIn; 54 unsigned NumOut; 55 bool IsNot; 56 bool IsSigned = false; 57 /// Variables that can be removed from the system once the stack entry gets 58 /// removed. 59 SmallVector<Value *, 2> ValuesToRelease; 60 61 StackEntry(unsigned NumIn, unsigned NumOut, bool IsNot, bool IsSigned, 62 SmallVector<Value *, 2> ValuesToRelease) 63 : NumIn(NumIn), NumOut(NumOut), IsNot(IsNot), IsSigned(IsSigned), 64 ValuesToRelease(ValuesToRelease) {} 65 }; 66 67 /// Struct to express a pre-condition of the form %Op0 Pred %Op1. 68 struct PreconditionTy { 69 CmpInst::Predicate Pred; 70 Value *Op0; 71 Value *Op1; 72 73 PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 74 : Pred(Pred), Op0(Op0), Op1(Op1) {} 75 }; 76 77 struct ConstraintTy { 78 SmallVector<int64_t, 8> Coefficients; 79 SmallVector<PreconditionTy, 2> Preconditions; 80 81 bool IsSigned = false; 82 bool IsEq = false; 83 84 ConstraintTy() = default; 85 86 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned) 87 : Coefficients(Coefficients), IsSigned(IsSigned) {} 88 89 unsigned size() const { return Coefficients.size(); } 90 91 unsigned empty() const { return Coefficients.empty(); } 92 93 /// Returns true if any constraint has a non-zero coefficient for any of the 94 /// newly added indices. Zero coefficients for new indices are removed. If it 95 /// returns true, no new variable need to be added to the system. 96 bool needsNewIndices(const DenseMap<Value *, unsigned> &NewIndices) { 97 for (unsigned I = 0; I < NewIndices.size(); ++I) { 98 int64_t Last = Coefficients.pop_back_val(); 99 if (Last != 0) 100 return true; 101 } 102 return false; 103 } 104 105 /// Returns true if all preconditions for this list of constraints are 106 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 107 bool isValid(const ConstraintInfo &Info) const; 108 }; 109 110 /// Wrapper encapsulating separate constraint systems and corresponding value 111 /// mappings for both unsigned and signed information. Facts are added to and 112 /// conditions are checked against the corresponding system depending on the 113 /// signed-ness of their predicates. While the information is kept separate 114 /// based on signed-ness, certain conditions can be transferred between the two 115 /// systems. 116 class ConstraintInfo { 117 DenseMap<Value *, unsigned> UnsignedValue2Index; 118 DenseMap<Value *, unsigned> SignedValue2Index; 119 120 ConstraintSystem UnsignedCS; 121 ConstraintSystem SignedCS; 122 123 public: 124 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 125 return Signed ? SignedValue2Index : UnsignedValue2Index; 126 } 127 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 128 return Signed ? SignedValue2Index : UnsignedValue2Index; 129 } 130 131 ConstraintSystem &getCS(bool Signed) { 132 return Signed ? SignedCS : UnsignedCS; 133 } 134 const ConstraintSystem &getCS(bool Signed) const { 135 return Signed ? SignedCS : UnsignedCS; 136 } 137 138 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 139 void popLastNVariables(bool Signed, unsigned N) { 140 getCS(Signed).popLastNVariables(N); 141 } 142 143 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 144 145 void addFact(CmpInst *Condition, bool IsNegated, unsigned NumIn, 146 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 147 148 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 149 /// constraints, using indices from the corresponding constraint system. 150 /// Additional indices for newly discovered values are added to \p NewIndices. 151 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 152 DenseMap<Value *, unsigned> &NewIndices) const; 153 154 /// Turn a condition \p CmpI into a vector of constraints, using indices from 155 /// the corresponding constraint system. Additional indices for newly 156 /// discovered values are added to \p NewIndices. 157 ConstraintTy getConstraint(CmpInst *Cmp, 158 DenseMap<Value *, unsigned> &NewIndices) const { 159 return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0), 160 Cmp->getOperand(1), NewIndices); 161 } 162 }; 163 164 } // namespace 165 166 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The 167 // sum of the pairs equals \p V. The first pair is the constant-factor and X 168 // must be nullptr. If the expression cannot be decomposed, returns an empty 169 // vector. 170 static SmallVector<std::pair<int64_t, Value *>, 4> 171 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions, 172 bool IsSigned) { 173 174 auto CanUseSExt = [](ConstantInt *CI) { 175 const APInt &Val = CI->getValue(); 176 return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 177 }; 178 // Decompose \p V used with a signed predicate. 179 if (IsSigned) { 180 if (auto *CI = dyn_cast<ConstantInt>(V)) { 181 if (CanUseSExt(CI)) 182 return {{CI->getSExtValue(), nullptr}}; 183 } 184 185 return {{0, nullptr}, {1, V}}; 186 } 187 188 if (auto *CI = dyn_cast<ConstantInt>(V)) { 189 if (CI->uge(MaxConstraintValue)) 190 return {}; 191 return {{CI->getZExtValue(), nullptr}}; 192 } 193 auto *GEP = dyn_cast<GetElementPtrInst>(V); 194 if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) { 195 Value *Op0, *Op1; 196 ConstantInt *CI; 197 198 // If the index is zero-extended, it is guaranteed to be positive. 199 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 200 m_ZExt(m_Value(Op0)))) { 201 if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && 202 CanUseSExt(CI)) 203 return {{0, nullptr}, 204 {1, GEP->getPointerOperand()}, 205 {std::pow(int64_t(2), CI->getSExtValue()), Op1}}; 206 if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI))) && 207 CanUseSExt(CI)) 208 return {{CI->getSExtValue(), nullptr}, 209 {1, GEP->getPointerOperand()}, 210 {1, Op1}}; 211 return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 212 } 213 214 if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) && 215 !CI->isNegative() && CanUseSExt(CI)) 216 return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}}; 217 218 SmallVector<std::pair<int64_t, Value *>, 4> Result; 219 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 220 m_NUWShl(m_Value(Op0), m_ConstantInt(CI))) && 221 CanUseSExt(CI)) 222 Result = {{0, nullptr}, 223 {1, GEP->getPointerOperand()}, 224 {std::pow(int64_t(2), CI->getSExtValue()), Op0}}; 225 else if (match(GEP->getOperand(GEP->getNumOperands() - 1), 226 m_NSWAdd(m_Value(Op0), m_ConstantInt(CI))) && 227 CanUseSExt(CI)) 228 Result = {{CI->getSExtValue(), nullptr}, 229 {1, GEP->getPointerOperand()}, 230 {1, Op0}}; 231 else { 232 Op0 = GEP->getOperand(GEP->getNumOperands() - 1); 233 Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 234 } 235 // If Op0 is signed non-negative, the GEP is increasing monotonically and 236 // can be de-composed. 237 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 238 ConstantInt::get(Op0->getType(), 0)); 239 return Result; 240 } 241 242 Value *Op0; 243 if (match(V, m_ZExt(m_Value(Op0)))) 244 V = Op0; 245 246 Value *Op1; 247 ConstantInt *CI; 248 if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))) && 249 !CI->uge(MaxConstraintValue)) 250 return {{CI->getZExtValue(), nullptr}, {1, Op0}}; 251 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 252 CanUseSExt(CI)) { 253 Preconditions.emplace_back( 254 CmpInst::ICMP_UGE, Op0, 255 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 256 return {{CI->getSExtValue(), nullptr}, {1, Op0}}; 257 } 258 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) 259 return {{0, nullptr}, {1, Op0}, {1, Op1}}; 260 261 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && CanUseSExt(CI)) 262 return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}}; 263 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 264 return {{0, nullptr}, {1, Op0}, {-1, Op1}}; 265 266 return {{0, nullptr}, {1, V}}; 267 } 268 269 ConstraintTy 270 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 271 DenseMap<Value *, unsigned> &NewIndices) const { 272 bool IsEq = false; 273 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 274 switch (Pred) { 275 case CmpInst::ICMP_UGT: 276 case CmpInst::ICMP_UGE: 277 case CmpInst::ICMP_SGT: 278 case CmpInst::ICMP_SGE: { 279 Pred = CmpInst::getSwappedPredicate(Pred); 280 std::swap(Op0, Op1); 281 break; 282 } 283 case CmpInst::ICMP_EQ: 284 if (match(Op1, m_Zero())) { 285 Pred = CmpInst::ICMP_ULE; 286 } else { 287 IsEq = true; 288 Pred = CmpInst::ICMP_ULE; 289 } 290 break; 291 case CmpInst::ICMP_NE: 292 if (!match(Op1, m_Zero())) 293 return {}; 294 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 295 std::swap(Op0, Op1); 296 break; 297 default: 298 break; 299 } 300 301 // Only ULE and ULT predicates are supported at the moment. 302 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 303 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 304 return {}; 305 306 SmallVector<PreconditionTy, 4> Preconditions; 307 bool IsSigned = CmpInst::isSigned(Pred); 308 auto &Value2Index = getValue2Index(IsSigned); 309 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 310 Preconditions, IsSigned); 311 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 312 Preconditions, IsSigned); 313 // Skip if decomposing either of the values failed. 314 if (ADec.empty() || BDec.empty()) 315 return {}; 316 317 int64_t Offset1 = ADec[0].first; 318 int64_t Offset2 = BDec[0].first; 319 Offset1 *= -1; 320 321 // Create iterator ranges that skip the constant-factor. 322 auto VariablesA = llvm::drop_begin(ADec); 323 auto VariablesB = llvm::drop_begin(BDec); 324 325 // First try to look up \p V in Value2Index and NewIndices. Otherwise add a 326 // new entry to NewIndices. 327 auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned { 328 auto V2I = Value2Index.find(V); 329 if (V2I != Value2Index.end()) 330 return V2I->second; 331 auto Insert = 332 NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1}); 333 return Insert.first->second; 334 }; 335 336 // Make sure all variables have entries in Value2Index or NewIndices. 337 for (const auto &KV : 338 concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB)) 339 GetOrAddIndex(KV.second); 340 341 // Build result constraint, by first adding all coefficients from A and then 342 // subtracting all coefficients from B. 343 ConstraintTy Res( 344 SmallVector<int64_t, 8>(Value2Index.size() + NewIndices.size() + 1, 0), 345 IsSigned); 346 Res.IsEq = IsEq; 347 auto &R = Res.Coefficients; 348 for (const auto &KV : VariablesA) 349 R[GetOrAddIndex(KV.second)] += KV.first; 350 351 for (const auto &KV : VariablesB) 352 R[GetOrAddIndex(KV.second)] -= KV.first; 353 354 int64_t OffsetSum; 355 if (AddOverflow(Offset1, Offset2, OffsetSum)) 356 return {}; 357 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 358 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 359 return {}; 360 R[0] = OffsetSum; 361 Res.Preconditions = std::move(Preconditions); 362 return Res; 363 } 364 365 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 366 return Coefficients.size() > 0 && 367 all_of(Preconditions, [&Info](const PreconditionTy &C) { 368 return Info.doesHold(C.Pred, C.Op0, C.Op1); 369 }); 370 } 371 372 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 373 Value *B) const { 374 DenseMap<Value *, unsigned> NewIndices; 375 auto R = getConstraint(Pred, A, B, NewIndices); 376 377 if (!NewIndices.empty()) 378 return false; 379 380 // TODO: properly check NewIndices. 381 return NewIndices.empty() && R.Preconditions.empty() && !R.IsEq && 382 !R.empty() && 383 getCS(CmpInst::isSigned(Pred)).isConditionImplied(R.Coefficients); 384 } 385 386 namespace { 387 /// Represents either a condition that holds on entry to a block or a basic 388 /// block, with their respective Dominator DFS in and out numbers. 389 struct ConstraintOrBlock { 390 unsigned NumIn; 391 unsigned NumOut; 392 bool IsBlock; 393 bool Not; 394 union { 395 BasicBlock *BB; 396 CmpInst *Condition; 397 }; 398 399 ConstraintOrBlock(DomTreeNode *DTN) 400 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 401 BB(DTN->getBlock()) {} 402 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 403 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 404 Not(Not), Condition(Condition) {} 405 }; 406 407 /// Keep state required to build worklist. 408 struct State { 409 DominatorTree &DT; 410 SmallVector<ConstraintOrBlock, 64> WorkList; 411 412 State(DominatorTree &DT) : DT(DT) {} 413 414 /// Process block \p BB and add known facts to work-list. 415 void addInfoFor(BasicBlock &BB); 416 417 /// Returns true if we can add a known condition from BB to its successor 418 /// block Succ. Each predecessor of Succ can either be BB or be dominated 419 /// by Succ (e.g. the case when adding a condition from a pre-header to a 420 /// loop header). 421 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 422 if (BB.getSingleSuccessor()) { 423 assert(BB.getSingleSuccessor() == Succ); 424 return DT.properlyDominates(&BB, Succ); 425 } 426 return any_of(successors(&BB), 427 [Succ](const BasicBlock *S) { return S != Succ; }) && 428 all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) { 429 return Pred == &BB || DT.dominates(Succ, Pred); 430 }); 431 } 432 }; 433 434 } // namespace 435 436 #ifndef NDEBUG 437 static void dumpWithNames(const ConstraintSystem &CS, 438 DenseMap<Value *, unsigned> &Value2Index) { 439 SmallVector<std::string> Names(Value2Index.size(), ""); 440 for (auto &KV : Value2Index) { 441 Names[KV.second - 1] = std::string("%") + KV.first->getName().str(); 442 } 443 CS.dump(Names); 444 } 445 446 static void dumpWithNames(ArrayRef<int64_t> C, 447 DenseMap<Value *, unsigned> &Value2Index) { 448 ConstraintSystem CS; 449 CS.addVariableRowFill(C); 450 dumpWithNames(CS, Value2Index); 451 } 452 #endif 453 454 void State::addInfoFor(BasicBlock &BB) { 455 WorkList.emplace_back(DT.getNode(&BB)); 456 457 // True as long as long as the current instruction is guaranteed to execute. 458 bool GuaranteedToExecute = true; 459 // Scan BB for assume calls. 460 // TODO: also use this scan to queue conditions to simplify, so we can 461 // interleave facts from assumes and conditions to simplify in a single 462 // basic block. And to skip another traversal of each basic block when 463 // simplifying. 464 for (Instruction &I : BB) { 465 Value *Cond; 466 // For now, just handle assumes with a single compare as condition. 467 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 468 isa<ICmpInst>(Cond)) { 469 if (GuaranteedToExecute) { 470 // The assume is guaranteed to execute when BB is entered, hence Cond 471 // holds on entry to BB. 472 WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false); 473 } else { 474 // Otherwise the condition only holds in the successors. 475 for (BasicBlock *Succ : successors(&BB)) { 476 if (!canAddSuccessor(BB, Succ)) 477 continue; 478 WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false); 479 } 480 } 481 } 482 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 483 } 484 485 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 486 if (!Br || !Br->isConditional()) 487 return; 488 489 // If the condition is an OR of 2 compares and the false successor only has 490 // the current block as predecessor, queue both negated conditions for the 491 // false successor. 492 Value *Op0, *Op1; 493 if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) && 494 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 495 BasicBlock *FalseSuccessor = Br->getSuccessor(1); 496 if (canAddSuccessor(BB, FalseSuccessor)) { 497 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0), 498 true); 499 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1), 500 true); 501 } 502 return; 503 } 504 505 // If the condition is an AND of 2 compares and the true successor only has 506 // the current block as predecessor, queue both conditions for the true 507 // successor. 508 if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) && 509 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 510 BasicBlock *TrueSuccessor = Br->getSuccessor(0); 511 if (canAddSuccessor(BB, TrueSuccessor)) { 512 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0), 513 false); 514 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1), 515 false); 516 } 517 return; 518 } 519 520 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 521 if (!CmpI) 522 return; 523 if (canAddSuccessor(BB, Br->getSuccessor(0))) 524 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 525 if (canAddSuccessor(BB, Br->getSuccessor(1))) 526 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 527 } 528 529 void ConstraintInfo::addFact(CmpInst *Condition, bool IsNegated, unsigned NumIn, 530 unsigned NumOut, 531 SmallVectorImpl<StackEntry> &DFSInStack) { 532 // If the constraint has a pre-condition, skip the constraint if it does not 533 // hold. 534 DenseMap<Value *, unsigned> NewIndices; 535 auto R = getConstraint(Condition, NewIndices); 536 if (!R.isValid(*this)) 537 return; 538 539 LLVM_DEBUG(dbgs() << "Adding " << *Condition << " " << IsNegated << "\n"); 540 bool Added = false; 541 assert(CmpInst::isSigned(Condition->getPredicate()) == R.IsSigned && 542 "condition and constraint signs must match"); 543 auto &CSToUse = getCS(R.IsSigned); 544 if (R.Coefficients.empty()) 545 return; 546 547 Added |= CSToUse.addVariableRowFill(R.Coefficients); 548 549 // If R has been added to the system, queue it for removal once it goes 550 // out-of-scope. 551 if (Added) { 552 SmallVector<Value *, 2> ValuesToRelease; 553 for (auto &KV : NewIndices) { 554 getValue2Index(R.IsSigned).insert(KV); 555 ValuesToRelease.push_back(KV.first); 556 } 557 558 LLVM_DEBUG({ 559 dbgs() << " constraint: "; 560 dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned)); 561 }); 562 563 DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned, 564 ValuesToRelease); 565 566 if (R.IsEq) { 567 // Also add the inverted constraint for equality constraints. 568 for (auto &Coeff : R.Coefficients) 569 Coeff *= -1; 570 CSToUse.addVariableRowFill(R.Coefficients); 571 572 DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned, 573 SmallVector<Value *, 2>()); 574 } 575 } 576 } 577 578 static void 579 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 580 SmallVectorImpl<Instruction *> &ToRemove) { 581 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 582 ConstraintInfo &Info) { 583 DenseMap<Value *, unsigned> NewIndices; 584 auto R = Info.getConstraint(Pred, A, B, NewIndices); 585 if (R.size() < 2 || R.needsNewIndices(NewIndices) || !R.isValid(Info)) 586 return false; 587 588 auto &CSToUse = Info.getCS(CmpInst::isSigned(Pred)); 589 return CSToUse.isConditionImplied(R.Coefficients); 590 }; 591 592 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 593 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 594 // can be simplified to a regular sub. 595 Value *A = II->getArgOperand(0); 596 Value *B = II->getArgOperand(1); 597 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 598 !DoesConditionHold(CmpInst::ICMP_SGE, B, 599 ConstantInt::get(A->getType(), 0), Info)) 600 return; 601 602 IRBuilder<> Builder(II->getParent(), II->getIterator()); 603 Value *Sub = nullptr; 604 for (User *U : make_early_inc_range(II->users())) { 605 if (match(U, m_ExtractValue<0>(m_Value()))) { 606 if (!Sub) 607 Sub = Builder.CreateSub(A, B); 608 U->replaceAllUsesWith(Sub); 609 } else if (match(U, m_ExtractValue<1>(m_Value()))) 610 U->replaceAllUsesWith(Builder.getFalse()); 611 else 612 continue; 613 614 if (U->use_empty()) { 615 auto *I = cast<Instruction>(U); 616 ToRemove.push_back(I); 617 I->setOperand(0, PoisonValue::get(II->getType())); 618 } 619 } 620 621 if (II->use_empty()) 622 II->eraseFromParent(); 623 } 624 } 625 626 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 627 bool Changed = false; 628 DT.updateDFSNumbers(); 629 630 ConstraintInfo Info; 631 State S(DT); 632 633 // First, collect conditions implied by branches and blocks with their 634 // Dominator DFS in and out numbers. 635 for (BasicBlock &BB : F) { 636 if (!DT.getNode(&BB)) 637 continue; 638 S.addInfoFor(BB); 639 } 640 641 // Next, sort worklist by dominance, so that dominating blocks and conditions 642 // come before blocks and conditions dominated by them. If a block and a 643 // condition have the same numbers, the condition comes before the block, as 644 // it holds on entry to the block. 645 sort(S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 646 return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock); 647 }); 648 649 SmallVector<Instruction *> ToRemove; 650 651 // Finally, process ordered worklist and eliminate implied conditions. 652 SmallVector<StackEntry, 16> DFSInStack; 653 for (ConstraintOrBlock &CB : S.WorkList) { 654 // First, pop entries from the stack that are out-of-scope for CB. Remove 655 // the corresponding entry from the constraint system. 656 while (!DFSInStack.empty()) { 657 auto &E = DFSInStack.back(); 658 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 659 << "\n"); 660 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 661 assert(E.NumIn <= CB.NumIn); 662 if (CB.NumOut <= E.NumOut) 663 break; 664 LLVM_DEBUG({ 665 dbgs() << "Removing "; 666 dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(), 667 Info.getValue2Index(E.IsSigned)); 668 dbgs() << "\n"; 669 }); 670 671 Info.popLastConstraint(E.IsSigned); 672 // Remove variables in the system that went out of scope. 673 auto &Mapping = Info.getValue2Index(E.IsSigned); 674 for (Value *V : E.ValuesToRelease) 675 Mapping.erase(V); 676 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 677 DFSInStack.pop_back(); 678 } 679 680 LLVM_DEBUG({ 681 dbgs() << "Processing "; 682 if (CB.IsBlock) 683 dbgs() << *CB.BB; 684 else 685 dbgs() << *CB.Condition; 686 dbgs() << "\n"; 687 }); 688 689 // For a block, check if any CmpInsts become known based on the current set 690 // of constraints. 691 if (CB.IsBlock) { 692 for (Instruction &I : make_early_inc_range(*CB.BB)) { 693 if (auto *II = dyn_cast<WithOverflowInst>(&I)) { 694 tryToSimplifyOverflowMath(II, Info, ToRemove); 695 continue; 696 } 697 auto *Cmp = dyn_cast<ICmpInst>(&I); 698 if (!Cmp) 699 continue; 700 701 DenseMap<Value *, unsigned> NewIndices; 702 auto R = Info.getConstraint(Cmp, NewIndices); 703 if (R.IsEq || R.empty() || R.needsNewIndices(NewIndices) || 704 !R.isValid(Info)) 705 continue; 706 707 auto &CSToUse = Info.getCS(R.IsSigned); 708 if (CSToUse.isConditionImplied(R.Coefficients)) { 709 if (!DebugCounter::shouldExecute(EliminatedCounter)) 710 continue; 711 712 LLVM_DEBUG({ 713 dbgs() << "Condition " << *Cmp 714 << " implied by dominating constraints\n"; 715 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 716 }); 717 Cmp->replaceUsesWithIf( 718 ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) { 719 // Conditions in an assume trivially simplify to true. Skip uses 720 // in assume calls to not destroy the available information. 721 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 722 return !II || II->getIntrinsicID() != Intrinsic::assume; 723 }); 724 NumCondsRemoved++; 725 Changed = true; 726 } 727 if (CSToUse.isConditionImplied( 728 ConstraintSystem::negate(R.Coefficients))) { 729 if (!DebugCounter::shouldExecute(EliminatedCounter)) 730 continue; 731 732 LLVM_DEBUG({ 733 dbgs() << "Condition !" << *Cmp 734 << " implied by dominating constraints\n"; 735 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 736 }); 737 Cmp->replaceAllUsesWith( 738 ConstantInt::getFalse(F.getParent()->getContext())); 739 NumCondsRemoved++; 740 Changed = true; 741 } 742 } 743 continue; 744 } 745 746 // Set up a function to restore the predicate at the end of the scope if it 747 // has been negated. Negate the predicate in-place, if required. 748 auto *CI = dyn_cast<ICmpInst>(CB.Condition); 749 auto PredicateRestorer = make_scope_exit([CI, &CB]() { 750 if (CB.Not && CI) 751 CI->setPredicate(CI->getInversePredicate()); 752 }); 753 if (CB.Not) { 754 if (CI) { 755 CI->setPredicate(CI->getInversePredicate()); 756 } else { 757 LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n"); 758 continue; 759 } 760 } 761 762 // Otherwise, add the condition to the system and stack, if we can transform 763 // it into a constraint. 764 Info.addFact(CB.Condition, CB.Not, CB.NumIn, CB.NumOut, DFSInStack); 765 } 766 767 #ifndef NDEBUG 768 unsigned SignedEntries = 769 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 770 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 771 "updates to CS and DFSInStack are out of sync"); 772 assert(Info.getCS(true).size() == SignedEntries && 773 "updates to CS and DFSInStack are out of sync"); 774 #endif 775 776 for (Instruction *I : ToRemove) 777 I->eraseFromParent(); 778 return Changed; 779 } 780 781 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 782 FunctionAnalysisManager &AM) { 783 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 784 if (!eliminateConstraints(F, DT)) 785 return PreservedAnalyses::all(); 786 787 PreservedAnalyses PA; 788 PA.preserve<DominatorTreeAnalysis>(); 789 PA.preserveSet<CFGAnalyses>(); 790 return PA; 791 } 792 793 namespace { 794 795 class ConstraintElimination : public FunctionPass { 796 public: 797 static char ID; 798 799 ConstraintElimination() : FunctionPass(ID) { 800 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 801 } 802 803 bool runOnFunction(Function &F) override { 804 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 805 return eliminateConstraints(F, DT); 806 } 807 808 void getAnalysisUsage(AnalysisUsage &AU) const override { 809 AU.setPreservesCFG(); 810 AU.addRequired<DominatorTreeWrapperPass>(); 811 AU.addPreserved<GlobalsAAWrapperPass>(); 812 AU.addPreserved<DominatorTreeWrapperPass>(); 813 } 814 }; 815 816 } // end anonymous namespace 817 818 char ConstraintElimination::ID = 0; 819 820 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 821 "Constraint Elimination", false, false) 822 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 823 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 824 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 825 "Constraint Elimination", false, false) 826 827 FunctionPass *llvm::createConstraintEliminationPass() { 828 return new ConstraintElimination(); 829 } 830