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