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