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