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