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/LoopInfo.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/Analysis/ScalarEvolution.h" 24 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/IRBuilder.h" 31 #include "llvm/IR/InstrTypes.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/PatternMatch.h" 34 #include "llvm/IR/Verifier.h" 35 #include "llvm/Pass.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/DebugCounter.h" 39 #include "llvm/Support/KnownBits.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Transforms/Utils/Cloning.h" 42 #include "llvm/Transforms/Utils/ValueMapper.h" 43 44 #include <cmath> 45 #include <optional> 46 #include <string> 47 48 using namespace llvm; 49 using namespace PatternMatch; 50 51 #define DEBUG_TYPE "constraint-elimination" 52 53 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 54 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 55 "Controls which conditions are eliminated"); 56 57 static cl::opt<unsigned> 58 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, 59 cl::desc("Maximum number of rows to keep in constraint system")); 60 61 static cl::opt<bool> DumpReproducers( 62 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, 63 cl::desc("Dump IR to reproduce successful transformations.")); 64 65 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 66 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 67 68 // A helper to multiply 2 signed integers where overflowing is allowed. 69 static int64_t multiplyWithOverflow(int64_t A, int64_t B) { 70 int64_t Result; 71 MulOverflow(A, B, Result); 72 return Result; 73 } 74 75 // A helper to add 2 signed integers where overflowing is allowed. 76 static int64_t addWithOverflow(int64_t A, int64_t B) { 77 int64_t Result; 78 AddOverflow(A, B, Result); 79 return Result; 80 } 81 82 static Instruction *getContextInstForUse(Use &U) { 83 Instruction *UserI = cast<Instruction>(U.getUser()); 84 if (auto *Phi = dyn_cast<PHINode>(UserI)) 85 UserI = Phi->getIncomingBlock(U)->getTerminator(); 86 return UserI; 87 } 88 89 namespace { 90 /// Struct to express a condition of the form %Op0 Pred %Op1. 91 struct ConditionTy { 92 CmpInst::Predicate Pred; 93 Value *Op0; 94 Value *Op1; 95 96 ConditionTy() 97 : Pred(CmpInst::BAD_ICMP_PREDICATE), Op0(nullptr), Op1(nullptr) {} 98 ConditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 99 : Pred(Pred), Op0(Op0), Op1(Op1) {} 100 }; 101 102 /// Represents either 103 /// * a condition that holds on entry to a block (=condition fact) 104 /// * an assume (=assume fact) 105 /// * a use of a compare instruction to simplify. 106 /// It also tracks the Dominator DFS in and out numbers for each entry. 107 struct FactOrCheck { 108 enum class EntryTy { 109 ConditionFact, /// A condition that holds on entry to a block. 110 InstFact, /// A fact that holds after Inst executed (e.g. an assume or 111 /// min/mix intrinsic. 112 InstCheck, /// An instruction to simplify (e.g. an overflow math 113 /// intrinsics). 114 UseCheck /// An use of a compare instruction to simplify. 115 }; 116 117 union { 118 Instruction *Inst; 119 Use *U; 120 ConditionTy Cond; 121 }; 122 123 /// A pre-condition that must hold for the current fact to be added to the 124 /// system. 125 ConditionTy DoesHold; 126 127 unsigned NumIn; 128 unsigned NumOut; 129 EntryTy Ty; 130 131 FactOrCheck(EntryTy Ty, DomTreeNode *DTN, Instruction *Inst) 132 : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 133 Ty(Ty) {} 134 135 FactOrCheck(DomTreeNode *DTN, Use *U) 136 : U(U), DoesHold(CmpInst::BAD_ICMP_PREDICATE, nullptr, nullptr), 137 NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 138 Ty(EntryTy::UseCheck) {} 139 140 FactOrCheck(DomTreeNode *DTN, CmpInst::Predicate Pred, Value *Op0, Value *Op1, 141 ConditionTy Precond = ConditionTy()) 142 : Cond(Pred, Op0, Op1), DoesHold(Precond), NumIn(DTN->getDFSNumIn()), 143 NumOut(DTN->getDFSNumOut()), Ty(EntryTy::ConditionFact) {} 144 145 static FactOrCheck getConditionFact(DomTreeNode *DTN, CmpInst::Predicate Pred, 146 Value *Op0, Value *Op1, 147 ConditionTy Precond = ConditionTy()) { 148 return FactOrCheck(DTN, Pred, Op0, Op1, Precond); 149 } 150 151 static FactOrCheck getInstFact(DomTreeNode *DTN, Instruction *Inst) { 152 return FactOrCheck(EntryTy::InstFact, DTN, Inst); 153 } 154 155 static FactOrCheck getCheck(DomTreeNode *DTN, Use *U) { 156 return FactOrCheck(DTN, U); 157 } 158 159 static FactOrCheck getCheck(DomTreeNode *DTN, CallInst *CI) { 160 return FactOrCheck(EntryTy::InstCheck, DTN, CI); 161 } 162 163 bool isCheck() const { 164 return Ty == EntryTy::InstCheck || Ty == EntryTy::UseCheck; 165 } 166 167 Instruction *getContextInst() const { 168 if (Ty == EntryTy::UseCheck) 169 return getContextInstForUse(*U); 170 return Inst; 171 } 172 173 Instruction *getInstructionToSimplify() const { 174 assert(isCheck()); 175 if (Ty == EntryTy::InstCheck) 176 return Inst; 177 // The use may have been simplified to a constant already. 178 return dyn_cast<Instruction>(*U); 179 } 180 181 bool isConditionFact() const { return Ty == EntryTy::ConditionFact; } 182 }; 183 184 /// Keep state required to build worklist. 185 struct State { 186 DominatorTree &DT; 187 LoopInfo &LI; 188 ScalarEvolution &SE; 189 SmallVector<FactOrCheck, 64> WorkList; 190 191 State(DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE) 192 : DT(DT), LI(LI), SE(SE) {} 193 194 /// Process block \p BB and add known facts to work-list. 195 void addInfoFor(BasicBlock &BB); 196 197 /// Try to add facts for loop inductions (AddRecs) in EQ/NE compares 198 /// controlling the loop header. 199 void addInfoForInductions(BasicBlock &BB); 200 201 /// Returns true if we can add a known condition from BB to its successor 202 /// block Succ. 203 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 204 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ); 205 } 206 }; 207 208 class ConstraintInfo; 209 210 struct StackEntry { 211 unsigned NumIn; 212 unsigned NumOut; 213 bool IsSigned = false; 214 /// Variables that can be removed from the system once the stack entry gets 215 /// removed. 216 SmallVector<Value *, 2> ValuesToRelease; 217 218 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned, 219 SmallVector<Value *, 2> ValuesToRelease) 220 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned), 221 ValuesToRelease(ValuesToRelease) {} 222 }; 223 224 struct ConstraintTy { 225 SmallVector<int64_t, 8> Coefficients; 226 SmallVector<ConditionTy, 2> Preconditions; 227 228 SmallVector<SmallVector<int64_t, 8>> ExtraInfo; 229 230 bool IsSigned = false; 231 232 ConstraintTy() = default; 233 234 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned, bool IsEq, 235 bool IsNe) 236 : Coefficients(Coefficients), IsSigned(IsSigned), IsEq(IsEq), IsNe(IsNe) { 237 } 238 239 unsigned size() const { return Coefficients.size(); } 240 241 unsigned empty() const { return Coefficients.empty(); } 242 243 /// Returns true if all preconditions for this list of constraints are 244 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 245 bool isValid(const ConstraintInfo &Info) const; 246 247 bool isEq() const { return IsEq; } 248 249 bool isNe() const { return IsNe; } 250 251 /// Check if the current constraint is implied by the given ConstraintSystem. 252 /// 253 /// \return true or false if the constraint is proven to be respectively true, 254 /// or false. When the constraint cannot be proven to be either true or false, 255 /// std::nullopt is returned. 256 std::optional<bool> isImpliedBy(const ConstraintSystem &CS) const; 257 258 private: 259 bool IsEq = false; 260 bool IsNe = false; 261 }; 262 263 /// Wrapper encapsulating separate constraint systems and corresponding value 264 /// mappings for both unsigned and signed information. Facts are added to and 265 /// conditions are checked against the corresponding system depending on the 266 /// signed-ness of their predicates. While the information is kept separate 267 /// based on signed-ness, certain conditions can be transferred between the two 268 /// systems. 269 class ConstraintInfo { 270 271 ConstraintSystem UnsignedCS; 272 ConstraintSystem SignedCS; 273 274 const DataLayout &DL; 275 276 public: 277 ConstraintInfo(const DataLayout &DL, ArrayRef<Value *> FunctionArgs) 278 : UnsignedCS(FunctionArgs), SignedCS(FunctionArgs), DL(DL) {} 279 280 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 281 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 282 } 283 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 284 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 285 } 286 287 ConstraintSystem &getCS(bool Signed) { 288 return Signed ? SignedCS : UnsignedCS; 289 } 290 const ConstraintSystem &getCS(bool Signed) const { 291 return Signed ? SignedCS : UnsignedCS; 292 } 293 294 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 295 void popLastNVariables(bool Signed, unsigned N) { 296 getCS(Signed).popLastNVariables(N); 297 } 298 299 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 300 301 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 302 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 303 304 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 305 /// constraints, using indices from the corresponding constraint system. 306 /// New variables that need to be added to the system are collected in 307 /// \p NewVariables. 308 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 309 SmallVectorImpl<Value *> &NewVariables) const; 310 311 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 312 /// constraints using getConstraint. Returns an empty constraint if the result 313 /// cannot be used to query the existing constraint system, e.g. because it 314 /// would require adding new variables. Also tries to convert signed 315 /// predicates to unsigned ones if possible to allow using the unsigned system 316 /// which increases the effectiveness of the signed <-> unsigned transfer 317 /// logic. 318 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0, 319 Value *Op1) const; 320 321 /// Try to add information from \p A \p Pred \p B to the unsigned/signed 322 /// system if \p Pred is signed/unsigned. 323 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B, 324 unsigned NumIn, unsigned NumOut, 325 SmallVectorImpl<StackEntry> &DFSInStack); 326 }; 327 328 /// Represents a (Coefficient * Variable) entry after IR decomposition. 329 struct DecompEntry { 330 int64_t Coefficient; 331 Value *Variable; 332 /// True if the variable is known positive in the current constraint. 333 bool IsKnownNonNegative; 334 335 DecompEntry(int64_t Coefficient, Value *Variable, 336 bool IsKnownNonNegative = false) 337 : Coefficient(Coefficient), Variable(Variable), 338 IsKnownNonNegative(IsKnownNonNegative) {} 339 }; 340 341 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition. 342 struct Decomposition { 343 int64_t Offset = 0; 344 SmallVector<DecompEntry, 3> Vars; 345 346 Decomposition(int64_t Offset) : Offset(Offset) {} 347 Decomposition(Value *V, bool IsKnownNonNegative = false) { 348 Vars.emplace_back(1, V, IsKnownNonNegative); 349 } 350 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars) 351 : Offset(Offset), Vars(Vars) {} 352 353 void add(int64_t OtherOffset) { 354 Offset = addWithOverflow(Offset, OtherOffset); 355 } 356 357 void add(const Decomposition &Other) { 358 add(Other.Offset); 359 append_range(Vars, Other.Vars); 360 } 361 362 void mul(int64_t Factor) { 363 Offset = multiplyWithOverflow(Offset, Factor); 364 for (auto &Var : Vars) 365 Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor); 366 } 367 }; 368 369 } // namespace 370 371 static Decomposition decompose(Value *V, 372 SmallVectorImpl<ConditionTy> &Preconditions, 373 bool IsSigned, const DataLayout &DL); 374 375 static bool canUseSExt(ConstantInt *CI) { 376 const APInt &Val = CI->getValue(); 377 return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 378 } 379 380 static Decomposition decomposeGEP(GEPOperator &GEP, 381 SmallVectorImpl<ConditionTy> &Preconditions, 382 bool IsSigned, const DataLayout &DL) { 383 // Do not reason about pointers where the index size is larger than 64 bits, 384 // as the coefficients used to encode constraints are 64 bit integers. 385 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64) 386 return &GEP; 387 388 if (!GEP.isInBounds()) 389 return &GEP; 390 391 assert(!IsSigned && "The logic below only supports decomposition for " 392 "unsinged predicates at the moment."); 393 Type *PtrTy = GEP.getType()->getScalarType(); 394 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy); 395 MapVector<Value *, APInt> VariableOffsets; 396 APInt ConstantOffset(BitWidth, 0); 397 if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) 398 return &GEP; 399 400 // Handle the (gep (gep ....), C) case by incrementing the constant 401 // coefficient of the inner GEP, if C is a constant. 402 auto *InnerGEP = dyn_cast<GEPOperator>(GEP.getPointerOperand()); 403 if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) { 404 auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL); 405 Result.add(ConstantOffset.getSExtValue()); 406 407 if (ConstantOffset.isNegative()) { 408 unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType()); 409 int64_t ConstantOffsetI = ConstantOffset.getSExtValue(); 410 if (ConstantOffsetI % Scale != 0) 411 return &GEP; 412 // Add pre-condition ensuring the GEP is increasing monotonically and 413 // can be de-composed. 414 // Both sides are normalized by being divided by Scale. 415 Preconditions.emplace_back( 416 CmpInst::ICMP_SGE, InnerGEP->getOperand(1), 417 ConstantInt::get(InnerGEP->getOperand(1)->getType(), 418 -1 * (ConstantOffsetI / Scale))); 419 } 420 return Result; 421 } 422 423 Decomposition Result(ConstantOffset.getSExtValue(), 424 DecompEntry(1, GEP.getPointerOperand())); 425 for (auto [Index, Scale] : VariableOffsets) { 426 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL); 427 IdxResult.mul(Scale.getSExtValue()); 428 Result.add(IdxResult); 429 430 // If Op0 is signed non-negative, the GEP is increasing monotonically and 431 // can be de-composed. 432 if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 433 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index, 434 ConstantInt::get(Index->getType(), 0)); 435 } 436 return Result; 437 } 438 439 // Decomposes \p V into a constant offset + list of pairs { Coefficient, 440 // Variable } where Coefficient * Variable. The sum of the constant offset and 441 // pairs equals \p V. 442 static Decomposition decompose(Value *V, 443 SmallVectorImpl<ConditionTy> &Preconditions, 444 bool IsSigned, const DataLayout &DL) { 445 446 auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B, 447 bool IsSignedB) { 448 auto ResA = decompose(A, Preconditions, IsSigned, DL); 449 auto ResB = decompose(B, Preconditions, IsSignedB, DL); 450 ResA.add(ResB); 451 return ResA; 452 }; 453 454 Type *Ty = V->getType()->getScalarType(); 455 if (Ty->isPointerTy() && !IsSigned) { 456 if (auto *GEP = dyn_cast<GEPOperator>(V)) 457 return decomposeGEP(*GEP, Preconditions, IsSigned, DL); 458 return V; 459 } 460 461 // Don't handle integers > 64 bit. Our coefficients are 64-bit large, so 462 // coefficient add/mul may wrap, while the operation in the full bit width 463 // would not. 464 if (!Ty->isIntegerTy() || Ty->getIntegerBitWidth() > 64) 465 return V; 466 467 // Decompose \p V used with a signed predicate. 468 if (IsSigned) { 469 if (auto *CI = dyn_cast<ConstantInt>(V)) { 470 if (canUseSExt(CI)) 471 return CI->getSExtValue(); 472 } 473 Value *Op0; 474 Value *Op1; 475 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) 476 return MergeResults(Op0, Op1, IsSigned); 477 478 ConstantInt *CI; 479 if (match(V, m_NSWMul(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) { 480 auto Result = decompose(Op0, Preconditions, IsSigned, DL); 481 Result.mul(CI->getSExtValue()); 482 return Result; 483 } 484 485 return V; 486 } 487 488 if (auto *CI = dyn_cast<ConstantInt>(V)) { 489 if (CI->uge(MaxConstraintValue)) 490 return V; 491 return int64_t(CI->getZExtValue()); 492 } 493 494 Value *Op0; 495 bool IsKnownNonNegative = false; 496 if (match(V, m_ZExt(m_Value(Op0)))) { 497 IsKnownNonNegative = true; 498 V = Op0; 499 } 500 501 Value *Op1; 502 ConstantInt *CI; 503 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) { 504 return MergeResults(Op0, Op1, IsSigned); 505 } 506 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) { 507 if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 508 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 509 ConstantInt::get(Op0->getType(), 0)); 510 if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 511 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1, 512 ConstantInt::get(Op1->getType(), 0)); 513 514 return MergeResults(Op0, Op1, IsSigned); 515 } 516 517 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 518 canUseSExt(CI)) { 519 Preconditions.emplace_back( 520 CmpInst::ICMP_UGE, Op0, 521 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 522 return MergeResults(Op0, CI, true); 523 } 524 525 // Decompose or as an add if there are no common bits between the operands. 526 if (match(V, m_Or(m_Value(Op0), m_ConstantInt(CI))) && 527 haveNoCommonBitsSet(Op0, CI, DL)) { 528 return MergeResults(Op0, CI, IsSigned); 529 } 530 531 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) { 532 if (CI->getSExtValue() < 0 || CI->getSExtValue() >= 64) 533 return {V, IsKnownNonNegative}; 534 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 535 Result.mul(int64_t{1} << CI->getSExtValue()); 536 return Result; 537 } 538 539 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) && 540 (!CI->isNegative())) { 541 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 542 Result.mul(CI->getSExtValue()); 543 return Result; 544 } 545 546 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) 547 return {-1 * CI->getSExtValue(), {{1, Op0}}}; 548 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 549 return {0, {{1, Op0}, {-1, Op1}}}; 550 551 return {V, IsKnownNonNegative}; 552 } 553 554 ConstraintTy 555 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 556 SmallVectorImpl<Value *> &NewVariables) const { 557 assert(NewVariables.empty() && "NewVariables must be empty when passed in"); 558 bool IsEq = false; 559 bool IsNe = false; 560 561 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 562 switch (Pred) { 563 case CmpInst::ICMP_UGT: 564 case CmpInst::ICMP_UGE: 565 case CmpInst::ICMP_SGT: 566 case CmpInst::ICMP_SGE: { 567 Pred = CmpInst::getSwappedPredicate(Pred); 568 std::swap(Op0, Op1); 569 break; 570 } 571 case CmpInst::ICMP_EQ: 572 if (match(Op1, m_Zero())) { 573 Pred = CmpInst::ICMP_ULE; 574 } else { 575 IsEq = true; 576 Pred = CmpInst::ICMP_ULE; 577 } 578 break; 579 case CmpInst::ICMP_NE: 580 if (match(Op1, m_Zero())) { 581 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 582 std::swap(Op0, Op1); 583 } else { 584 IsNe = true; 585 Pred = CmpInst::ICMP_ULE; 586 } 587 break; 588 default: 589 break; 590 } 591 592 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 593 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 594 return {}; 595 596 SmallVector<ConditionTy, 4> Preconditions; 597 bool IsSigned = CmpInst::isSigned(Pred); 598 auto &Value2Index = getValue2Index(IsSigned); 599 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 600 Preconditions, IsSigned, DL); 601 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 602 Preconditions, IsSigned, DL); 603 int64_t Offset1 = ADec.Offset; 604 int64_t Offset2 = BDec.Offset; 605 Offset1 *= -1; 606 607 auto &VariablesA = ADec.Vars; 608 auto &VariablesB = BDec.Vars; 609 610 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a 611 // new entry to NewVariables. 612 DenseMap<Value *, unsigned> NewIndexMap; 613 auto GetOrAddIndex = [&Value2Index, &NewVariables, 614 &NewIndexMap](Value *V) -> unsigned { 615 auto V2I = Value2Index.find(V); 616 if (V2I != Value2Index.end()) 617 return V2I->second; 618 auto Insert = 619 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1}); 620 if (Insert.second) 621 NewVariables.push_back(V); 622 return Insert.first->second; 623 }; 624 625 // Make sure all variables have entries in Value2Index or NewVariables. 626 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB)) 627 GetOrAddIndex(KV.Variable); 628 629 // Build result constraint, by first adding all coefficients from A and then 630 // subtracting all coefficients from B. 631 ConstraintTy Res( 632 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0), 633 IsSigned, IsEq, IsNe); 634 // Collect variables that are known to be positive in all uses in the 635 // constraint. 636 DenseMap<Value *, bool> KnownNonNegativeVariables; 637 auto &R = Res.Coefficients; 638 for (const auto &KV : VariablesA) { 639 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient; 640 auto I = 641 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 642 I.first->second &= KV.IsKnownNonNegative; 643 } 644 645 for (const auto &KV : VariablesB) { 646 if (SubOverflow(R[GetOrAddIndex(KV.Variable)], KV.Coefficient, 647 R[GetOrAddIndex(KV.Variable)])) 648 return {}; 649 auto I = 650 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 651 I.first->second &= KV.IsKnownNonNegative; 652 } 653 654 int64_t OffsetSum; 655 if (AddOverflow(Offset1, Offset2, OffsetSum)) 656 return {}; 657 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 658 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 659 return {}; 660 R[0] = OffsetSum; 661 Res.Preconditions = std::move(Preconditions); 662 663 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new 664 // variables. 665 while (!NewVariables.empty()) { 666 int64_t Last = R.back(); 667 if (Last != 0) 668 break; 669 R.pop_back(); 670 Value *RemovedV = NewVariables.pop_back_val(); 671 NewIndexMap.erase(RemovedV); 672 } 673 674 // Add extra constraints for variables that are known positive. 675 for (auto &KV : KnownNonNegativeVariables) { 676 if (!KV.second || 677 (!Value2Index.contains(KV.first) && !NewIndexMap.contains(KV.first))) 678 continue; 679 SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0); 680 C[GetOrAddIndex(KV.first)] = -1; 681 Res.ExtraInfo.push_back(C); 682 } 683 return Res; 684 } 685 686 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred, 687 Value *Op0, 688 Value *Op1) const { 689 Constant *NullC = Constant::getNullValue(Op0->getType()); 690 // Handle trivially true compares directly to avoid adding V UGE 0 constraints 691 // for all variables in the unsigned system. 692 if ((Pred == CmpInst::ICMP_ULE && Op0 == NullC) || 693 (Pred == CmpInst::ICMP_UGE && Op1 == NullC)) { 694 auto &Value2Index = getValue2Index(false); 695 // Return constraint that's trivially true. 696 return ConstraintTy(SmallVector<int64_t, 8>(Value2Index.size(), 0), false, 697 false, false); 698 } 699 700 // If both operands are known to be non-negative, change signed predicates to 701 // unsigned ones. This increases the reasoning effectiveness in combination 702 // with the signed <-> unsigned transfer logic. 703 if (CmpInst::isSigned(Pred) && 704 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) && 705 isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 706 Pred = CmpInst::getUnsignedPredicate(Pred); 707 708 SmallVector<Value *> NewVariables; 709 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables); 710 if (!NewVariables.empty()) 711 return {}; 712 return R; 713 } 714 715 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 716 return Coefficients.size() > 0 && 717 all_of(Preconditions, [&Info](const ConditionTy &C) { 718 return Info.doesHold(C.Pred, C.Op0, C.Op1); 719 }); 720 } 721 722 std::optional<bool> 723 ConstraintTy::isImpliedBy(const ConstraintSystem &CS) const { 724 bool IsConditionImplied = CS.isConditionImplied(Coefficients); 725 726 if (IsEq || IsNe) { 727 auto NegatedOrEqual = ConstraintSystem::negateOrEqual(Coefficients); 728 bool IsNegatedOrEqualImplied = 729 !NegatedOrEqual.empty() && CS.isConditionImplied(NegatedOrEqual); 730 731 // In order to check that `%a == %b` is true (equality), both conditions `%a 732 // >= %b` and `%a <= %b` must hold true. When checking for equality (`IsEq` 733 // is true), we return true if they both hold, false in the other cases. 734 if (IsConditionImplied && IsNegatedOrEqualImplied) 735 return IsEq; 736 737 auto Negated = ConstraintSystem::negate(Coefficients); 738 bool IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 739 740 auto StrictLessThan = ConstraintSystem::toStrictLessThan(Coefficients); 741 bool IsStrictLessThanImplied = 742 !StrictLessThan.empty() && CS.isConditionImplied(StrictLessThan); 743 744 // In order to check that `%a != %b` is true (non-equality), either 745 // condition `%a > %b` or `%a < %b` must hold true. When checking for 746 // non-equality (`IsNe` is true), we return true if one of the two holds, 747 // false in the other cases. 748 if (IsNegatedImplied || IsStrictLessThanImplied) 749 return IsNe; 750 751 return std::nullopt; 752 } 753 754 if (IsConditionImplied) 755 return true; 756 757 auto Negated = ConstraintSystem::negate(Coefficients); 758 auto IsNegatedImplied = !Negated.empty() && CS.isConditionImplied(Negated); 759 if (IsNegatedImplied) 760 return false; 761 762 // Neither the condition nor its negated holds, did not prove anything. 763 return std::nullopt; 764 } 765 766 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 767 Value *B) const { 768 auto R = getConstraintForSolving(Pred, A, B); 769 return R.isValid(*this) && 770 getCS(R.IsSigned).isConditionImplied(R.Coefficients); 771 } 772 773 void ConstraintInfo::transferToOtherSystem( 774 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 775 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) { 776 // Check if we can combine facts from the signed and unsigned systems to 777 // derive additional facts. 778 if (!A->getType()->isIntegerTy()) 779 return; 780 // FIXME: This currently depends on the order we add facts. Ideally we 781 // would first add all known facts and only then try to add additional 782 // facts. 783 switch (Pred) { 784 default: 785 break; 786 case CmpInst::ICMP_ULT: 787 case CmpInst::ICMP_ULE: 788 // If B is a signed positive constant, then A >=s 0 and A <s (or <=s) B. 789 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 790 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn, 791 NumOut, DFSInStack); 792 addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut, 793 DFSInStack); 794 } 795 break; 796 case CmpInst::ICMP_UGE: 797 case CmpInst::ICMP_UGT: 798 // If A is a signed positive constant, then B >=s 0 and A >s (or >=s) B. 799 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) { 800 addFact(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0), NumIn, 801 NumOut, DFSInStack); 802 addFact(CmpInst::getSignedPredicate(Pred), A, B, NumIn, NumOut, 803 DFSInStack); 804 } 805 break; 806 case CmpInst::ICMP_SLT: 807 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) 808 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack); 809 break; 810 case CmpInst::ICMP_SGT: { 811 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 812 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn, 813 NumOut, DFSInStack); 814 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) 815 addFact(CmpInst::ICMP_UGT, A, B, NumIn, NumOut, DFSInStack); 816 817 break; 818 } 819 case CmpInst::ICMP_SGE: 820 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 821 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack); 822 } 823 break; 824 } 825 } 826 827 #ifndef NDEBUG 828 829 static void dumpConstraint(ArrayRef<int64_t> C, 830 const DenseMap<Value *, unsigned> &Value2Index) { 831 ConstraintSystem CS(Value2Index); 832 CS.addVariableRowFill(C); 833 CS.dump(); 834 } 835 #endif 836 837 void State::addInfoForInductions(BasicBlock &BB) { 838 auto *L = LI.getLoopFor(&BB); 839 if (!L || L->getHeader() != &BB) 840 return; 841 842 Value *A; 843 Value *B; 844 CmpInst::Predicate Pred; 845 846 if (!match(BB.getTerminator(), 847 m_Br(m_ICmp(Pred, m_Value(A), m_Value(B)), m_Value(), m_Value()))) 848 return; 849 PHINode *PN = dyn_cast<PHINode>(A); 850 if (!PN) { 851 Pred = CmpInst::getSwappedPredicate(Pred); 852 std::swap(A, B); 853 PN = dyn_cast<PHINode>(A); 854 } 855 856 if (!PN || PN->getParent() != &BB || PN->getNumIncomingValues() != 2 || 857 !SE.isSCEVable(PN->getType())) 858 return; 859 860 BasicBlock *InLoopSucc = nullptr; 861 if (Pred == CmpInst::ICMP_NE) 862 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(0); 863 else if (Pred == CmpInst::ICMP_EQ) 864 InLoopSucc = cast<BranchInst>(BB.getTerminator())->getSuccessor(1); 865 else 866 return; 867 868 if (!L->contains(InLoopSucc) || !L->isLoopExiting(&BB) || InLoopSucc == &BB) 869 return; 870 871 auto *AR = dyn_cast_or_null<SCEVAddRecExpr>(SE.getSCEV(PN)); 872 BasicBlock *LoopPred = L->getLoopPredecessor(); 873 if (!AR || AR->getLoop() != L || !LoopPred) 874 return; 875 876 const SCEV *StartSCEV = AR->getStart(); 877 Value *StartValue = nullptr; 878 if (auto *C = dyn_cast<SCEVConstant>(StartSCEV)) { 879 StartValue = C->getValue(); 880 } else { 881 StartValue = PN->getIncomingValueForBlock(LoopPred); 882 assert(SE.getSCEV(StartValue) == StartSCEV && "inconsistent start value"); 883 } 884 885 DomTreeNode *DTN = DT.getNode(InLoopSucc); 886 auto Inc = SE.getMonotonicPredicateType(AR, CmpInst::ICMP_UGT); 887 bool MonotonicallyIncreasing = 888 Inc && *Inc == ScalarEvolution::MonotonicallyIncreasing; 889 if (MonotonicallyIncreasing) { 890 // SCEV guarantees that AR does not wrap, so PN >= StartValue can be added 891 // unconditionally. 892 WorkList.push_back( 893 FactOrCheck::getConditionFact(DTN, CmpInst::ICMP_UGE, PN, StartValue)); 894 } 895 896 APInt StepOffset; 897 if (auto *C = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 898 StepOffset = C->getAPInt(); 899 else 900 return; 901 902 // Make sure the bound B is loop-invariant. 903 if (!L->isLoopInvariant(B)) 904 return; 905 906 // Handle negative steps. 907 if (StepOffset.isNegative()) { 908 // TODO: Extend to allow steps > -1. 909 if (!(-StepOffset).isOne()) 910 return; 911 912 // AR may wrap. 913 // Add StartValue >= PN conditional on B <= StartValue which guarantees that 914 // the loop exits before wrapping with a step of -1. 915 WorkList.push_back(FactOrCheck::getConditionFact( 916 DTN, CmpInst::ICMP_UGE, StartValue, PN, 917 ConditionTy(CmpInst::ICMP_ULE, B, StartValue))); 918 // Add PN > B conditional on B <= StartValue which guarantees that the loop 919 // exits when reaching B with a step of -1. 920 WorkList.push_back(FactOrCheck::getConditionFact( 921 DTN, CmpInst::ICMP_UGT, PN, B, 922 ConditionTy(CmpInst::ICMP_ULE, B, StartValue))); 923 return; 924 } 925 926 // Make sure AR either steps by 1 or that the value we compare against is a 927 // GEP based on the same start value and all offsets are a multiple of the 928 // step size, to guarantee that the induction will reach the value. 929 if (StepOffset.isZero() || StepOffset.isNegative()) 930 return; 931 932 if (!StepOffset.isOne()) { 933 auto *UpperGEP = dyn_cast<GetElementPtrInst>(B); 934 if (!UpperGEP || UpperGEP->getPointerOperand() != StartValue || 935 !UpperGEP->isInBounds()) 936 return; 937 938 MapVector<Value *, APInt> UpperVariableOffsets; 939 APInt UpperConstantOffset(StepOffset.getBitWidth(), 0); 940 const DataLayout &DL = BB.getModule()->getDataLayout(); 941 if (!UpperGEP->collectOffset(DL, StepOffset.getBitWidth(), 942 UpperVariableOffsets, UpperConstantOffset)) 943 return; 944 // All variable offsets and the constant offset have to be a multiple of the 945 // step. 946 if (!UpperConstantOffset.urem(StepOffset).isZero() || 947 any_of(UpperVariableOffsets, [&StepOffset](const auto &P) { 948 return !P.second.urem(StepOffset).isZero(); 949 })) 950 return; 951 } 952 953 // AR may wrap. Add PN >= StartValue conditional on StartValue <= B which 954 // guarantees that the loop exits before wrapping in combination with the 955 // restrictions on B and the step above. 956 if (!MonotonicallyIncreasing) { 957 WorkList.push_back(FactOrCheck::getConditionFact( 958 DTN, CmpInst::ICMP_UGE, PN, StartValue, 959 ConditionTy(CmpInst::ICMP_ULE, StartValue, B))); 960 } 961 WorkList.push_back(FactOrCheck::getConditionFact( 962 DTN, CmpInst::ICMP_ULT, PN, B, 963 ConditionTy(CmpInst::ICMP_ULE, StartValue, B))); 964 } 965 966 void State::addInfoFor(BasicBlock &BB) { 967 addInfoForInductions(BB); 968 969 // True as long as long as the current instruction is guaranteed to execute. 970 bool GuaranteedToExecute = true; 971 // Queue conditions and assumes. 972 for (Instruction &I : BB) { 973 if (auto Cmp = dyn_cast<ICmpInst>(&I)) { 974 for (Use &U : Cmp->uses()) { 975 auto *UserI = getContextInstForUse(U); 976 auto *DTN = DT.getNode(UserI->getParent()); 977 if (!DTN) 978 continue; 979 WorkList.push_back(FactOrCheck::getCheck(DTN, &U)); 980 } 981 continue; 982 } 983 984 if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) { 985 WorkList.push_back( 986 FactOrCheck::getCheck(DT.getNode(&BB), cast<CallInst>(&I))); 987 continue; 988 } 989 990 if (isa<MinMaxIntrinsic>(&I)) { 991 WorkList.push_back(FactOrCheck::getInstFact(DT.getNode(&BB), &I)); 992 continue; 993 } 994 995 Value *A, *B; 996 CmpInst::Predicate Pred; 997 // For now, just handle assumes with a single compare as condition. 998 if (match(&I, m_Intrinsic<Intrinsic::assume>( 999 m_ICmp(Pred, m_Value(A), m_Value(B))))) { 1000 if (GuaranteedToExecute) { 1001 // The assume is guaranteed to execute when BB is entered, hence Cond 1002 // holds on entry to BB. 1003 WorkList.emplace_back(FactOrCheck::getConditionFact( 1004 DT.getNode(I.getParent()), Pred, A, B)); 1005 } else { 1006 WorkList.emplace_back( 1007 FactOrCheck::getInstFact(DT.getNode(I.getParent()), &I)); 1008 } 1009 } 1010 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 1011 } 1012 1013 if (auto *Switch = dyn_cast<SwitchInst>(BB.getTerminator())) { 1014 for (auto &Case : Switch->cases()) { 1015 BasicBlock *Succ = Case.getCaseSuccessor(); 1016 Value *V = Case.getCaseValue(); 1017 if (!canAddSuccessor(BB, Succ)) 1018 continue; 1019 WorkList.emplace_back(FactOrCheck::getConditionFact( 1020 DT.getNode(Succ), CmpInst::ICMP_EQ, Switch->getCondition(), V)); 1021 } 1022 return; 1023 } 1024 1025 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 1026 if (!Br || !Br->isConditional()) 1027 return; 1028 1029 Value *Cond = Br->getCondition(); 1030 1031 // If the condition is a chain of ORs/AND and the successor only has the 1032 // current block as predecessor, queue conditions for the successor. 1033 Value *Op0, *Op1; 1034 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 1035 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 1036 bool IsOr = match(Cond, m_LogicalOr()); 1037 bool IsAnd = match(Cond, m_LogicalAnd()); 1038 // If there's a select that matches both AND and OR, we need to commit to 1039 // one of the options. Arbitrarily pick OR. 1040 if (IsOr && IsAnd) 1041 IsAnd = false; 1042 1043 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0); 1044 if (canAddSuccessor(BB, Successor)) { 1045 SmallVector<Value *> CondWorkList; 1046 SmallPtrSet<Value *, 8> SeenCond; 1047 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) { 1048 if (SeenCond.insert(V).second) 1049 CondWorkList.push_back(V); 1050 }; 1051 QueueValue(Op1); 1052 QueueValue(Op0); 1053 while (!CondWorkList.empty()) { 1054 Value *Cur = CondWorkList.pop_back_val(); 1055 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) { 1056 WorkList.emplace_back(FactOrCheck::getConditionFact( 1057 DT.getNode(Successor), 1058 IsOr ? CmpInst::getInversePredicate(Cmp->getPredicate()) 1059 : Cmp->getPredicate(), 1060 Cmp->getOperand(0), Cmp->getOperand(1))); 1061 continue; 1062 } 1063 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 1064 QueueValue(Op1); 1065 QueueValue(Op0); 1066 continue; 1067 } 1068 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 1069 QueueValue(Op1); 1070 QueueValue(Op0); 1071 continue; 1072 } 1073 } 1074 } 1075 return; 1076 } 1077 1078 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 1079 if (!CmpI) 1080 return; 1081 if (canAddSuccessor(BB, Br->getSuccessor(0))) 1082 WorkList.emplace_back(FactOrCheck::getConditionFact( 1083 DT.getNode(Br->getSuccessor(0)), CmpI->getPredicate(), 1084 CmpI->getOperand(0), CmpI->getOperand(1))); 1085 if (canAddSuccessor(BB, Br->getSuccessor(1))) 1086 WorkList.emplace_back(FactOrCheck::getConditionFact( 1087 DT.getNode(Br->getSuccessor(1)), 1088 CmpInst::getInversePredicate(CmpI->getPredicate()), CmpI->getOperand(0), 1089 CmpI->getOperand(1))); 1090 } 1091 1092 namespace { 1093 /// Helper to keep track of a condition and if it should be treated as negated 1094 /// for reproducer construction. 1095 /// Pred == Predicate::BAD_ICMP_PREDICATE indicates that this entry is a 1096 /// placeholder to keep the ReproducerCondStack in sync with DFSInStack. 1097 struct ReproducerEntry { 1098 ICmpInst::Predicate Pred; 1099 Value *LHS; 1100 Value *RHS; 1101 1102 ReproducerEntry(ICmpInst::Predicate Pred, Value *LHS, Value *RHS) 1103 : Pred(Pred), LHS(LHS), RHS(RHS) {} 1104 }; 1105 } // namespace 1106 1107 /// Helper function to generate a reproducer function for simplifying \p Cond. 1108 /// The reproducer function contains a series of @llvm.assume calls, one for 1109 /// each condition in \p Stack. For each condition, the operand instruction are 1110 /// cloned until we reach operands that have an entry in \p Value2Index. Those 1111 /// will then be added as function arguments. \p DT is used to order cloned 1112 /// instructions. The reproducer function will get added to \p M, if it is 1113 /// non-null. Otherwise no reproducer function is generated. 1114 static void generateReproducer(CmpInst *Cond, Module *M, 1115 ArrayRef<ReproducerEntry> Stack, 1116 ConstraintInfo &Info, DominatorTree &DT) { 1117 if (!M) 1118 return; 1119 1120 LLVMContext &Ctx = Cond->getContext(); 1121 1122 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n"); 1123 1124 ValueToValueMapTy Old2New; 1125 SmallVector<Value *> Args; 1126 SmallPtrSet<Value *, 8> Seen; 1127 // Traverse Cond and its operands recursively until we reach a value that's in 1128 // Value2Index or not an instruction, or not a operation that 1129 // ConstraintElimination can decompose. Such values will be considered as 1130 // external inputs to the reproducer, they are collected and added as function 1131 // arguments later. 1132 auto CollectArguments = [&](ArrayRef<Value *> Ops, bool IsSigned) { 1133 auto &Value2Index = Info.getValue2Index(IsSigned); 1134 SmallVector<Value *, 4> WorkList(Ops); 1135 while (!WorkList.empty()) { 1136 Value *V = WorkList.pop_back_val(); 1137 if (!Seen.insert(V).second) 1138 continue; 1139 if (Old2New.find(V) != Old2New.end()) 1140 continue; 1141 if (isa<Constant>(V)) 1142 continue; 1143 1144 auto *I = dyn_cast<Instruction>(V); 1145 if (Value2Index.contains(V) || !I || 1146 !isa<CmpInst, BinaryOperator, GEPOperator, CastInst>(V)) { 1147 Old2New[V] = V; 1148 Args.push_back(V); 1149 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n"); 1150 } else { 1151 append_range(WorkList, I->operands()); 1152 } 1153 } 1154 }; 1155 1156 for (auto &Entry : Stack) 1157 if (Entry.Pred != ICmpInst::BAD_ICMP_PREDICATE) 1158 CollectArguments({Entry.LHS, Entry.RHS}, ICmpInst::isSigned(Entry.Pred)); 1159 CollectArguments(Cond, ICmpInst::isSigned(Cond->getPredicate())); 1160 1161 SmallVector<Type *> ParamTys; 1162 for (auto *P : Args) 1163 ParamTys.push_back(P->getType()); 1164 1165 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys, 1166 /*isVarArg=*/false); 1167 Function *F = Function::Create(FTy, Function::ExternalLinkage, 1168 Cond->getModule()->getName() + 1169 Cond->getFunction()->getName() + "repro", 1170 M); 1171 // Add arguments to the reproducer function for each external value collected. 1172 for (unsigned I = 0; I < Args.size(); ++I) { 1173 F->getArg(I)->setName(Args[I]->getName()); 1174 Old2New[Args[I]] = F->getArg(I); 1175 } 1176 1177 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F); 1178 IRBuilder<> Builder(Entry); 1179 Builder.CreateRet(Builder.getTrue()); 1180 Builder.SetInsertPoint(Entry->getTerminator()); 1181 1182 // Clone instructions in \p Ops and their operands recursively until reaching 1183 // an value in Value2Index (external input to the reproducer). Update Old2New 1184 // mapping for the original and cloned instructions. Sort instructions to 1185 // clone by dominance, then insert the cloned instructions in the function. 1186 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) { 1187 SmallVector<Value *, 4> WorkList(Ops); 1188 SmallVector<Instruction *> ToClone; 1189 auto &Value2Index = Info.getValue2Index(IsSigned); 1190 while (!WorkList.empty()) { 1191 Value *V = WorkList.pop_back_val(); 1192 if (Old2New.find(V) != Old2New.end()) 1193 continue; 1194 1195 auto *I = dyn_cast<Instruction>(V); 1196 if (!Value2Index.contains(V) && I) { 1197 Old2New[V] = nullptr; 1198 ToClone.push_back(I); 1199 append_range(WorkList, I->operands()); 1200 } 1201 } 1202 1203 sort(ToClone, 1204 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); }); 1205 for (Instruction *I : ToClone) { 1206 Instruction *Cloned = I->clone(); 1207 Old2New[I] = Cloned; 1208 Old2New[I]->setName(I->getName()); 1209 Cloned->insertBefore(&*Builder.GetInsertPoint()); 1210 Cloned->dropUnknownNonDebugMetadata(); 1211 Cloned->setDebugLoc({}); 1212 } 1213 }; 1214 1215 // Materialize the assumptions for the reproducer using the entries in Stack. 1216 // That is, first clone the operands of the condition recursively until we 1217 // reach an external input to the reproducer and add them to the reproducer 1218 // function. Then add an ICmp for the condition (with the inverse predicate if 1219 // the entry is negated) and an assert using the ICmp. 1220 for (auto &Entry : Stack) { 1221 if (Entry.Pred == ICmpInst::BAD_ICMP_PREDICATE) 1222 continue; 1223 1224 LLVM_DEBUG( 1225 dbgs() << " Materializing assumption icmp " << Entry.Pred << ' '; 1226 Entry.LHS->printAsOperand(dbgs(), /*PrintType=*/true); dbgs() << ", "; 1227 Entry.RHS->printAsOperand(dbgs(), /*PrintType=*/false); dbgs() << "\n"); 1228 CloneInstructions({Entry.LHS, Entry.RHS}, CmpInst::isSigned(Entry.Pred)); 1229 1230 auto *Cmp = Builder.CreateICmp(Entry.Pred, Entry.LHS, Entry.RHS); 1231 Builder.CreateAssumption(Cmp); 1232 } 1233 1234 // Finally, clone the condition to reproduce and remap instruction operands in 1235 // the reproducer using Old2New. 1236 CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate())); 1237 Entry->getTerminator()->setOperand(0, Cond); 1238 remapInstructionsInBlocks({Entry}, Old2New); 1239 1240 assert(!verifyFunction(*F, &dbgs())); 1241 } 1242 1243 static std::optional<bool> checkCondition(CmpInst *Cmp, ConstraintInfo &Info, 1244 unsigned NumIn, unsigned NumOut, 1245 Instruction *ContextInst) { 1246 LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n"); 1247 1248 CmpInst::Predicate Pred = Cmp->getPredicate(); 1249 Value *A = Cmp->getOperand(0); 1250 Value *B = Cmp->getOperand(1); 1251 1252 auto R = Info.getConstraintForSolving(Pred, A, B); 1253 if (R.empty() || !R.isValid(Info)){ 1254 LLVM_DEBUG(dbgs() << " failed to decompose condition\n"); 1255 return std::nullopt; 1256 } 1257 1258 auto &CSToUse = Info.getCS(R.IsSigned); 1259 1260 // If there was extra information collected during decomposition, apply 1261 // it now and remove it immediately once we are done with reasoning 1262 // about the constraint. 1263 for (auto &Row : R.ExtraInfo) 1264 CSToUse.addVariableRow(Row); 1265 auto InfoRestorer = make_scope_exit([&]() { 1266 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I) 1267 CSToUse.popLastConstraint(); 1268 }); 1269 1270 if (auto ImpliedCondition = R.isImpliedBy(CSToUse)) { 1271 if (!DebugCounter::shouldExecute(EliminatedCounter)) 1272 return std::nullopt; 1273 1274 LLVM_DEBUG({ 1275 if (*ImpliedCondition) { 1276 dbgs() << "Condition " << *Cmp; 1277 } else { 1278 auto InversePred = Cmp->getInversePredicate(); 1279 dbgs() << "Condition " << CmpInst::getPredicateName(InversePred) << " " 1280 << *A << ", " << *B; 1281 } 1282 dbgs() << " implied by dominating constraints\n"; 1283 CSToUse.dump(); 1284 }); 1285 return ImpliedCondition; 1286 } 1287 1288 return std::nullopt; 1289 } 1290 1291 static bool checkAndReplaceCondition( 1292 CmpInst *Cmp, ConstraintInfo &Info, unsigned NumIn, unsigned NumOut, 1293 Instruction *ContextInst, Module *ReproducerModule, 1294 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT, 1295 SmallVectorImpl<Instruction *> &ToRemove) { 1296 auto ReplaceCmpWithConstant = [&](CmpInst *Cmp, bool IsTrue) { 1297 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT); 1298 Constant *ConstantC = ConstantInt::getBool( 1299 CmpInst::makeCmpResultType(Cmp->getType()), IsTrue); 1300 Cmp->replaceUsesWithIf(ConstantC, [&DT, NumIn, NumOut, 1301 ContextInst](Use &U) { 1302 auto *UserI = getContextInstForUse(U); 1303 auto *DTN = DT.getNode(UserI->getParent()); 1304 if (!DTN || DTN->getDFSNumIn() < NumIn || DTN->getDFSNumOut() > NumOut) 1305 return false; 1306 if (UserI->getParent() == ContextInst->getParent() && 1307 UserI->comesBefore(ContextInst)) 1308 return false; 1309 1310 // Conditions in an assume trivially simplify to true. Skip uses 1311 // in assume calls to not destroy the available information. 1312 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 1313 return !II || II->getIntrinsicID() != Intrinsic::assume; 1314 }); 1315 NumCondsRemoved++; 1316 if (Cmp->use_empty()) 1317 ToRemove.push_back(Cmp); 1318 return true; 1319 }; 1320 1321 if (auto ImpliedCondition = 1322 checkCondition(Cmp, Info, NumIn, NumOut, ContextInst)) 1323 return ReplaceCmpWithConstant(Cmp, *ImpliedCondition); 1324 return false; 1325 } 1326 1327 static void 1328 removeEntryFromStack(const StackEntry &E, ConstraintInfo &Info, 1329 Module *ReproducerModule, 1330 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 1331 SmallVectorImpl<StackEntry> &DFSInStack) { 1332 Info.popLastConstraint(E.IsSigned); 1333 // Remove variables in the system that went out of scope. 1334 auto &Mapping = Info.getValue2Index(E.IsSigned); 1335 for (Value *V : E.ValuesToRelease) 1336 Mapping.erase(V); 1337 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 1338 DFSInStack.pop_back(); 1339 if (ReproducerModule) 1340 ReproducerCondStack.pop_back(); 1341 } 1342 1343 /// Check if the first condition for an AND implies the second. 1344 static bool checkAndSecondOpImpliedByFirst( 1345 FactOrCheck &CB, ConstraintInfo &Info, Module *ReproducerModule, 1346 SmallVectorImpl<ReproducerEntry> &ReproducerCondStack, 1347 SmallVectorImpl<StackEntry> &DFSInStack) { 1348 1349 CmpInst::Predicate Pred; 1350 Value *A, *B; 1351 Instruction *And = CB.getContextInst(); 1352 if (!match(And->getOperand(0), m_ICmp(Pred, m_Value(A), m_Value(B)))) 1353 return false; 1354 1355 // Optimistically add fact from first condition. 1356 unsigned OldSize = DFSInStack.size(); 1357 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1358 if (OldSize == DFSInStack.size()) 1359 return false; 1360 1361 bool Changed = false; 1362 // Check if the second condition can be simplified now. 1363 if (auto ImpliedCondition = 1364 checkCondition(cast<ICmpInst>(And->getOperand(1)), Info, CB.NumIn, 1365 CB.NumOut, CB.getContextInst())) { 1366 And->setOperand(1, ConstantInt::getBool(And->getType(), *ImpliedCondition)); 1367 Changed = true; 1368 } 1369 1370 // Remove entries again. 1371 while (OldSize < DFSInStack.size()) { 1372 StackEntry E = DFSInStack.back(); 1373 removeEntryFromStack(E, Info, ReproducerModule, ReproducerCondStack, 1374 DFSInStack); 1375 } 1376 return Changed; 1377 } 1378 1379 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 1380 unsigned NumIn, unsigned NumOut, 1381 SmallVectorImpl<StackEntry> &DFSInStack) { 1382 // If the constraint has a pre-condition, skip the constraint if it does not 1383 // hold. 1384 SmallVector<Value *> NewVariables; 1385 auto R = getConstraint(Pred, A, B, NewVariables); 1386 1387 // TODO: Support non-equality for facts as well. 1388 if (!R.isValid(*this) || R.isNe()) 1389 return; 1390 1391 LLVM_DEBUG(dbgs() << "Adding '" << Pred << " "; 1392 A->printAsOperand(dbgs(), false); dbgs() << ", "; 1393 B->printAsOperand(dbgs(), false); dbgs() << "'\n"); 1394 bool Added = false; 1395 auto &CSToUse = getCS(R.IsSigned); 1396 if (R.Coefficients.empty()) 1397 return; 1398 1399 Added |= CSToUse.addVariableRowFill(R.Coefficients); 1400 1401 // If R has been added to the system, add the new variables and queue it for 1402 // removal once it goes out-of-scope. 1403 if (Added) { 1404 SmallVector<Value *, 2> ValuesToRelease; 1405 auto &Value2Index = getValue2Index(R.IsSigned); 1406 for (Value *V : NewVariables) { 1407 Value2Index.insert({V, Value2Index.size() + 1}); 1408 ValuesToRelease.push_back(V); 1409 } 1410 1411 LLVM_DEBUG({ 1412 dbgs() << " constraint: "; 1413 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned)); 1414 dbgs() << "\n"; 1415 }); 1416 1417 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1418 std::move(ValuesToRelease)); 1419 1420 if (R.isEq()) { 1421 // Also add the inverted constraint for equality constraints. 1422 for (auto &Coeff : R.Coefficients) 1423 Coeff *= -1; 1424 CSToUse.addVariableRowFill(R.Coefficients); 1425 1426 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1427 SmallVector<Value *, 2>()); 1428 } 1429 } 1430 } 1431 1432 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, 1433 SmallVectorImpl<Instruction *> &ToRemove) { 1434 bool Changed = false; 1435 IRBuilder<> Builder(II->getParent(), II->getIterator()); 1436 Value *Sub = nullptr; 1437 for (User *U : make_early_inc_range(II->users())) { 1438 if (match(U, m_ExtractValue<0>(m_Value()))) { 1439 if (!Sub) 1440 Sub = Builder.CreateSub(A, B); 1441 U->replaceAllUsesWith(Sub); 1442 Changed = true; 1443 } else if (match(U, m_ExtractValue<1>(m_Value()))) { 1444 U->replaceAllUsesWith(Builder.getFalse()); 1445 Changed = true; 1446 } else 1447 continue; 1448 1449 if (U->use_empty()) { 1450 auto *I = cast<Instruction>(U); 1451 ToRemove.push_back(I); 1452 I->setOperand(0, PoisonValue::get(II->getType())); 1453 Changed = true; 1454 } 1455 } 1456 1457 if (II->use_empty()) { 1458 II->eraseFromParent(); 1459 Changed = true; 1460 } 1461 return Changed; 1462 } 1463 1464 static bool 1465 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 1466 SmallVectorImpl<Instruction *> &ToRemove) { 1467 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 1468 ConstraintInfo &Info) { 1469 auto R = Info.getConstraintForSolving(Pred, A, B); 1470 if (R.size() < 2 || !R.isValid(Info)) 1471 return false; 1472 1473 auto &CSToUse = Info.getCS(R.IsSigned); 1474 return CSToUse.isConditionImplied(R.Coefficients); 1475 }; 1476 1477 bool Changed = false; 1478 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 1479 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 1480 // can be simplified to a regular sub. 1481 Value *A = II->getArgOperand(0); 1482 Value *B = II->getArgOperand(1); 1483 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 1484 !DoesConditionHold(CmpInst::ICMP_SGE, B, 1485 ConstantInt::get(A->getType(), 0), Info)) 1486 return false; 1487 Changed = replaceSubOverflowUses(II, A, B, ToRemove); 1488 } 1489 return Changed; 1490 } 1491 1492 static bool eliminateConstraints(Function &F, DominatorTree &DT, LoopInfo &LI, 1493 ScalarEvolution &SE, 1494 OptimizationRemarkEmitter &ORE) { 1495 bool Changed = false; 1496 DT.updateDFSNumbers(); 1497 SmallVector<Value *> FunctionArgs; 1498 for (Value &Arg : F.args()) 1499 FunctionArgs.push_back(&Arg); 1500 ConstraintInfo Info(F.getParent()->getDataLayout(), FunctionArgs); 1501 State S(DT, LI, SE); 1502 std::unique_ptr<Module> ReproducerModule( 1503 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr); 1504 1505 // First, collect conditions implied by branches and blocks with their 1506 // Dominator DFS in and out numbers. 1507 for (BasicBlock &BB : F) { 1508 if (!DT.getNode(&BB)) 1509 continue; 1510 S.addInfoFor(BB); 1511 } 1512 1513 // Next, sort worklist by dominance, so that dominating conditions to check 1514 // and facts come before conditions and facts dominated by them. If a 1515 // condition to check and a fact have the same numbers, conditional facts come 1516 // first. Assume facts and checks are ordered according to their relative 1517 // order in the containing basic block. Also make sure conditions with 1518 // constant operands come before conditions without constant operands. This 1519 // increases the effectiveness of the current signed <-> unsigned fact 1520 // transfer logic. 1521 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) { 1522 auto HasNoConstOp = [](const FactOrCheck &B) { 1523 Value *V0 = B.isConditionFact() ? B.Cond.Op0 : B.Inst->getOperand(0); 1524 Value *V1 = B.isConditionFact() ? B.Cond.Op1 : B.Inst->getOperand(1); 1525 return !isa<ConstantInt>(V0) && !isa<ConstantInt>(V1); 1526 }; 1527 // If both entries have the same In numbers, conditional facts come first. 1528 // Otherwise use the relative order in the basic block. 1529 if (A.NumIn == B.NumIn) { 1530 if (A.isConditionFact() && B.isConditionFact()) { 1531 bool NoConstOpA = HasNoConstOp(A); 1532 bool NoConstOpB = HasNoConstOp(B); 1533 return NoConstOpA < NoConstOpB; 1534 } 1535 if (A.isConditionFact()) 1536 return true; 1537 if (B.isConditionFact()) 1538 return false; 1539 auto *InstA = A.getContextInst(); 1540 auto *InstB = B.getContextInst(); 1541 return InstA->comesBefore(InstB); 1542 } 1543 return A.NumIn < B.NumIn; 1544 }); 1545 1546 SmallVector<Instruction *> ToRemove; 1547 1548 // Finally, process ordered worklist and eliminate implied conditions. 1549 SmallVector<StackEntry, 16> DFSInStack; 1550 SmallVector<ReproducerEntry> ReproducerCondStack; 1551 for (FactOrCheck &CB : S.WorkList) { 1552 // First, pop entries from the stack that are out-of-scope for CB. Remove 1553 // the corresponding entry from the constraint system. 1554 while (!DFSInStack.empty()) { 1555 auto &E = DFSInStack.back(); 1556 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 1557 << "\n"); 1558 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 1559 assert(E.NumIn <= CB.NumIn); 1560 if (CB.NumOut <= E.NumOut) 1561 break; 1562 LLVM_DEBUG({ 1563 dbgs() << "Removing "; 1564 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(), 1565 Info.getValue2Index(E.IsSigned)); 1566 dbgs() << "\n"; 1567 }); 1568 removeEntryFromStack(E, Info, ReproducerModule.get(), ReproducerCondStack, 1569 DFSInStack); 1570 } 1571 1572 LLVM_DEBUG(dbgs() << "Processing "); 1573 1574 // For a block, check if any CmpInsts become known based on the current set 1575 // of constraints. 1576 if (CB.isCheck()) { 1577 Instruction *Inst = CB.getInstructionToSimplify(); 1578 if (!Inst) 1579 continue; 1580 LLVM_DEBUG(dbgs() << "condition to simplify: " << *Inst << "\n"); 1581 if (auto *II = dyn_cast<WithOverflowInst>(Inst)) { 1582 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove); 1583 } else if (auto *Cmp = dyn_cast<ICmpInst>(Inst)) { 1584 bool Simplified = checkAndReplaceCondition( 1585 Cmp, Info, CB.NumIn, CB.NumOut, CB.getContextInst(), 1586 ReproducerModule.get(), ReproducerCondStack, S.DT, ToRemove); 1587 if (!Simplified && match(CB.getContextInst(), 1588 m_LogicalAnd(m_Value(), m_Specific(Inst)))) { 1589 Simplified = 1590 checkAndSecondOpImpliedByFirst(CB, Info, ReproducerModule.get(), 1591 ReproducerCondStack, DFSInStack); 1592 } 1593 Changed |= Simplified; 1594 } 1595 continue; 1596 } 1597 1598 auto AddFact = [&](CmpInst::Predicate Pred, Value *A, Value *B) { 1599 LLVM_DEBUG(dbgs() << "fact to add to the system: " 1600 << CmpInst::getPredicateName(Pred) << " "; 1601 A->printAsOperand(dbgs()); dbgs() << ", "; 1602 B->printAsOperand(dbgs()); dbgs() << "\n"); 1603 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) { 1604 LLVM_DEBUG( 1605 dbgs() 1606 << "Skip adding constraint because system has too many rows.\n"); 1607 return; 1608 } 1609 1610 LLVM_DEBUG({ 1611 dbgs() << "Processing fact to add to the system: " << Pred << " "; 1612 A->printAsOperand(dbgs()); 1613 dbgs() << ", "; 1614 B->printAsOperand(dbgs(), false); 1615 dbgs() << "\n"; 1616 }); 1617 1618 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1619 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) 1620 ReproducerCondStack.emplace_back(Pred, A, B); 1621 1622 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1623 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) { 1624 // Add dummy entries to ReproducerCondStack to keep it in sync with 1625 // DFSInStack. 1626 for (unsigned I = 0, 1627 E = (DFSInStack.size() - ReproducerCondStack.size()); 1628 I < E; ++I) { 1629 ReproducerCondStack.emplace_back(ICmpInst::BAD_ICMP_PREDICATE, 1630 nullptr, nullptr); 1631 } 1632 } 1633 }; 1634 1635 ICmpInst::Predicate Pred; 1636 if (!CB.isConditionFact()) { 1637 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(CB.Inst)) { 1638 Pred = ICmpInst::getNonStrictPredicate(MinMax->getPredicate()); 1639 AddFact(Pred, MinMax, MinMax->getLHS()); 1640 AddFact(Pred, MinMax, MinMax->getRHS()); 1641 continue; 1642 } 1643 } 1644 1645 Value *A = nullptr, *B = nullptr; 1646 if (CB.isConditionFact()) { 1647 Pred = CB.Cond.Pred; 1648 A = CB.Cond.Op0; 1649 B = CB.Cond.Op1; 1650 if (CB.DoesHold.Pred != CmpInst::BAD_ICMP_PREDICATE && 1651 !Info.doesHold(CB.DoesHold.Pred, CB.DoesHold.Op0, CB.DoesHold.Op1)) 1652 continue; 1653 } else { 1654 bool Matched = match(CB.Inst, m_Intrinsic<Intrinsic::assume>( 1655 m_ICmp(Pred, m_Value(A), m_Value(B)))); 1656 (void)Matched; 1657 assert(Matched && "Must have an assume intrinsic with a icmp operand"); 1658 } 1659 AddFact(Pred, A, B); 1660 } 1661 1662 if (ReproducerModule && !ReproducerModule->functions().empty()) { 1663 std::string S; 1664 raw_string_ostream StringS(S); 1665 ReproducerModule->print(StringS, nullptr); 1666 StringS.flush(); 1667 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F); 1668 Rem << ore::NV("module") << S; 1669 ORE.emit(Rem); 1670 } 1671 1672 #ifndef NDEBUG 1673 unsigned SignedEntries = 1674 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 1675 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 1676 "updates to CS and DFSInStack are out of sync"); 1677 assert(Info.getCS(true).size() == SignedEntries && 1678 "updates to CS and DFSInStack are out of sync"); 1679 #endif 1680 1681 for (Instruction *I : ToRemove) 1682 I->eraseFromParent(); 1683 return Changed; 1684 } 1685 1686 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 1687 FunctionAnalysisManager &AM) { 1688 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1689 auto &LI = AM.getResult<LoopAnalysis>(F); 1690 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 1691 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1692 if (!eliminateConstraints(F, DT, LI, SE, ORE)) 1693 return PreservedAnalyses::all(); 1694 1695 PreservedAnalyses PA; 1696 PA.preserve<DominatorTreeAnalysis>(); 1697 PA.preserve<LoopAnalysis>(); 1698 PA.preserve<ScalarEvolutionAnalysis>(); 1699 PA.preserveSet<CFGAnalyses>(); 1700 return PA; 1701 } 1702