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