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