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/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/GetElementPtrTypeIterator.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/PatternMatch.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/DebugCounter.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Transforms/Utils/Cloning.h" 37 #include "llvm/Transforms/Utils/ValueMapper.h" 38 39 #include <cmath> 40 #include <string> 41 42 using namespace llvm; 43 using namespace PatternMatch; 44 45 #define DEBUG_TYPE "constraint-elimination" 46 47 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 48 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 49 "Controls which conditions are eliminated"); 50 51 static cl::opt<unsigned> 52 MaxRows("constraint-elimination-max-rows", cl::init(500), cl::Hidden, 53 cl::desc("Maximum number of rows to keep in constraint system")); 54 55 static cl::opt<bool> DumpReproducers( 56 "constraint-elimination-dump-reproducers", cl::init(false), cl::Hidden, 57 cl::desc("Dump IR to reproduce successful transformations.")); 58 59 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 60 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 61 62 // A helper to multiply 2 signed integers where overflowing is allowed. 63 static int64_t multiplyWithOverflow(int64_t A, int64_t B) { 64 int64_t Result; 65 MulOverflow(A, B, Result); 66 return Result; 67 } 68 69 // A helper to add 2 signed integers where overflowing is allowed. 70 static int64_t addWithOverflow(int64_t A, int64_t B) { 71 int64_t Result; 72 AddOverflow(A, B, Result); 73 return Result; 74 } 75 76 namespace { 77 78 class ConstraintInfo; 79 80 struct StackEntry { 81 unsigned NumIn; 82 unsigned NumOut; 83 bool IsSigned = false; 84 /// Variables that can be removed from the system once the stack entry gets 85 /// removed. 86 SmallVector<Value *, 2> ValuesToRelease; 87 88 StackEntry(unsigned NumIn, unsigned NumOut, bool IsSigned, 89 SmallVector<Value *, 2> ValuesToRelease) 90 : NumIn(NumIn), NumOut(NumOut), IsSigned(IsSigned), 91 ValuesToRelease(ValuesToRelease) {} 92 }; 93 94 /// Struct to express a pre-condition of the form %Op0 Pred %Op1. 95 struct PreconditionTy { 96 CmpInst::Predicate Pred; 97 Value *Op0; 98 Value *Op1; 99 100 PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 101 : Pred(Pred), Op0(Op0), Op1(Op1) {} 102 }; 103 104 struct ConstraintTy { 105 SmallVector<int64_t, 8> Coefficients; 106 SmallVector<PreconditionTy, 2> Preconditions; 107 108 SmallVector<SmallVector<int64_t, 8>> ExtraInfo; 109 110 bool IsSigned = false; 111 bool IsEq = false; 112 113 ConstraintTy() = default; 114 115 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned) 116 : Coefficients(Coefficients), IsSigned(IsSigned) {} 117 118 unsigned size() const { return Coefficients.size(); } 119 120 unsigned empty() const { return Coefficients.empty(); } 121 122 /// Returns true if all preconditions for this list of constraints are 123 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 124 bool isValid(const ConstraintInfo &Info) const; 125 }; 126 127 /// Wrapper encapsulating separate constraint systems and corresponding value 128 /// mappings for both unsigned and signed information. Facts are added to and 129 /// conditions are checked against the corresponding system depending on the 130 /// signed-ness of their predicates. While the information is kept separate 131 /// based on signed-ness, certain conditions can be transferred between the two 132 /// systems. 133 class ConstraintInfo { 134 135 ConstraintSystem UnsignedCS; 136 ConstraintSystem SignedCS; 137 138 const DataLayout &DL; 139 140 public: 141 ConstraintInfo(const DataLayout &DL) : DL(DL) {} 142 143 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 144 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 145 } 146 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 147 return Signed ? SignedCS.getValue2Index() : UnsignedCS.getValue2Index(); 148 } 149 150 ConstraintSystem &getCS(bool Signed) { 151 return Signed ? SignedCS : UnsignedCS; 152 } 153 const ConstraintSystem &getCS(bool Signed) const { 154 return Signed ? SignedCS : UnsignedCS; 155 } 156 157 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 158 void popLastNVariables(bool Signed, unsigned N) { 159 getCS(Signed).popLastNVariables(N); 160 } 161 162 bool doesHold(CmpInst::Predicate Pred, Value *A, Value *B) const; 163 164 void addFact(CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 165 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack); 166 167 /// Turn a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 168 /// constraints, using indices from the corresponding constraint system. 169 /// New variables that need to be added to the system are collected in 170 /// \p NewVariables. 171 ConstraintTy getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 172 SmallVectorImpl<Value *> &NewVariables) const; 173 174 /// Turns a comparison of the form \p Op0 \p Pred \p Op1 into a vector of 175 /// constraints using getConstraint. Returns an empty constraint if the result 176 /// cannot be used to query the existing constraint system, e.g. because it 177 /// would require adding new variables. Also tries to convert signed 178 /// predicates to unsigned ones if possible to allow using the unsigned system 179 /// which increases the effectiveness of the signed <-> unsigned transfer 180 /// logic. 181 ConstraintTy getConstraintForSolving(CmpInst::Predicate Pred, Value *Op0, 182 Value *Op1) const; 183 184 /// Try to add information from \p A \p Pred \p B to the unsigned/signed 185 /// system if \p Pred is signed/unsigned. 186 void transferToOtherSystem(CmpInst::Predicate Pred, Value *A, Value *B, 187 unsigned NumIn, unsigned NumOut, 188 SmallVectorImpl<StackEntry> &DFSInStack); 189 }; 190 191 /// Represents a (Coefficient * Variable) entry after IR decomposition. 192 struct DecompEntry { 193 int64_t Coefficient; 194 Value *Variable; 195 /// True if the variable is known positive in the current constraint. 196 bool IsKnownNonNegative; 197 198 DecompEntry(int64_t Coefficient, Value *Variable, 199 bool IsKnownNonNegative = false) 200 : Coefficient(Coefficient), Variable(Variable), 201 IsKnownNonNegative(IsKnownNonNegative) {} 202 }; 203 204 /// Represents an Offset + Coefficient1 * Variable1 + ... decomposition. 205 struct Decomposition { 206 int64_t Offset = 0; 207 SmallVector<DecompEntry, 3> Vars; 208 209 Decomposition(int64_t Offset) : Offset(Offset) {} 210 Decomposition(Value *V, bool IsKnownNonNegative = false) { 211 Vars.emplace_back(1, V, IsKnownNonNegative); 212 } 213 Decomposition(int64_t Offset, ArrayRef<DecompEntry> Vars) 214 : Offset(Offset), Vars(Vars) {} 215 216 void add(int64_t OtherOffset) { 217 Offset = addWithOverflow(Offset, OtherOffset); 218 } 219 220 void add(const Decomposition &Other) { 221 add(Other.Offset); 222 append_range(Vars, Other.Vars); 223 } 224 225 void mul(int64_t Factor) { 226 Offset = multiplyWithOverflow(Offset, Factor); 227 for (auto &Var : Vars) 228 Var.Coefficient = multiplyWithOverflow(Var.Coefficient, Factor); 229 } 230 }; 231 232 } // namespace 233 234 static Decomposition decompose(Value *V, 235 SmallVectorImpl<PreconditionTy> &Preconditions, 236 bool IsSigned, const DataLayout &DL); 237 238 static bool canUseSExt(ConstantInt *CI) { 239 const APInt &Val = CI->getValue(); 240 return Val.sgt(MinSignedConstraintValue) && Val.slt(MaxConstraintValue); 241 } 242 243 static Decomposition 244 decomposeGEP(GetElementPtrInst &GEP, 245 SmallVectorImpl<PreconditionTy> &Preconditions, bool IsSigned, 246 const DataLayout &DL) { 247 // Do not reason about pointers where the index size is larger than 64 bits, 248 // as the coefficients used to encode constraints are 64 bit integers. 249 if (DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()) > 64) 250 return &GEP; 251 252 if (!GEP.isInBounds()) 253 return &GEP; 254 255 assert(!IsSigned && "The logic below only supports decomposition for " 256 "unsinged predicates at the moment."); 257 Type *PtrTy = GEP.getType()->getScalarType(); 258 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy); 259 MapVector<Value *, APInt> VariableOffsets; 260 APInt ConstantOffset(BitWidth, 0); 261 if (!GEP.collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) 262 return &GEP; 263 264 // Handle the (gep (gep ....), C) case by incrementing the constant 265 // coefficient of the inner GEP, if C is a constant. 266 auto *InnerGEP = dyn_cast<GetElementPtrInst>(GEP.getPointerOperand()); 267 if (VariableOffsets.empty() && InnerGEP && InnerGEP->getNumOperands() == 2) { 268 auto Result = decompose(InnerGEP, Preconditions, IsSigned, DL); 269 Result.add(ConstantOffset.getSExtValue()); 270 271 if (ConstantOffset.isNegative()) { 272 unsigned Scale = DL.getTypeAllocSize(InnerGEP->getResultElementType()); 273 int64_t ConstantOffsetI = ConstantOffset.getSExtValue(); 274 if (ConstantOffsetI % Scale != 0) 275 return &GEP; 276 // Add pre-condition ensuring the GEP is increasing monotonically and 277 // can be de-composed. 278 // Both sides are normalized by being divided by Scale. 279 Preconditions.emplace_back( 280 CmpInst::ICMP_SGE, InnerGEP->getOperand(1), 281 ConstantInt::get(InnerGEP->getOperand(1)->getType(), 282 -1 * (ConstantOffsetI / Scale))); 283 } 284 return Result; 285 } 286 287 Decomposition Result(ConstantOffset.getSExtValue(), 288 DecompEntry(1, GEP.getPointerOperand())); 289 for (auto [Index, Scale] : VariableOffsets) { 290 auto IdxResult = decompose(Index, Preconditions, IsSigned, DL); 291 IdxResult.mul(Scale.getSExtValue()); 292 Result.add(IdxResult); 293 294 // If Op0 is signed non-negative, the GEP is increasing monotonically and 295 // can be de-composed. 296 if (!isKnownNonNegative(Index, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 297 Preconditions.emplace_back(CmpInst::ICMP_SGE, Index, 298 ConstantInt::get(Index->getType(), 0)); 299 } 300 return Result; 301 } 302 303 // Decomposes \p V into a constant offset + list of pairs { Coefficient, 304 // Variable } where Coefficient * Variable. The sum of the constant offset and 305 // pairs equals \p V. 306 static Decomposition decompose(Value *V, 307 SmallVectorImpl<PreconditionTy> &Preconditions, 308 bool IsSigned, const DataLayout &DL) { 309 310 auto MergeResults = [&Preconditions, IsSigned, &DL](Value *A, Value *B, 311 bool IsSignedB) { 312 auto ResA = decompose(A, Preconditions, IsSigned, DL); 313 auto ResB = decompose(B, Preconditions, IsSignedB, DL); 314 ResA.add(ResB); 315 return ResA; 316 }; 317 318 // Decompose \p V used with a signed predicate. 319 if (IsSigned) { 320 if (auto *CI = dyn_cast<ConstantInt>(V)) { 321 if (canUseSExt(CI)) 322 return CI->getSExtValue(); 323 } 324 Value *Op0; 325 Value *Op1; 326 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) 327 return MergeResults(Op0, Op1, IsSigned); 328 329 return V; 330 } 331 332 if (auto *CI = dyn_cast<ConstantInt>(V)) { 333 if (CI->uge(MaxConstraintValue)) 334 return V; 335 return int64_t(CI->getZExtValue()); 336 } 337 338 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) 339 return decomposeGEP(*GEP, Preconditions, IsSigned, DL); 340 341 Value *Op0; 342 bool IsKnownNonNegative = false; 343 if (match(V, m_ZExt(m_Value(Op0)))) { 344 IsKnownNonNegative = true; 345 V = Op0; 346 } 347 348 Value *Op1; 349 ConstantInt *CI; 350 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) { 351 return MergeResults(Op0, Op1, IsSigned); 352 } 353 if (match(V, m_NSWAdd(m_Value(Op0), m_Value(Op1)))) { 354 if (!isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 355 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 356 ConstantInt::get(Op0->getType(), 0)); 357 if (!isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 358 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op1, 359 ConstantInt::get(Op1->getType(), 0)); 360 361 return MergeResults(Op0, Op1, IsSigned); 362 } 363 364 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative() && 365 canUseSExt(CI)) { 366 Preconditions.emplace_back( 367 CmpInst::ICMP_UGE, Op0, 368 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 369 return MergeResults(Op0, CI, true); 370 } 371 372 if (match(V, m_NUWShl(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI)) { 373 int64_t Mult = int64_t(std::pow(int64_t(2), CI->getSExtValue())); 374 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 375 Result.mul(Mult); 376 return Result; 377 } 378 379 if (match(V, m_NUWMul(m_Value(Op1), m_ConstantInt(CI))) && canUseSExt(CI) && 380 (!CI->isNegative())) { 381 auto Result = decompose(Op1, Preconditions, IsSigned, DL); 382 Result.mul(CI->getSExtValue()); 383 return Result; 384 } 385 386 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI))) && canUseSExt(CI)) 387 return {-1 * CI->getSExtValue(), {{1, Op0}}}; 388 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 389 return {0, {{1, Op0}, {-1, Op1}}}; 390 391 return {V, IsKnownNonNegative}; 392 } 393 394 ConstraintTy 395 ConstraintInfo::getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 396 SmallVectorImpl<Value *> &NewVariables) const { 397 assert(NewVariables.empty() && "NewVariables must be empty when passed in"); 398 bool IsEq = false; 399 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 400 switch (Pred) { 401 case CmpInst::ICMP_UGT: 402 case CmpInst::ICMP_UGE: 403 case CmpInst::ICMP_SGT: 404 case CmpInst::ICMP_SGE: { 405 Pred = CmpInst::getSwappedPredicate(Pred); 406 std::swap(Op0, Op1); 407 break; 408 } 409 case CmpInst::ICMP_EQ: 410 if (match(Op1, m_Zero())) { 411 Pred = CmpInst::ICMP_ULE; 412 } else { 413 IsEq = true; 414 Pred = CmpInst::ICMP_ULE; 415 } 416 break; 417 case CmpInst::ICMP_NE: 418 if (!match(Op1, m_Zero())) 419 return {}; 420 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 421 std::swap(Op0, Op1); 422 break; 423 default: 424 break; 425 } 426 427 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 428 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 429 return {}; 430 431 SmallVector<PreconditionTy, 4> Preconditions; 432 bool IsSigned = CmpInst::isSigned(Pred); 433 auto &Value2Index = getValue2Index(IsSigned); 434 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 435 Preconditions, IsSigned, DL); 436 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 437 Preconditions, IsSigned, DL); 438 int64_t Offset1 = ADec.Offset; 439 int64_t Offset2 = BDec.Offset; 440 Offset1 *= -1; 441 442 auto &VariablesA = ADec.Vars; 443 auto &VariablesB = BDec.Vars; 444 445 // First try to look up \p V in Value2Index and NewVariables. Otherwise add a 446 // new entry to NewVariables. 447 DenseMap<Value *, unsigned> NewIndexMap; 448 auto GetOrAddIndex = [&Value2Index, &NewVariables, 449 &NewIndexMap](Value *V) -> unsigned { 450 auto V2I = Value2Index.find(V); 451 if (V2I != Value2Index.end()) 452 return V2I->second; 453 auto Insert = 454 NewIndexMap.insert({V, Value2Index.size() + NewVariables.size() + 1}); 455 if (Insert.second) 456 NewVariables.push_back(V); 457 return Insert.first->second; 458 }; 459 460 // Make sure all variables have entries in Value2Index or NewVariables. 461 for (const auto &KV : concat<DecompEntry>(VariablesA, VariablesB)) 462 GetOrAddIndex(KV.Variable); 463 464 // Build result constraint, by first adding all coefficients from A and then 465 // subtracting all coefficients from B. 466 ConstraintTy Res( 467 SmallVector<int64_t, 8>(Value2Index.size() + NewVariables.size() + 1, 0), 468 IsSigned); 469 // Collect variables that are known to be positive in all uses in the 470 // constraint. 471 DenseMap<Value *, bool> KnownNonNegativeVariables; 472 Res.IsEq = IsEq; 473 auto &R = Res.Coefficients; 474 for (const auto &KV : VariablesA) { 475 R[GetOrAddIndex(KV.Variable)] += KV.Coefficient; 476 auto I = 477 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 478 I.first->second &= KV.IsKnownNonNegative; 479 } 480 481 for (const auto &KV : VariablesB) { 482 R[GetOrAddIndex(KV.Variable)] -= KV.Coefficient; 483 auto I = 484 KnownNonNegativeVariables.insert({KV.Variable, KV.IsKnownNonNegative}); 485 I.first->second &= KV.IsKnownNonNegative; 486 } 487 488 int64_t OffsetSum; 489 if (AddOverflow(Offset1, Offset2, OffsetSum)) 490 return {}; 491 if (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT)) 492 if (AddOverflow(OffsetSum, int64_t(-1), OffsetSum)) 493 return {}; 494 R[0] = OffsetSum; 495 Res.Preconditions = std::move(Preconditions); 496 497 // Remove any (Coefficient, Variable) entry where the Coefficient is 0 for new 498 // variables. 499 while (!NewVariables.empty()) { 500 int64_t Last = R.back(); 501 if (Last != 0) 502 break; 503 R.pop_back(); 504 Value *RemovedV = NewVariables.pop_back_val(); 505 NewIndexMap.erase(RemovedV); 506 } 507 508 // Add extra constraints for variables that are known positive. 509 for (auto &KV : KnownNonNegativeVariables) { 510 if (!KV.second || (Value2Index.find(KV.first) == Value2Index.end() && 511 NewIndexMap.find(KV.first) == NewIndexMap.end())) 512 continue; 513 SmallVector<int64_t, 8> C(Value2Index.size() + NewVariables.size() + 1, 0); 514 C[GetOrAddIndex(KV.first)] = -1; 515 Res.ExtraInfo.push_back(C); 516 } 517 return Res; 518 } 519 520 ConstraintTy ConstraintInfo::getConstraintForSolving(CmpInst::Predicate Pred, 521 Value *Op0, 522 Value *Op1) const { 523 // If both operands are known to be non-negative, change signed predicates to 524 // unsigned ones. This increases the reasoning effectiveness in combination 525 // with the signed <-> unsigned transfer logic. 526 if (CmpInst::isSigned(Pred) && 527 isKnownNonNegative(Op0, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1) && 528 isKnownNonNegative(Op1, DL, /*Depth=*/MaxAnalysisRecursionDepth - 1)) 529 Pred = CmpInst::getUnsignedPredicate(Pred); 530 531 SmallVector<Value *> NewVariables; 532 ConstraintTy R = getConstraint(Pred, Op0, Op1, NewVariables); 533 if (R.IsEq || !NewVariables.empty()) 534 return {}; 535 return R; 536 } 537 538 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 539 return Coefficients.size() > 0 && 540 all_of(Preconditions, [&Info](const PreconditionTy &C) { 541 return Info.doesHold(C.Pred, C.Op0, C.Op1); 542 }); 543 } 544 545 bool ConstraintInfo::doesHold(CmpInst::Predicate Pred, Value *A, 546 Value *B) const { 547 auto R = getConstraintForSolving(Pred, A, B); 548 return R.Preconditions.empty() && !R.empty() && 549 getCS(R.IsSigned).isConditionImplied(R.Coefficients); 550 } 551 552 void ConstraintInfo::transferToOtherSystem( 553 CmpInst::Predicate Pred, Value *A, Value *B, unsigned NumIn, 554 unsigned NumOut, SmallVectorImpl<StackEntry> &DFSInStack) { 555 // Check if we can combine facts from the signed and unsigned systems to 556 // derive additional facts. 557 if (!A->getType()->isIntegerTy()) 558 return; 559 // FIXME: This currently depends on the order we add facts. Ideally we 560 // would first add all known facts and only then try to add additional 561 // facts. 562 switch (Pred) { 563 default: 564 break; 565 case CmpInst::ICMP_ULT: 566 // If B is a signed positive constant, A >=s 0 and A <s B. 567 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 568 addFact(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0), NumIn, 569 NumOut, DFSInStack); 570 addFact(CmpInst::ICMP_SLT, A, B, NumIn, NumOut, DFSInStack); 571 } 572 break; 573 case CmpInst::ICMP_SLT: 574 if (doesHold(CmpInst::ICMP_SGE, A, ConstantInt::get(B->getType(), 0))) 575 addFact(CmpInst::ICMP_ULT, A, B, NumIn, NumOut, DFSInStack); 576 break; 577 case CmpInst::ICMP_SGT: 578 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), -1))) 579 addFact(CmpInst::ICMP_UGE, A, ConstantInt::get(B->getType(), 0), NumIn, 580 NumOut, DFSInStack); 581 break; 582 case CmpInst::ICMP_SGE: 583 if (doesHold(CmpInst::ICMP_SGE, B, ConstantInt::get(B->getType(), 0))) { 584 addFact(CmpInst::ICMP_UGE, A, B, NumIn, NumOut, DFSInStack); 585 } 586 break; 587 } 588 } 589 590 namespace { 591 /// Represents either 592 /// * a condition that holds on entry to a block (=conditional fact) 593 /// * an assume (=assume fact) 594 /// * an instruction to simplify. 595 /// It also tracks the Dominator DFS in and out numbers for each entry. 596 struct FactOrCheck { 597 Instruction *Inst; 598 unsigned NumIn; 599 unsigned NumOut; 600 bool IsCheck; 601 bool Not; 602 603 FactOrCheck(DomTreeNode *DTN, Instruction *Inst, bool IsCheck, bool Not) 604 : Inst(Inst), NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), 605 IsCheck(IsCheck), Not(Not) {} 606 607 static FactOrCheck getFact(DomTreeNode *DTN, Instruction *Inst, 608 bool Not = false) { 609 return FactOrCheck(DTN, Inst, false, Not); 610 } 611 612 static FactOrCheck getCheck(DomTreeNode *DTN, Instruction *Inst) { 613 return FactOrCheck(DTN, Inst, true, false); 614 } 615 616 bool isAssumeFact() const { 617 if (!IsCheck && isa<IntrinsicInst>(Inst)) { 618 assert(match(Inst, m_Intrinsic<Intrinsic::assume>())); 619 return true; 620 } 621 return false; 622 } 623 624 bool isConditionFact() const { return !IsCheck && isa<CmpInst>(Inst); } 625 }; 626 627 /// Keep state required to build worklist. 628 struct State { 629 DominatorTree &DT; 630 SmallVector<FactOrCheck, 64> WorkList; 631 632 State(DominatorTree &DT) : DT(DT) {} 633 634 /// Process block \p BB and add known facts to work-list. 635 void addInfoFor(BasicBlock &BB); 636 637 /// Returns true if we can add a known condition from BB to its successor 638 /// block Succ. 639 bool canAddSuccessor(BasicBlock &BB, BasicBlock *Succ) const { 640 return DT.dominates(BasicBlockEdge(&BB, Succ), Succ); 641 } 642 }; 643 644 } // namespace 645 646 #ifndef NDEBUG 647 648 static void dumpConstraint(ArrayRef<int64_t> C, 649 const DenseMap<Value *, unsigned> &Value2Index) { 650 ConstraintSystem CS(Value2Index); 651 CS.addVariableRowFill(C); 652 CS.dump(); 653 } 654 #endif 655 656 void State::addInfoFor(BasicBlock &BB) { 657 // True as long as long as the current instruction is guaranteed to execute. 658 bool GuaranteedToExecute = true; 659 // Queue conditions and assumes. 660 for (Instruction &I : BB) { 661 if (auto Cmp = dyn_cast<ICmpInst>(&I)) { 662 WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), Cmp)); 663 continue; 664 } 665 666 if (match(&I, m_Intrinsic<Intrinsic::ssub_with_overflow>())) { 667 WorkList.push_back(FactOrCheck::getCheck(DT.getNode(&BB), &I)); 668 continue; 669 } 670 671 Value *Cond; 672 // For now, just handle assumes with a single compare as condition. 673 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 674 isa<ICmpInst>(Cond)) { 675 if (GuaranteedToExecute) { 676 // The assume is guaranteed to execute when BB is entered, hence Cond 677 // holds on entry to BB. 678 WorkList.emplace_back(FactOrCheck::getFact(DT.getNode(I.getParent()), 679 cast<Instruction>(Cond))); 680 } else { 681 WorkList.emplace_back( 682 FactOrCheck::getFact(DT.getNode(I.getParent()), &I)); 683 } 684 } 685 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 686 } 687 688 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 689 if (!Br || !Br->isConditional()) 690 return; 691 692 Value *Cond = Br->getCondition(); 693 694 // If the condition is a chain of ORs/AND and the successor only has the 695 // current block as predecessor, queue conditions for the successor. 696 Value *Op0, *Op1; 697 if (match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1))) || 698 match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 699 bool IsOr = match(Cond, m_LogicalOr()); 700 bool IsAnd = match(Cond, m_LogicalAnd()); 701 // If there's a select that matches both AND and OR, we need to commit to 702 // one of the options. Arbitrarily pick OR. 703 if (IsOr && IsAnd) 704 IsAnd = false; 705 706 BasicBlock *Successor = Br->getSuccessor(IsOr ? 1 : 0); 707 if (canAddSuccessor(BB, Successor)) { 708 SmallVector<Value *> CondWorkList; 709 SmallPtrSet<Value *, 8> SeenCond; 710 auto QueueValue = [&CondWorkList, &SeenCond](Value *V) { 711 if (SeenCond.insert(V).second) 712 CondWorkList.push_back(V); 713 }; 714 QueueValue(Op1); 715 QueueValue(Op0); 716 while (!CondWorkList.empty()) { 717 Value *Cur = CondWorkList.pop_back_val(); 718 if (auto *Cmp = dyn_cast<ICmpInst>(Cur)) { 719 WorkList.emplace_back( 720 FactOrCheck::getFact(DT.getNode(Successor), Cmp, IsOr)); 721 continue; 722 } 723 if (IsOr && match(Cur, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 724 QueueValue(Op1); 725 QueueValue(Op0); 726 continue; 727 } 728 if (IsAnd && match(Cur, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 729 QueueValue(Op1); 730 QueueValue(Op0); 731 continue; 732 } 733 } 734 } 735 return; 736 } 737 738 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 739 if (!CmpI) 740 return; 741 if (canAddSuccessor(BB, Br->getSuccessor(0))) 742 WorkList.emplace_back( 743 FactOrCheck::getFact(DT.getNode(Br->getSuccessor(0)), CmpI)); 744 if (canAddSuccessor(BB, Br->getSuccessor(1))) 745 WorkList.emplace_back( 746 FactOrCheck::getFact(DT.getNode(Br->getSuccessor(1)), CmpI, true)); 747 } 748 749 namespace { 750 /// Helper to keep track of a condition and if it should be treated as negated 751 /// for reproducer construction. 752 struct ReproducerEntry { 753 CmpInst *Cond; 754 bool IsNot; 755 756 ReproducerEntry(CmpInst *Cond, bool IsNot) : Cond(Cond), IsNot(IsNot) {} 757 }; 758 } // namespace 759 760 /// Helper function to generate a reproducer function for simplifying \p Cond. 761 /// The reproducer function contains a series of @llvm.assume calls, one for 762 /// each condition in \p Stack. For each condition, the operand instruction are 763 /// cloned until we reach operands that have an entry in \p Value2Index. Those 764 /// will then be added as function arguments. \p DT is used to order cloned 765 /// instructions. The reproducer function will get added to \p M, if it is 766 /// non-null. Otherwise no reproducer function is generated. 767 static void generateReproducer(CmpInst *Cond, Module *M, 768 ArrayRef<ReproducerEntry> Stack, 769 ConstraintInfo &Info, DominatorTree &DT) { 770 if (!M) 771 return; 772 773 LLVMContext &Ctx = Cond->getContext(); 774 775 LLVM_DEBUG(dbgs() << "Creating reproducer for " << *Cond << "\n"); 776 777 ValueToValueMapTy Old2New; 778 SmallVector<Value *> Args; 779 SmallPtrSet<Value *, 8> Seen; 780 // Traverse Cond and its operands recursively until we reach a value that's in 781 // Value2Index or not an instruction, or not a operation that 782 // ConstraintElimination can decompose. Such values will be considered as 783 // external inputs to the reproducer, they are collected and added as function 784 // arguments later. 785 auto CollectArguments = [&](CmpInst *Cond) { 786 if (!Cond) 787 return; 788 auto &Value2Index = 789 Info.getValue2Index(CmpInst::isSigned(Cond->getPredicate())); 790 SmallVector<Value *, 4> WorkList; 791 WorkList.push_back(Cond); 792 while (!WorkList.empty()) { 793 Value *V = WorkList.pop_back_val(); 794 if (!Seen.insert(V).second) 795 continue; 796 if (Old2New.find(V) != Old2New.end()) 797 continue; 798 if (isa<Constant>(V)) 799 continue; 800 801 auto *I = dyn_cast<Instruction>(V); 802 if (Value2Index.find(V) != Value2Index.end() || !I || 803 !isa<CmpInst, BinaryOperator, GetElementPtrInst, CastInst>(V)) { 804 Old2New[V] = V; 805 Args.push_back(V); 806 LLVM_DEBUG(dbgs() << " found external input " << *V << "\n"); 807 } else { 808 append_range(WorkList, I->operands()); 809 } 810 } 811 }; 812 813 for (auto &Entry : Stack) 814 CollectArguments(Entry.Cond); 815 CollectArguments(Cond); 816 817 SmallVector<Type *> ParamTys; 818 for (auto *P : Args) 819 ParamTys.push_back(P->getType()); 820 821 FunctionType *FTy = FunctionType::get(Cond->getType(), ParamTys, 822 /*isVarArg=*/false); 823 Function *F = Function::Create(FTy, Function::ExternalLinkage, 824 Cond->getModule()->getName() + 825 Cond->getFunction()->getName() + "repro", 826 M); 827 // Add arguments to the reproducer function for each external value collected. 828 for (unsigned I = 0; I < Args.size(); ++I) { 829 F->getArg(I)->setName(Args[I]->getName()); 830 Old2New[Args[I]] = F->getArg(I); 831 } 832 833 BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F); 834 IRBuilder<> Builder(Entry); 835 Builder.CreateRet(Builder.getTrue()); 836 Builder.SetInsertPoint(Entry->getTerminator()); 837 838 // Clone instructions in \p Ops and their operands recursively until reaching 839 // an value in Value2Index (external input to the reproducer). Update Old2New 840 // mapping for the original and cloned instructions. Sort instructions to 841 // clone by dominance, then insert the cloned instructions in the function. 842 auto CloneInstructions = [&](ArrayRef<Value *> Ops, bool IsSigned) { 843 SmallVector<Value *, 4> WorkList(Ops); 844 SmallVector<Instruction *> ToClone; 845 auto &Value2Index = Info.getValue2Index(IsSigned); 846 while (!WorkList.empty()) { 847 Value *V = WorkList.pop_back_val(); 848 if (Old2New.find(V) != Old2New.end()) 849 continue; 850 851 auto *I = dyn_cast<Instruction>(V); 852 if (Value2Index.find(V) == Value2Index.end() && I) { 853 Old2New[V] = nullptr; 854 ToClone.push_back(I); 855 append_range(WorkList, I->operands()); 856 } 857 } 858 859 sort(ToClone, 860 [&DT](Instruction *A, Instruction *B) { return DT.dominates(A, B); }); 861 for (Instruction *I : ToClone) { 862 Instruction *Cloned = I->clone(); 863 Old2New[I] = Cloned; 864 Old2New[I]->setName(I->getName()); 865 Cloned->insertBefore(&*Builder.GetInsertPoint()); 866 Cloned->dropUnknownNonDebugMetadata(); 867 Cloned->setDebugLoc({}); 868 } 869 }; 870 871 // Materialize the assumptions for the reproducer using the entries in Stack. 872 // That is, first clone the operands of the condition recursively until we 873 // reach an external input to the reproducer and add them to the reproducer 874 // function. Then add an ICmp for the condition (with the inverse predicate if 875 // the entry is negated) and an assert using the ICmp. 876 for (auto &Entry : Stack) { 877 if (!Entry.Cond) 878 continue; 879 880 LLVM_DEBUG(dbgs() << " Materializing assumption " << *Entry.Cond << "\n"); 881 CmpInst::Predicate Pred = Entry.Cond->getPredicate(); 882 if (Entry.IsNot) 883 Pred = CmpInst::getInversePredicate(Pred); 884 885 CloneInstructions({Entry.Cond->getOperand(0), Entry.Cond->getOperand(1)}, 886 CmpInst::isSigned(Entry.Cond->getPredicate())); 887 888 auto *Cmp = Builder.CreateICmp(Pred, Entry.Cond->getOperand(0), 889 Entry.Cond->getOperand(1)); 890 Builder.CreateAssumption(Cmp); 891 } 892 893 // Finally, clone the condition to reproduce and remap instruction operands in 894 // the reproducer using Old2New. 895 CloneInstructions(Cond, CmpInst::isSigned(Cond->getPredicate())); 896 Entry->getTerminator()->setOperand(0, Cond); 897 remapInstructionsInBlocks({Entry}, Old2New); 898 899 assert(!verifyFunction(*F, &dbgs())); 900 } 901 902 static bool checkAndReplaceCondition( 903 CmpInst *Cmp, ConstraintInfo &Info, Module *ReproducerModule, 904 ArrayRef<ReproducerEntry> ReproducerCondStack, DominatorTree &DT) { 905 LLVM_DEBUG(dbgs() << "Checking " << *Cmp << "\n"); 906 907 CmpInst::Predicate Pred = Cmp->getPredicate(); 908 Value *A = Cmp->getOperand(0); 909 Value *B = Cmp->getOperand(1); 910 911 auto R = Info.getConstraintForSolving(Pred, A, B); 912 if (R.empty() || !R.isValid(Info)){ 913 LLVM_DEBUG(dbgs() << " failed to decompose condition\n"); 914 return false; 915 } 916 917 auto &CSToUse = Info.getCS(R.IsSigned); 918 919 // If there was extra information collected during decomposition, apply 920 // it now and remove it immediately once we are done with reasoning 921 // about the constraint. 922 for (auto &Row : R.ExtraInfo) 923 CSToUse.addVariableRow(Row); 924 auto InfoRestorer = make_scope_exit([&]() { 925 for (unsigned I = 0; I < R.ExtraInfo.size(); ++I) 926 CSToUse.popLastConstraint(); 927 }); 928 929 bool Changed = false; 930 if (CSToUse.isConditionImplied(R.Coefficients)) { 931 if (!DebugCounter::shouldExecute(EliminatedCounter)) 932 return false; 933 934 LLVM_DEBUG({ 935 dbgs() << "Condition " << *Cmp << " implied by dominating constraints\n"; 936 CSToUse.dump(); 937 }); 938 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT); 939 Constant *TrueC = 940 ConstantInt::getTrue(CmpInst::makeCmpResultType(Cmp->getType())); 941 Cmp->replaceUsesWithIf(TrueC, [](Use &U) { 942 // Conditions in an assume trivially simplify to true. Skip uses 943 // in assume calls to not destroy the available information. 944 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 945 return !II || II->getIntrinsicID() != Intrinsic::assume; 946 }); 947 NumCondsRemoved++; 948 Changed = true; 949 } 950 if (CSToUse.isConditionImplied(ConstraintSystem::negate(R.Coefficients))) { 951 if (!DebugCounter::shouldExecute(EliminatedCounter)) 952 return false; 953 954 LLVM_DEBUG({ 955 dbgs() << "Condition !" << *Cmp << " implied by dominating constraints\n"; 956 CSToUse.dump(); 957 }); 958 generateReproducer(Cmp, ReproducerModule, ReproducerCondStack, Info, DT); 959 Constant *FalseC = 960 ConstantInt::getFalse(CmpInst::makeCmpResultType(Cmp->getType())); 961 Cmp->replaceAllUsesWith(FalseC); 962 NumCondsRemoved++; 963 Changed = true; 964 } 965 return Changed; 966 } 967 968 void ConstraintInfo::addFact(CmpInst::Predicate Pred, Value *A, Value *B, 969 unsigned NumIn, unsigned NumOut, 970 SmallVectorImpl<StackEntry> &DFSInStack) { 971 // If the constraint has a pre-condition, skip the constraint if it does not 972 // hold. 973 SmallVector<Value *> NewVariables; 974 auto R = getConstraint(Pred, A, B, NewVariables); 975 if (!R.isValid(*this)) 976 return; 977 978 LLVM_DEBUG(dbgs() << "Adding '" << CmpInst::getPredicateName(Pred) << " "; 979 A->printAsOperand(dbgs(), false); dbgs() << ", "; 980 B->printAsOperand(dbgs(), false); dbgs() << "'\n"); 981 bool Added = false; 982 auto &CSToUse = getCS(R.IsSigned); 983 if (R.Coefficients.empty()) 984 return; 985 986 Added |= CSToUse.addVariableRowFill(R.Coefficients); 987 988 // If R has been added to the system, add the new variables and queue it for 989 // removal once it goes out-of-scope. 990 if (Added) { 991 SmallVector<Value *, 2> ValuesToRelease; 992 auto &Value2Index = getValue2Index(R.IsSigned); 993 for (Value *V : NewVariables) { 994 Value2Index.insert({V, Value2Index.size() + 1}); 995 ValuesToRelease.push_back(V); 996 } 997 998 LLVM_DEBUG({ 999 dbgs() << " constraint: "; 1000 dumpConstraint(R.Coefficients, getValue2Index(R.IsSigned)); 1001 dbgs() << "\n"; 1002 }); 1003 1004 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1005 std::move(ValuesToRelease)); 1006 1007 if (R.IsEq) { 1008 // Also add the inverted constraint for equality constraints. 1009 for (auto &Coeff : R.Coefficients) 1010 Coeff *= -1; 1011 CSToUse.addVariableRowFill(R.Coefficients); 1012 1013 DFSInStack.emplace_back(NumIn, NumOut, R.IsSigned, 1014 SmallVector<Value *, 2>()); 1015 } 1016 } 1017 } 1018 1019 static bool replaceSubOverflowUses(IntrinsicInst *II, Value *A, Value *B, 1020 SmallVectorImpl<Instruction *> &ToRemove) { 1021 bool Changed = false; 1022 IRBuilder<> Builder(II->getParent(), II->getIterator()); 1023 Value *Sub = nullptr; 1024 for (User *U : make_early_inc_range(II->users())) { 1025 if (match(U, m_ExtractValue<0>(m_Value()))) { 1026 if (!Sub) 1027 Sub = Builder.CreateSub(A, B); 1028 U->replaceAllUsesWith(Sub); 1029 Changed = true; 1030 } else if (match(U, m_ExtractValue<1>(m_Value()))) { 1031 U->replaceAllUsesWith(Builder.getFalse()); 1032 Changed = true; 1033 } else 1034 continue; 1035 1036 if (U->use_empty()) { 1037 auto *I = cast<Instruction>(U); 1038 ToRemove.push_back(I); 1039 I->setOperand(0, PoisonValue::get(II->getType())); 1040 Changed = true; 1041 } 1042 } 1043 1044 if (II->use_empty()) { 1045 II->eraseFromParent(); 1046 Changed = true; 1047 } 1048 return Changed; 1049 } 1050 1051 static bool 1052 tryToSimplifyOverflowMath(IntrinsicInst *II, ConstraintInfo &Info, 1053 SmallVectorImpl<Instruction *> &ToRemove) { 1054 auto DoesConditionHold = [](CmpInst::Predicate Pred, Value *A, Value *B, 1055 ConstraintInfo &Info) { 1056 auto R = Info.getConstraintForSolving(Pred, A, B); 1057 if (R.size() < 2 || !R.isValid(Info)) 1058 return false; 1059 1060 auto &CSToUse = Info.getCS(R.IsSigned); 1061 return CSToUse.isConditionImplied(R.Coefficients); 1062 }; 1063 1064 bool Changed = false; 1065 if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow) { 1066 // If A s>= B && B s>= 0, ssub.with.overflow(a, b) should not overflow and 1067 // can be simplified to a regular sub. 1068 Value *A = II->getArgOperand(0); 1069 Value *B = II->getArgOperand(1); 1070 if (!DoesConditionHold(CmpInst::ICMP_SGE, A, B, Info) || 1071 !DoesConditionHold(CmpInst::ICMP_SGE, B, 1072 ConstantInt::get(A->getType(), 0), Info)) 1073 return false; 1074 Changed = replaceSubOverflowUses(II, A, B, ToRemove); 1075 } 1076 return Changed; 1077 } 1078 1079 static bool eliminateConstraints(Function &F, DominatorTree &DT, 1080 OptimizationRemarkEmitter &ORE) { 1081 bool Changed = false; 1082 DT.updateDFSNumbers(); 1083 1084 ConstraintInfo Info(F.getParent()->getDataLayout()); 1085 State S(DT); 1086 std::unique_ptr<Module> ReproducerModule( 1087 DumpReproducers ? new Module(F.getName(), F.getContext()) : nullptr); 1088 1089 // First, collect conditions implied by branches and blocks with their 1090 // Dominator DFS in and out numbers. 1091 for (BasicBlock &BB : F) { 1092 if (!DT.getNode(&BB)) 1093 continue; 1094 S.addInfoFor(BB); 1095 } 1096 1097 // Next, sort worklist by dominance, so that dominating conditions to check 1098 // and facts come before conditions and facts dominated by them. If a 1099 // condition to check and a fact have the same numbers, conditional facts come 1100 // first. Assume facts and checks are ordered according to their relative 1101 // order in the containing basic block. Also make sure conditions with 1102 // constant operands come before conditions without constant operands. This 1103 // increases the effectiveness of the current signed <-> unsigned fact 1104 // transfer logic. 1105 stable_sort(S.WorkList, [](const FactOrCheck &A, const FactOrCheck &B) { 1106 auto HasNoConstOp = [](const FactOrCheck &B) { 1107 return !isa<ConstantInt>(B.Inst->getOperand(0)) && 1108 !isa<ConstantInt>(B.Inst->getOperand(1)); 1109 }; 1110 // If both entries have the same In numbers, conditional facts come first. 1111 // Otherwise use the relative order in the basic block. 1112 if (A.NumIn == B.NumIn) { 1113 if (A.isConditionFact() && B.isConditionFact()) { 1114 bool NoConstOpA = HasNoConstOp(A); 1115 bool NoConstOpB = HasNoConstOp(B); 1116 return NoConstOpA < NoConstOpB; 1117 } 1118 if (A.isConditionFact()) 1119 return true; 1120 if (B.isConditionFact()) 1121 return false; 1122 return A.Inst->comesBefore(B.Inst); 1123 } 1124 return A.NumIn < B.NumIn; 1125 }); 1126 1127 SmallVector<Instruction *> ToRemove; 1128 1129 // Finally, process ordered worklist and eliminate implied conditions. 1130 SmallVector<StackEntry, 16> DFSInStack; 1131 SmallVector<ReproducerEntry> ReproducerCondStack; 1132 for (FactOrCheck &CB : S.WorkList) { 1133 // First, pop entries from the stack that are out-of-scope for CB. Remove 1134 // the corresponding entry from the constraint system. 1135 while (!DFSInStack.empty()) { 1136 auto &E = DFSInStack.back(); 1137 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 1138 << "\n"); 1139 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 1140 assert(E.NumIn <= CB.NumIn); 1141 if (CB.NumOut <= E.NumOut) 1142 break; 1143 LLVM_DEBUG({ 1144 dbgs() << "Removing "; 1145 dumpConstraint(Info.getCS(E.IsSigned).getLastConstraint(), 1146 Info.getValue2Index(E.IsSigned)); 1147 dbgs() << "\n"; 1148 }); 1149 1150 Info.popLastConstraint(E.IsSigned); 1151 // Remove variables in the system that went out of scope. 1152 auto &Mapping = Info.getValue2Index(E.IsSigned); 1153 for (Value *V : E.ValuesToRelease) 1154 Mapping.erase(V); 1155 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 1156 DFSInStack.pop_back(); 1157 if (ReproducerModule) 1158 ReproducerCondStack.pop_back(); 1159 } 1160 1161 LLVM_DEBUG({ 1162 dbgs() << "Processing "; 1163 if (CB.IsCheck) 1164 dbgs() << "condition to simplify: " << *CB.Inst; 1165 else 1166 dbgs() << "fact to add to the system: " << *CB.Inst; 1167 dbgs() << "\n"; 1168 }); 1169 1170 // For a block, check if any CmpInsts become known based on the current set 1171 // of constraints. 1172 if (CB.IsCheck) { 1173 if (auto *II = dyn_cast<WithOverflowInst>(CB.Inst)) { 1174 Changed |= tryToSimplifyOverflowMath(II, Info, ToRemove); 1175 } else if (auto *Cmp = dyn_cast<ICmpInst>(CB.Inst)) { 1176 Changed |= checkAndReplaceCondition(Cmp, Info, ReproducerModule.get(), 1177 ReproducerCondStack, S.DT); 1178 } 1179 continue; 1180 } 1181 1182 ICmpInst::Predicate Pred; 1183 Value *A, *B; 1184 Value *Cmp = CB.Inst; 1185 match(Cmp, m_Intrinsic<Intrinsic::assume>(m_Value(Cmp))); 1186 if (match(Cmp, m_ICmp(Pred, m_Value(A), m_Value(B)))) { 1187 if (Info.getCS(CmpInst::isSigned(Pred)).size() > MaxRows) { 1188 LLVM_DEBUG( 1189 dbgs() 1190 << "Skip adding constraint because system has too many rows.\n"); 1191 continue; 1192 } 1193 1194 // Use the inverse predicate if required. 1195 if (CB.Not) 1196 Pred = CmpInst::getInversePredicate(Pred); 1197 1198 Info.addFact(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1199 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) 1200 ReproducerCondStack.emplace_back(cast<CmpInst>(Cmp), CB.Not); 1201 1202 Info.transferToOtherSystem(Pred, A, B, CB.NumIn, CB.NumOut, DFSInStack); 1203 if (ReproducerModule && DFSInStack.size() > ReproducerCondStack.size()) { 1204 // Add dummy entries to ReproducerCondStack to keep it in sync with 1205 // DFSInStack. 1206 for (unsigned I = 0, 1207 E = (DFSInStack.size() - ReproducerCondStack.size()); 1208 I < E; ++I) { 1209 ReproducerCondStack.emplace_back(nullptr, false); 1210 } 1211 } 1212 } 1213 } 1214 1215 if (ReproducerModule && !ReproducerModule->functions().empty()) { 1216 std::string S; 1217 raw_string_ostream StringS(S); 1218 ReproducerModule->print(StringS, nullptr); 1219 StringS.flush(); 1220 OptimizationRemark Rem(DEBUG_TYPE, "Reproducer", &F); 1221 Rem << ore::NV("module") << S; 1222 ORE.emit(Rem); 1223 } 1224 1225 #ifndef NDEBUG 1226 unsigned SignedEntries = 1227 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 1228 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 1229 "updates to CS and DFSInStack are out of sync"); 1230 assert(Info.getCS(true).size() == SignedEntries && 1231 "updates to CS and DFSInStack are out of sync"); 1232 #endif 1233 1234 for (Instruction *I : ToRemove) 1235 I->eraseFromParent(); 1236 return Changed; 1237 } 1238 1239 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 1240 FunctionAnalysisManager &AM) { 1241 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1242 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1243 if (!eliminateConstraints(F, DT, ORE)) 1244 return PreservedAnalyses::all(); 1245 1246 PreservedAnalyses PA; 1247 PA.preserve<DominatorTreeAnalysis>(); 1248 PA.preserveSet<CFGAnalyses>(); 1249 return PA; 1250 } 1251