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