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/ValueTracking.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/InitializePasses.h" 27 #include "llvm/Pass.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/DebugCounter.h" 30 #include "llvm/Transforms/Scalar.h" 31 32 #include <string> 33 34 using namespace llvm; 35 using namespace PatternMatch; 36 37 #define DEBUG_TYPE "constraint-elimination" 38 39 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 40 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 41 "Controls which conditions are eliminated"); 42 43 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 44 static int64_t MinSignedConstraintValue = std::numeric_limits<int64_t>::min(); 45 46 namespace { 47 48 /// Wrapper encapsulating separate constraint systems and corresponding value 49 /// mappings for both unsigned and signed information. Facts are added to and 50 /// conditions are checked against the corresponding system depending on the 51 /// signed-ness of their predicates. While the information is kept separate 52 /// based on signed-ness, certain conditions can be transferred between the two 53 /// systems. 54 class ConstraintInfo { 55 DenseMap<Value *, unsigned> UnsignedValue2Index; 56 DenseMap<Value *, unsigned> SignedValue2Index; 57 58 ConstraintSystem UnsignedCS; 59 ConstraintSystem SignedCS; 60 61 public: 62 DenseMap<Value *, unsigned> &getValue2Index(bool Signed) { 63 return Signed ? SignedValue2Index : UnsignedValue2Index; 64 } 65 const DenseMap<Value *, unsigned> &getValue2Index(bool Signed) const { 66 return Signed ? SignedValue2Index : UnsignedValue2Index; 67 } 68 69 ConstraintSystem &getCS(bool Signed) { 70 return Signed ? SignedCS : UnsignedCS; 71 } 72 const ConstraintSystem &getCS(bool Signed) const { 73 return Signed ? SignedCS : UnsignedCS; 74 } 75 76 void popLastConstraint(bool Signed) { getCS(Signed).popLastConstraint(); } 77 void popLastNVariables(bool Signed, unsigned N) { 78 getCS(Signed).popLastNVariables(N); 79 } 80 }; 81 82 /// Struct to express a pre-condition of the form %Op0 Pred %Op1. 83 struct PreconditionTy { 84 CmpInst::Predicate Pred; 85 Value *Op0; 86 Value *Op1; 87 88 PreconditionTy(CmpInst::Predicate Pred, Value *Op0, Value *Op1) 89 : Pred(Pred), Op0(Op0), Op1(Op1) {} 90 }; 91 92 struct ConstraintTy { 93 SmallVector<int64_t, 8> Coefficients; 94 SmallVector<PreconditionTy, 2> Preconditions; 95 96 bool IsSigned = false; 97 bool IsEq = false; 98 99 ConstraintTy() = default; 100 101 ConstraintTy(SmallVector<int64_t, 8> Coefficients, bool IsSigned) 102 : Coefficients(Coefficients), IsSigned(IsSigned) {} 103 104 unsigned size() const { return Coefficients.size(); } 105 106 unsigned empty() const { return Coefficients.empty(); } 107 108 /// Returns true if any constraint has a non-zero coefficient for any of the 109 /// newly added indices. Zero coefficients for new indices are removed. If it 110 /// returns true, no new variable need to be added to the system. 111 bool needsNewIndices(const DenseMap<Value *, unsigned> &NewIndices) { 112 for (unsigned I = 0; I < NewIndices.size(); ++I) { 113 int64_t Last = Coefficients.pop_back_val(); 114 if (Last != 0) 115 return true; 116 } 117 return false; 118 } 119 120 /// Returns true if all preconditions for this list of constraints are 121 /// satisfied given \p CS and the corresponding \p Value2Index mapping. 122 bool isValid(const ConstraintInfo &Info) const; 123 124 /// Returns true if there is exactly one constraint in the list and isValid is 125 /// also true. 126 bool isValidSingle(const ConstraintInfo &Info) const { 127 if (size() != 1) 128 return false; 129 return isValid(Info); 130 } 131 }; 132 133 } // namespace 134 135 // Decomposes \p V into a vector of pairs of the form { c, X } where c * X. The 136 // sum of the pairs equals \p V. The first pair is the constant-factor and X 137 // must be nullptr. If the expression cannot be decomposed, returns an empty 138 // vector. 139 static SmallVector<std::pair<int64_t, Value *>, 4> 140 decompose(Value *V, SmallVector<PreconditionTy, 4> &Preconditions, 141 bool IsSigned) { 142 143 // Decompose \p V used with a signed predicate. 144 if (IsSigned) { 145 if (auto *CI = dyn_cast<ConstantInt>(V)) { 146 const APInt &Val = CI->getValue(); 147 if (Val.sle(MinSignedConstraintValue) || Val.sge(MaxConstraintValue)) 148 return {}; 149 return {{CI->getSExtValue(), nullptr}}; 150 } 151 152 return {{0, nullptr}, {1, V}}; 153 } 154 155 if (auto *CI = dyn_cast<ConstantInt>(V)) { 156 if (CI->uge(MaxConstraintValue)) 157 return {}; 158 return {{CI->getZExtValue(), nullptr}}; 159 } 160 auto *GEP = dyn_cast<GetElementPtrInst>(V); 161 if (GEP && GEP->getNumOperands() == 2 && GEP->isInBounds()) { 162 Value *Op0, *Op1; 163 ConstantInt *CI; 164 165 // If the index is zero-extended, it is guaranteed to be positive. 166 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 167 m_ZExt(m_Value(Op0)))) { 168 if (match(Op0, m_NUWShl(m_Value(Op1), m_ConstantInt(CI)))) 169 return {{0, nullptr}, 170 {1, GEP->getPointerOperand()}, 171 {std::pow(int64_t(2), CI->getSExtValue()), Op1}}; 172 if (match(Op0, m_NSWAdd(m_Value(Op1), m_ConstantInt(CI)))) 173 return {{CI->getSExtValue(), nullptr}, 174 {1, GEP->getPointerOperand()}, 175 {1, Op1}}; 176 return {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 177 } 178 179 if (match(GEP->getOperand(GEP->getNumOperands() - 1), m_ConstantInt(CI)) && 180 !CI->isNegative()) 181 return {{CI->getSExtValue(), nullptr}, {1, GEP->getPointerOperand()}}; 182 183 SmallVector<std::pair<int64_t, Value *>, 4> Result; 184 if (match(GEP->getOperand(GEP->getNumOperands() - 1), 185 m_NUWShl(m_Value(Op0), m_ConstantInt(CI)))) 186 Result = {{0, nullptr}, 187 {1, GEP->getPointerOperand()}, 188 {std::pow(int64_t(2), CI->getSExtValue()), Op0}}; 189 else if (match(GEP->getOperand(GEP->getNumOperands() - 1), 190 m_NSWAdd(m_Value(Op0), m_ConstantInt(CI)))) 191 Result = {{CI->getSExtValue(), nullptr}, 192 {1, GEP->getPointerOperand()}, 193 {1, Op0}}; 194 else { 195 Op0 = GEP->getOperand(GEP->getNumOperands() - 1); 196 Result = {{0, nullptr}, {1, GEP->getPointerOperand()}, {1, Op0}}; 197 } 198 // If Op0 is signed non-negative, the GEP is increasing monotonically and 199 // can be de-composed. 200 Preconditions.emplace_back(CmpInst::ICMP_SGE, Op0, 201 ConstantInt::get(Op0->getType(), 0)); 202 return Result; 203 } 204 205 Value *Op0; 206 if (match(V, m_ZExt(m_Value(Op0)))) 207 V = Op0; 208 209 Value *Op1; 210 ConstantInt *CI; 211 if (match(V, m_NUWAdd(m_Value(Op0), m_ConstantInt(CI))) && 212 !CI->uge(MaxConstraintValue)) 213 return {{CI->getZExtValue(), nullptr}, {1, Op0}}; 214 if (match(V, m_Add(m_Value(Op0), m_ConstantInt(CI))) && CI->isNegative()) { 215 Preconditions.emplace_back( 216 CmpInst::ICMP_UGE, Op0, 217 ConstantInt::get(Op0->getType(), CI->getSExtValue() * -1)); 218 return {{CI->getSExtValue(), nullptr}, {1, Op0}}; 219 } 220 if (match(V, m_NUWAdd(m_Value(Op0), m_Value(Op1)))) 221 return {{0, nullptr}, {1, Op0}, {1, Op1}}; 222 223 if (match(V, m_NUWSub(m_Value(Op0), m_ConstantInt(CI)))) 224 return {{-1 * CI->getSExtValue(), nullptr}, {1, Op0}}; 225 if (match(V, m_NUWSub(m_Value(Op0), m_Value(Op1)))) 226 return {{0, nullptr}, {1, Op0}, {-1, Op1}}; 227 228 return {{0, nullptr}, {1, V}}; 229 } 230 231 /// Turn a condition \p CmpI into a vector of constraints, using indices from \p 232 /// Value2Index. Additional indices for newly discovered values are added to \p 233 /// NewIndices. 234 static ConstraintTy 235 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 236 const DenseMap<Value *, unsigned> &Value2Index, 237 DenseMap<Value *, unsigned> &NewIndices) { 238 bool IsEq = false; 239 // Try to convert Pred to one of ULE/SLT/SLE/SLT. 240 switch (Pred) { 241 case CmpInst::ICMP_UGT: 242 case CmpInst::ICMP_UGE: 243 case CmpInst::ICMP_SGT: 244 case CmpInst::ICMP_SGE: { 245 Pred = CmpInst::getSwappedPredicate(Pred); 246 std::swap(Op0, Op1); 247 break; 248 } 249 case CmpInst::ICMP_EQ: 250 if (match(Op1, m_Zero())) { 251 Pred = CmpInst::ICMP_ULE; 252 } else { 253 IsEq = true; 254 Pred = CmpInst::ICMP_ULE; 255 } 256 break; 257 case CmpInst::ICMP_NE: 258 if (!match(Op1, m_Zero())) 259 return {}; 260 Pred = CmpInst::getSwappedPredicate(CmpInst::ICMP_UGT); 261 std::swap(Op0, Op1); 262 break; 263 default: 264 break; 265 } 266 267 // Only ULE and ULT predicates are supported at the moment. 268 if (Pred != CmpInst::ICMP_ULE && Pred != CmpInst::ICMP_ULT && 269 Pred != CmpInst::ICMP_SLE && Pred != CmpInst::ICMP_SLT) 270 return {}; 271 272 SmallVector<PreconditionTy, 4> Preconditions; 273 bool IsSigned = CmpInst::isSigned(Pred); 274 auto ADec = decompose(Op0->stripPointerCastsSameRepresentation(), 275 Preconditions, IsSigned); 276 auto BDec = decompose(Op1->stripPointerCastsSameRepresentation(), 277 Preconditions, IsSigned); 278 // Skip if decomposing either of the values failed. 279 if (ADec.empty() || BDec.empty()) 280 return {}; 281 282 // Skip trivial constraints without any variables. 283 if (ADec.size() == 1 && BDec.size() == 1) 284 return {}; 285 286 int64_t Offset1 = ADec[0].first; 287 int64_t Offset2 = BDec[0].first; 288 Offset1 *= -1; 289 290 // Create iterator ranges that skip the constant-factor. 291 auto VariablesA = llvm::drop_begin(ADec); 292 auto VariablesB = llvm::drop_begin(BDec); 293 294 // First try to look up \p V in Value2Index and NewIndices. Otherwise add a 295 // new entry to NewIndices. 296 auto GetOrAddIndex = [&Value2Index, &NewIndices](Value *V) -> unsigned { 297 auto V2I = Value2Index.find(V); 298 if (V2I != Value2Index.end()) 299 return V2I->second; 300 auto Insert = 301 NewIndices.insert({V, Value2Index.size() + NewIndices.size() + 1}); 302 return Insert.first->second; 303 }; 304 305 // Make sure all variables have entries in Value2Index or NewIndices. 306 for (const auto &KV : 307 concat<std::pair<int64_t, Value *>>(VariablesA, VariablesB)) 308 GetOrAddIndex(KV.second); 309 310 // Build result constraint, by first adding all coefficients from A and then 311 // subtracting all coefficients from B. 312 ConstraintTy Res( 313 SmallVector<int64_t, 8>(Value2Index.size() + NewIndices.size() + 1, 0), 314 IsSigned); 315 Res.IsEq = IsEq; 316 auto &R = Res.Coefficients; 317 for (const auto &KV : VariablesA) 318 R[GetOrAddIndex(KV.second)] += KV.first; 319 320 for (const auto &KV : VariablesB) 321 R[GetOrAddIndex(KV.second)] -= KV.first; 322 323 R[0] = Offset1 + Offset2 + 324 (Pred == (IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT) ? -1 : 0); 325 Res.Preconditions = std::move(Preconditions); 326 return Res; 327 } 328 329 static ConstraintTy getConstraint(CmpInst *Cmp, ConstraintInfo &Info, 330 DenseMap<Value *, unsigned> &NewIndices) { 331 return getConstraint( 332 Cmp->getPredicate(), Cmp->getOperand(0), Cmp->getOperand(1), 333 Info.getValue2Index(CmpInst::isSigned(Cmp->getPredicate())), NewIndices); 334 } 335 336 bool ConstraintTy::isValid(const ConstraintInfo &Info) const { 337 return Coefficients.size() > 0 && 338 all_of(Preconditions, [&Info](const PreconditionTy &C) { 339 DenseMap<Value *, unsigned> NewIndices; 340 auto R = getConstraint( 341 C.Pred, C.Op0, C.Op1, 342 Info.getValue2Index(CmpInst::isSigned(C.Pred)), NewIndices); 343 // TODO: properly check NewIndices. 344 return NewIndices.empty() && R.Preconditions.empty() && !R.IsEq && 345 R.size() >= 2 && 346 Info.getCS(CmpInst::isSigned(C.Pred)) 347 .isConditionImplied(R.Coefficients); 348 }); 349 } 350 351 namespace { 352 /// Represents either a condition that holds on entry to a block or a basic 353 /// block, with their respective Dominator DFS in and out numbers. 354 struct ConstraintOrBlock { 355 unsigned NumIn; 356 unsigned NumOut; 357 bool IsBlock; 358 bool Not; 359 union { 360 BasicBlock *BB; 361 CmpInst *Condition; 362 }; 363 364 ConstraintOrBlock(DomTreeNode *DTN) 365 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 366 BB(DTN->getBlock()) {} 367 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 368 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 369 Not(Not), Condition(Condition) {} 370 }; 371 372 struct StackEntry { 373 unsigned NumIn; 374 unsigned NumOut; 375 Instruction *Condition; 376 bool IsNot; 377 bool IsSigned = false; 378 /// Variables that can be removed from the system once the stack entry gets 379 /// removed. 380 SmallVector<Value *, 2> ValuesToRelease; 381 382 StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot, 383 bool IsSigned, SmallVector<Value *, 2> ValuesToRelease) 384 : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot), 385 IsSigned(IsSigned), ValuesToRelease(ValuesToRelease) {} 386 }; 387 } // namespace 388 389 #ifndef NDEBUG 390 static void dumpWithNames(ConstraintTy &C, 391 DenseMap<Value *, unsigned> &Value2Index) { 392 SmallVector<std::string> Names(Value2Index.size(), ""); 393 for (auto &KV : Value2Index) { 394 Names[KV.second - 1] = std::string("%") + KV.first->getName().str(); 395 } 396 ConstraintSystem CS; 397 CS.addVariableRowFill(C.Coefficients); 398 CS.dump(Names); 399 } 400 #endif 401 402 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 403 bool Changed = false; 404 DT.updateDFSNumbers(); 405 406 ConstraintInfo Info; 407 408 SmallVector<ConstraintOrBlock, 64> WorkList; 409 410 // First, collect conditions implied by branches and blocks with their 411 // Dominator DFS in and out numbers. 412 for (BasicBlock &BB : F) { 413 if (!DT.getNode(&BB)) 414 continue; 415 WorkList.emplace_back(DT.getNode(&BB)); 416 417 // Returns true if we can add a known condition from BB to its successor 418 // block Succ. Each predecessor of Succ can either be BB or be dominated by 419 // Succ (e.g. the case when adding a condition from a pre-header to a loop 420 // header). 421 auto CanAdd = [&BB, &DT](BasicBlock *Succ) { 422 return any_of(successors(&BB), 423 [Succ](const BasicBlock *S) { return S != Succ; }) && 424 all_of(predecessors(Succ), [&BB, &DT, Succ](BasicBlock *Pred) { 425 return Pred == &BB || DT.dominates(Succ, Pred); 426 }); 427 }; 428 429 // True as long as long as the current instruction is guaranteed to execute. 430 bool GuaranteedToExecute = true; 431 // Scan BB for assume calls. 432 // TODO: also use this scan to queue conditions to simplify, so we can 433 // interleave facts from assumes and conditions to simplify in a single 434 // basic block. And to skip another traversal of each basic block when 435 // simplifying. 436 for (Instruction &I : BB) { 437 Value *Cond; 438 // For now, just handle assumes with a single compare as condition. 439 if (match(&I, m_Intrinsic<Intrinsic::assume>(m_Value(Cond))) && 440 isa<ICmpInst>(Cond)) { 441 if (GuaranteedToExecute) { 442 // The assume is guaranteed to execute when BB is entered, hence Cond 443 // holds on entry to BB. 444 WorkList.emplace_back(DT.getNode(&BB), cast<ICmpInst>(Cond), false); 445 } else { 446 // Otherwise the condition only holds in the successors. 447 for (BasicBlock *Succ : successors(&BB)) { 448 if (!CanAdd(Succ)) 449 continue; 450 WorkList.emplace_back(DT.getNode(Succ), cast<ICmpInst>(Cond), 451 false); 452 } 453 } 454 } 455 GuaranteedToExecute &= isGuaranteedToTransferExecutionToSuccessor(&I); 456 } 457 458 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 459 if (!Br || !Br->isConditional()) 460 continue; 461 462 // If the condition is an OR of 2 compares and the false successor only has 463 // the current block as predecessor, queue both negated conditions for the 464 // false successor. 465 Value *Op0, *Op1; 466 if (match(Br->getCondition(), m_LogicalOr(m_Value(Op0), m_Value(Op1))) && 467 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 468 BasicBlock *FalseSuccessor = Br->getSuccessor(1); 469 if (CanAdd(FalseSuccessor)) { 470 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op0), 471 true); 472 WorkList.emplace_back(DT.getNode(FalseSuccessor), cast<ICmpInst>(Op1), 473 true); 474 } 475 continue; 476 } 477 478 // If the condition is an AND of 2 compares and the true successor only has 479 // the current block as predecessor, queue both conditions for the true 480 // successor. 481 if (match(Br->getCondition(), m_LogicalAnd(m_Value(Op0), m_Value(Op1))) && 482 isa<ICmpInst>(Op0) && isa<ICmpInst>(Op1)) { 483 BasicBlock *TrueSuccessor = Br->getSuccessor(0); 484 if (CanAdd(TrueSuccessor)) { 485 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op0), 486 false); 487 WorkList.emplace_back(DT.getNode(TrueSuccessor), cast<ICmpInst>(Op1), 488 false); 489 } 490 continue; 491 } 492 493 auto *CmpI = dyn_cast<ICmpInst>(Br->getCondition()); 494 if (!CmpI) 495 continue; 496 if (CanAdd(Br->getSuccessor(0))) 497 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 498 if (CanAdd(Br->getSuccessor(1))) 499 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 500 } 501 502 // Next, sort worklist by dominance, so that dominating blocks and conditions 503 // come before blocks and conditions dominated by them. If a block and a 504 // condition have the same numbers, the condition comes before the block, as 505 // it holds on entry to the block. 506 sort(WorkList, [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 507 return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock); 508 }); 509 510 // Finally, process ordered worklist and eliminate implied conditions. 511 SmallVector<StackEntry, 16> DFSInStack; 512 for (ConstraintOrBlock &CB : WorkList) { 513 // First, pop entries from the stack that are out-of-scope for CB. Remove 514 // the corresponding entry from the constraint system. 515 while (!DFSInStack.empty()) { 516 auto &E = DFSInStack.back(); 517 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 518 << "\n"); 519 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 520 assert(E.NumIn <= CB.NumIn); 521 if (CB.NumOut <= E.NumOut) 522 break; 523 LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot 524 << "\n"); 525 Info.popLastConstraint(E.IsSigned); 526 // Remove variables in the system that went out of scope. 527 auto &Mapping = Info.getValue2Index(E.IsSigned); 528 for (Value *V : E.ValuesToRelease) 529 Mapping.erase(V); 530 Info.popLastNVariables(E.IsSigned, E.ValuesToRelease.size()); 531 DFSInStack.pop_back(); 532 } 533 534 LLVM_DEBUG({ 535 dbgs() << "Processing "; 536 if (CB.IsBlock) 537 dbgs() << *CB.BB; 538 else 539 dbgs() << *CB.Condition; 540 dbgs() << "\n"; 541 }); 542 543 // For a block, check if any CmpInsts become known based on the current set 544 // of constraints. 545 if (CB.IsBlock) { 546 for (Instruction &I : *CB.BB) { 547 auto *Cmp = dyn_cast<ICmpInst>(&I); 548 if (!Cmp) 549 continue; 550 551 DenseMap<Value *, unsigned> NewIndices; 552 auto R = getConstraint(Cmp, Info, NewIndices); 553 if (R.IsEq || R.size() < 2 || R.needsNewIndices(NewIndices) || 554 !R.isValid(Info)) 555 continue; 556 557 auto &CSToUse = Info.getCS(R.IsSigned); 558 if (CSToUse.isConditionImplied(R.Coefficients)) { 559 if (!DebugCounter::shouldExecute(EliminatedCounter)) 560 continue; 561 562 LLVM_DEBUG(dbgs() << "Condition " << *Cmp 563 << " implied by dominating constraints\n"); 564 LLVM_DEBUG({ 565 for (auto &E : reverse(DFSInStack)) 566 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 567 }); 568 Cmp->replaceUsesWithIf( 569 ConstantInt::getTrue(F.getParent()->getContext()), [](Use &U) { 570 // Conditions in an assume trivially simplify to true. Skip uses 571 // in assume calls to not destroy the available information. 572 auto *II = dyn_cast<IntrinsicInst>(U.getUser()); 573 return !II || II->getIntrinsicID() != Intrinsic::assume; 574 }); 575 NumCondsRemoved++; 576 Changed = true; 577 } 578 if (CSToUse.isConditionImplied( 579 ConstraintSystem::negate(R.Coefficients))) { 580 if (!DebugCounter::shouldExecute(EliminatedCounter)) 581 continue; 582 583 LLVM_DEBUG(dbgs() << "Condition !" << *Cmp 584 << " implied by dominating constraints\n"); 585 LLVM_DEBUG({ 586 for (auto &E : reverse(DFSInStack)) 587 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 588 }); 589 Cmp->replaceAllUsesWith( 590 ConstantInt::getFalse(F.getParent()->getContext())); 591 NumCondsRemoved++; 592 Changed = true; 593 } 594 } 595 continue; 596 } 597 598 // Set up a function to restore the predicate at the end of the scope if it 599 // has been negated. Negate the predicate in-place, if required. 600 auto *CI = dyn_cast<ICmpInst>(CB.Condition); 601 auto PredicateRestorer = make_scope_exit([CI, &CB]() { 602 if (CB.Not && CI) 603 CI->setPredicate(CI->getInversePredicate()); 604 }); 605 if (CB.Not) { 606 if (CI) { 607 CI->setPredicate(CI->getInversePredicate()); 608 } else { 609 LLVM_DEBUG(dbgs() << "Can only negate compares so far.\n"); 610 continue; 611 } 612 } 613 614 // Otherwise, add the condition to the system and stack, if we can transform 615 // it into a constraint. 616 DenseMap<Value *, unsigned> NewIndices; 617 auto R = getConstraint(CB.Condition, Info, NewIndices); 618 if (!R.isValid(Info)) 619 continue; 620 621 LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n"); 622 bool Added = false; 623 assert(CmpInst::isSigned(CB.Condition->getPredicate()) == R.IsSigned && 624 "condition and constraint signs must match"); 625 auto &CSToUse = Info.getCS(R.IsSigned); 626 if (R.Coefficients.empty()) 627 continue; 628 629 Added |= CSToUse.addVariableRowFill(R.Coefficients); 630 631 // If R has been added to the system, queue it for removal once it goes 632 // out-of-scope. 633 if (Added) { 634 SmallVector<Value *, 2> ValuesToRelease; 635 for (auto &KV : NewIndices) { 636 Info.getValue2Index(R.IsSigned).insert(KV); 637 ValuesToRelease.push_back(KV.first); 638 } 639 640 LLVM_DEBUG({ 641 dbgs() << " constraint: "; 642 dumpWithNames(R, Info.getValue2Index(R.IsSigned)); 643 }); 644 645 DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not, 646 R.IsSigned, ValuesToRelease); 647 648 if (R.IsEq) { 649 // Also add the inverted constraint for equality constraints. 650 for (auto &Coeff : R.Coefficients) 651 Coeff *= -1; 652 CSToUse.addVariableRowFill(R.Coefficients); 653 654 DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not, 655 R.IsSigned, SmallVector<Value *, 2>()); 656 } 657 } 658 } 659 660 #ifndef NDEBUG 661 unsigned SignedEntries = 662 count_if(DFSInStack, [](const StackEntry &E) { return E.IsSigned; }); 663 assert(Info.getCS(false).size() == DFSInStack.size() - SignedEntries && 664 "updates to CS and DFSInStack are out of sync"); 665 assert(Info.getCS(true).size() == SignedEntries && 666 "updates to CS and DFSInStack are out of sync"); 667 #endif 668 669 return Changed; 670 } 671 672 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 673 FunctionAnalysisManager &AM) { 674 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 675 if (!eliminateConstraints(F, DT)) 676 return PreservedAnalyses::all(); 677 678 PreservedAnalyses PA; 679 PA.preserve<DominatorTreeAnalysis>(); 680 PA.preserveSet<CFGAnalyses>(); 681 return PA; 682 } 683 684 namespace { 685 686 class ConstraintElimination : public FunctionPass { 687 public: 688 static char ID; 689 690 ConstraintElimination() : FunctionPass(ID) { 691 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 692 } 693 694 bool runOnFunction(Function &F) override { 695 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 696 return eliminateConstraints(F, DT); 697 } 698 699 void getAnalysisUsage(AnalysisUsage &AU) const override { 700 AU.setPreservesCFG(); 701 AU.addRequired<DominatorTreeWrapperPass>(); 702 AU.addPreserved<GlobalsAAWrapperPass>(); 703 AU.addPreserved<DominatorTreeWrapperPass>(); 704 } 705 }; 706 707 } // end anonymous namespace 708 709 char ConstraintElimination::ID = 0; 710 711 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 712 "Constraint Elimination", false, false) 713 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 714 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 715 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 716 "Constraint Elimination", false, false) 717 718 FunctionPass *llvm::createConstraintEliminationPass() { 719 return new ConstraintElimination(); 720 } 721