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_SLT: 407 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) 408 addFact(CmpInst::ICMP_ULT, A, B, IsNegated, NumIn, NumOut, DFSInStack); 409 break; 410 case CmpInst::ICMP_SGT: 411 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 412 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), 413 IsNegated, NumIn, NumOut, DFSInStack); 414 break; 415 case CmpInst::ICMP_SGE: 416 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 417 addFact(CmpInst::ICMP_UGE, A, B, IsNegated, NumIn, NumOut, DFSInStack); 418 } 419 break; 420 } 421 } 422 423 namespace { 424 /// Represents either a condition that holds on entry to a block or a basic 425 /// block, with their respective Dominator DFS in and out numbers. 426 struct ConstraintOrBlock { 427 unsigned NumIn; 428 unsigned NumOut; 429 bool IsBlock; 430 bool Not; 431 union { 432 BasicBlock *BB; 433 CmpInst *Condition; 434 }; 435 436 ConstraintOrBlock(DomTreeNode *DTN) 437 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 438 BB(DTN->getBlock()) {} 439 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 440 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 441 Not(Not), Condition(Condition) {} 442 }; 443 444 /// Keep state required to build worklist. 445 struct State { 446 DominatorTree &DT; 447 SmallVector<ConstraintOrBlock, 64> WorkList; 448 449 State(DominatorTree &DT) : DT(DT) {} 450 451 /// Process block \p BB and add known facts to work-list. 452 void addInfoFor(BasicBlock &BB); 453 454 /// Returns true if we can add a known condition from BB to its successor 455 /// block Succ. Each predecessor of Succ can either be BB or be dominated 456 /// by Succ (e.g. the case when adding a condition from a pre-header to a 457 /// loop header). 458 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 459 if (BB.getSingleSuccessor()) { 460 assert(BB.getSingleSuccessor() == Succ); 461 return DT.properlyDominates(&BB, Succ); 462 } 463 return any_of(successors(&BB), 464 [Succ](const BasicBlock *S) { return S != Succ; }) && 465 all_of(predecessors(Succ), [&BB, Succ, this](BasicBlock *Pred) { 466 return Pred == &BB || DT.dominates(Succ, Pred); 467 }); 468 } 469 }; 470 471 } // namespace 472 473 #ifndef NDEBUG 474 static void dumpWithNames(const ConstraintSystem &CS, 475 DenseMap<Value *, unsigned> &Value2Index) { 476 SmallVector<std::string> Names(Value2Index.size(), ""); 477 for (auto &KV : Value2Index) { 478 Names[KV.second - 1] = std::string("%") + KV.first->getName().str(); 479 } 480 CS.dump(Names); 481 } 482 483 static void dumpWithNames(ArrayRef<int64_t> C, 484 DenseMap<Value *, unsigned> &Value2Index) { 485 ConstraintSystem CS; 486 CS.addVariableRowFill(C); 487 dumpWithNames(CS, Value2Index); 488 } 489 #endif 490 491 void State::addInfoFor(BasicBlock &BB) { 492 WorkList.emplace_back(DT.getNode(&BB)); 493 494 // True as long as long as the current instruction is guaranteed to execute. 495 bool GuaranteedToExecute = true; 496 // Scan BB for assume calls. 497 // TODO: also use this scan to queue conditions to simplify, so we can 498 // interleave facts from assumes and conditions to simplify in a single 499 // basic block. And to skip another traversal of each basic block when 500 // simplifying. 501 for (Instruction &I : BB) { 502 Value *Cond; 503 // For now, just handle assumes with a single compare as condition. 504 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 505 isa<ICmpInst>(Cond)) { 506 if (GuaranteedToExecute) { 507 // The assume is guaranteed to execute when BB is entered, hence Cond 508 // holds on entry to BB. 509 WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false); 510 } else { 511 // Otherwise the condition only holds in the successors. 512 for (BasicBlock *Succ : successors(&BB)) { 513 if (!canAddSuccessor(BB, Succ)) 514 continue; 515 WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), false); 516 } 517 } 518 } 519 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 520 } 521 522 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 523 if (!Br || !Br->isConditional()) 524 return; 525 526 // If the condition is an OR of 2 compares and the false successor only has 527 // the current block as predecessor, queue both negated conditions for the 528 // false successor. 529 Value *Op0, *Op1; 530 if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) && 531 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 532 BasicBlock *FalseSuccessor = Br->getSuccessor(1); 533 if (canAddSuccessor(BB, FalseSuccessor)) { 534 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0), 535 true); 536 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1), 537 true); 538 } 539 return; 540 } 541 542 // If the condition is an AND of 2 compares and the true successor only has 543 // the current block as predecessor, queue both conditions for the true 544 // successor. 545 if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) && 546 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 547 BasicBlock *TrueSuccessor = Br->getSuccessor(0); 548 if (canAddSuccessor(BB, TrueSuccessor)) { 549 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0), 550 false); 551 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1), 552 false); 553 } 554 return; 555 } 556 557 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 558 if (!CmpI) 559 return; 560 if (canAddSuccessor(BB, Br->getSuccessor(0))) 561 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 562 if (canAddSuccessor(BB, Br->getSuccessor(1))) 563 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 564 } 565 566 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 567 bool IsNegated, unsigned NumIn, unsigned NumOut, 568 SmallVectorImpl<StackEntry> &DFSInStack) { 569 // If the constraint has a pre-condition, skip the constraint if it does not 570 // hold. 571 DenseMap<Value *, unsigned> NewIndices; 572 auto R = getConstraint(Pred, A, B, NewIndices); 573 if (!R.isValid(*this)) 574 return; 575 576 //LLVM_DEBUG(dbgs() << "Adding " << *Condition << " " << IsNegated << "\n"); 577 bool Added = false; 578 assert(CmpInst::isSigned(Pred) == R.IsSigned && 579 "condition and constraint signs must match"); 580 auto &CSToUse = getCS(R.IsSigned); 581 if (R.Coefficients.empty()) 582 return; 583 584 Added |= CSToUse.addVariableRowFill(R.Coefficients); 585 586 // If R has been added to the system, queue it for removal once it goes 587 // out-of-scope. 588 if (Added) { 589 SmallVector<Value *, 2> ValuesToRelease; 590 for (auto &KV : NewIndices) { 591 getValue2Index(R.IsSigned).insert(KV); 592 ValuesToRelease.push_back(KV.first); 593 } 594 595 LLVM_DEBUG({ 596 dbgs() << " constraint: "; 597 dumpWithNames(R.Coefficients, getValue2Index(R.IsSigned)); 598 }); 599 600 DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned, 601 ValuesToRelease); 602 603 if (R.IsEq) { 604 // Also add the inverted constraint for equality constraints. 605 for (auto &Coeff : R.Coefficients) 606 Coeff *= -1; 607 CSToUse.addVariableRowFill(R.Coefficients); 608 609 DFSInStack.emplace_back(NumIn, NumOut, IsNegated, R.IsSigned, 610 SmallVector<Value *, 2>()); 611 } 612 } 613 } 614 615 static void 616 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 617 SmallVectorImpl<Instruction *> &ToRemove) { 618 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 619 ConstraintInfo &Info) { 620 DenseMap<Value *, unsigned> NewIndices; 621 auto R = Info.getConstraint(Pred, A, B, NewIndices); 622 if (R.size() < 2 || R.needsNewIndices(NewIndices) || !R.isValid(Info)) 623 return false; 624 625 auto &CSToUse = Info.getCS(CmpInst::isSigned(Pred)); 626 return CSToUse.isConditionImplied(R.Coefficients); 627 }; 628 629 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 630 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 631 // can be simplified to a regular sub. 632 Value *A = II->getArgOperand(0); 633 Value *B = II->getArgOperand(1); 634 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 635 !DoesConditionHold(CmpInst::ICMP_SGE, B, 636 ConstantInt::get(A->getType(), 0), Info)) 637 return; 638 639 IRBuilder<> Builder(II->getParent(), II->getIterator()); 640 Value *Sub = nullptr; 641 for (User *U : make_early_inc_range(II->users())) { 642 if (match(U, m_ExtractValue<0>(m_Value()))) { 643 if (!Sub) 644 Sub = Builder.CreateSub(A, B); 645 U->replaceAllUsesWith(Sub); 646 } else if (match(U, m_ExtractValue<1>(m_Value()))) 647 U->replaceAllUsesWith(Builder.getFalse()); 648 else 649 continue; 650 651 if (U->use_empty()) { 652 auto *I = cast<Instruction>(U); 653 ToRemove.push_back(I); 654 I->setOperand(0, PoisonValue::get(II->getType())); 655 } 656 } 657 658 if (II->use_empty()) 659 II->eraseFromParent(); 660 } 661 } 662 663 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 664 bool Changed = false; 665 DT.updateDFSNumbers(); 666 667 ConstraintInfo Info; 668 State S(DT); 669 670 // First, collect conditions implied by branches and blocks with their 671 // Dominator DFS in and out numbers. 672 for (BasicBlock &BB : F) { 673 if (!DT.getNode(&BB)) 674 continue; 675 S.addInfoFor(BB); 676 } 677 678 // Next, sort worklist by dominance, so that dominating blocks and conditions 679 // come before blocks and conditions dominated by them. If a block and a 680 // condition have the same numbers, the condition comes before the block, as 681 // it holds on entry to the block. 682 sort(S.WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 683 return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock); 684 }); 685 686 SmallVector<Instruction *> ToRemove; 687 688 // Finally, process ordered worklist and eliminate implied conditions. 689 SmallVector<StackEntry, 16> DFSInStack; 690 for (ConstraintOrBlock &CB : S.WorkList) { 691 // First, pop entries from the stack that are out-of-scope for CB. Remove 692 // the corresponding entry from the constraint system. 693 while (!DFSInStack.empty()) { 694 auto &E = DFSInStack.back(); 695 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 696 << "\n"); 697 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 698 assert(E.NumIn <= CB.NumIn); 699 if (CB.NumOut <= E.NumOut) 700 break; 701 LLVM_DEBUG({ 702 dbgs() << "Removing "; 703 dumpWithNames(Info.getCS(E.IsSigned).getLastConstraint(), 704 Info.getValue2Index(E.IsSigned)); 705 dbgs() << "\n"; 706 }); 707 708 Info.popLastConstraint(E.IsSigned); 709 // Remove variables in the system that went out of scope. 710 auto &Mapping = Info.getValue2Index(E.IsSigned); 711 for (Value *V : E.ValuesToRelease) 712 Mapping.erase(V); 713 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 714 DFSInStack.pop_back(); 715 } 716 717 LLVM_DEBUG({ 718 dbgs() << "Processing "; 719 if (CB.IsBlock) 720 dbgs() << *CB.BB; 721 else 722 dbgs() << *CB.Condition; 723 dbgs() << "\n"; 724 }); 725 726 // For a block, check if any CmpInsts become known based on the current set 727 // of constraints. 728 if (CB.IsBlock) { 729 for (Instruction &I : make_early_inc_range(*CB.BB)) { 730 if (auto *II = dyn_cast<WithOverflowInst>(&I)) { 731 tryToSimplifyOverflowMath(II, Info, ToRemove); 732 continue; 733 } 734 auto *Cmp = dyn_cast<ICmpInst>(&I); 735 if (!Cmp) 736 continue; 737 738 DenseMap<Value *, unsigned> NewIndices; 739 auto R = Info.getConstraint(Cmp, NewIndices); 740 if (R.IsEq || R.empty() || R.needsNewIndices(NewIndices) || 741 !R.isValid(Info)) 742 continue; 743 744 auto &CSToUse = Info.getCS(R.IsSigned); 745 if (CSToUse.isConditionImplied(R.Coefficients)) { 746 if (!DebugCounter::shouldExecute(EliminatedCounter)) 747 continue; 748 749 LLVM_DEBUG({ 750 dbgs() << "Condition " << *Cmp 751 << " implied by dominating constraints\n"; 752 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 753 }); 754 Cmp->replaceUsesWithIf( 755 ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) { 756 // Conditions in an assume trivially simplify to true. Skip uses 757 // in assume calls to not destroy the available information. 758 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 759 return !II || II->getIntrinsicID() != Intrinsic::assume; 760 }); 761 NumCondsRemoved++; 762 Changed = true; 763 } 764 if (CSToUse.isConditionImplied( 765 ConstraintSystem::negate(R.Coefficients))) { 766 if (!DebugCounter::shouldExecute(EliminatedCounter)) 767 continue; 768 769 LLVM_DEBUG({ 770 dbgs() << "Condition !" << *Cmp 771 << " implied by dominating constraints\n"; 772 dumpWithNames(CSToUse, Info.getValue2Index(R.IsSigned)); 773 }); 774 Cmp->replaceAllUsesWith( 775 ConstantInt::getFalse(F.getParent()->getContext())); 776 NumCondsRemoved++; 777 Changed = true; 778 } 779 } 780 continue; 781 } 782 783 // Set up a function to restore the predicate at the end of the scope if it 784 // has been negated. Negate the predicate in-place, if required. 785 auto *CI = dyn_cast<ICmpInst>(CB.Condition); 786 auto PredicateRestorer = make_scope_exit([CI, &CB]() { 787 if (CB.Not && CI) 788 CI->setPredicate(CI->getInversePredicate()); 789 }); 790 if (CB.Not) { 791 if (CI) { 792 CI->setPredicate(CI->getInversePredicate()); 793 } else { 794 LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n"); 795 continue; 796 } 797 } 798 799 ICmpInst::Predicate Pred; 800 Value *A, *B; 801 if (match(CB.Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) { 802 // Otherwise, add the condition to the system and stack, if we can 803 // transform it into a constraint. 804 Info.addFact(Pred, A, B, CB.Not, CB.NumIn, CB.NumOut, DFSInStack); 805 Info.transferToOtherSystem(Pred, A, B, CB.Not, CB.NumIn, CB.NumOut, 806 DFSInStack); 807 } 808 } 809 810 #ifndef NDEBUG 811 unsigned SignedEntries = 812 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 813 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 814 "updates to CS and DFSInStack are out of sync"); 815 assert(Info.getCS(true).size() == SignedEntries && 816 "updates to CS and DFSInStack are out of sync"); 817 #endif 818 819 for (Instruction *I : ToRemove) 820 I->eraseFromParent(); 821 return Changed; 822 } 823 824 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 825 FunctionAnalysisManager &AM) { 826 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 827 if (!eliminateConstraints(F, DT)) 828 return PreservedAnalyses::all(); 829 830 PreservedAnalyses PA; 831 PA.preserve<DominatorTreeAnalysis>(); 832 PA.preserveSet<CFGAnalyses>(); 833 return PA; 834 } 835 836 namespace { 837 838 class ConstraintElimination : public FunctionPass { 839 public: 840 static char ID; 841 842 ConstraintElimination() : FunctionPass(ID) { 843 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 844 } 845 846 bool runOnFunction(Function &F) override { 847 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 848 return eliminateConstraints(F, DT); 849 } 850 851 void getAnalysisUsage(AnalysisUsage &AU) const override { 852 AU.setPreservesCFG(); 853 AU.addRequired<DominatorTreeWrapperPass>(); 854 AU.addPreserved<GlobalsAAWrapperPass>(); 855 AU.addPreserved<DominatorTreeWrapperPass>(); 856 } 857 }; 858 859 } // end anonymous namespace 860 861 char ConstraintElimination::ID = 0; 862 863 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 864 "Constraint Elimination", false, false) 865 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 866 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 867 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 868 "Constraint Elimination", false, false) 869 870 FunctionPass *llvm::createConstraintEliminationPass() { 871 return new ConstraintElimination(); 872 } 873