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