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/SmallVector.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/ConstraintSystem.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/IR/DataLayout.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/PatternMatch.h" 24 #include "llvm/InitializePasses.h" 25 #include "llvm/Pass.h" 26 #include "llvm/Support/Debug.h" 27 #include "llvm/Support/DebugCounter.h" 28 #include "llvm/Transforms/Scalar.h" 29 30 using namespace llvm; 31 using namespace PatternMatch; 32 33 #define DEBUG_TYPE "constraint-elimination" 34 35 STATISTIC(NumCondsRemoved, "Number of instructions removed"); 36 DEBUG_COUNTER(EliminatedCounter, "conds-eliminated", 37 "Controls which conditions are eliminated"); 38 39 static int64_t MaxConstraintValue = std::numeric_limits<int64_t>::max(); 40 41 static Optional<std::pair<int64_t, Value *>> decompose(Value *V) { 42 if (auto *CI = dyn_cast<ConstantInt>(V)) { 43 if (CI->isNegative() || CI->uge(MaxConstraintValue)) 44 return {}; 45 return {{CI->getSExtValue(), nullptr}}; 46 } 47 auto *GEP = dyn_cast<GetElementPtrInst>(V); 48 if (GEP && GEP->getNumOperands() == 2 && 49 isa<ConstantInt>(GEP->getOperand(GEP->getNumOperands() - 1))) { 50 return {{cast<ConstantInt>(GEP->getOperand(GEP->getNumOperands() - 1)) 51 ->getSExtValue(), 52 GEP->getPointerOperand()}}; 53 } 54 return {{0, V}}; 55 } 56 57 /// Turn a condition \p CmpI into a constraint vector, using indices from \p 58 /// Value2Index. If \p ShouldAdd is true, new indices are added for values not 59 /// yet in \p Value2Index. 60 static SmallVector<int64_t, 8> 61 getConstraint(CmpInst::Predicate Pred, Value *Op0, Value *Op1, 62 DenseMap<Value *, unsigned> &Value2Index, bool ShouldAdd) { 63 Value *A, *B; 64 65 int64_t Offset1 = 0; 66 int64_t Offset2 = 0; 67 68 auto TryToGetIndex = [ShouldAdd, 69 &Value2Index](Value *V) -> Optional<unsigned> { 70 if (ShouldAdd) { 71 Value2Index.insert({V, Value2Index.size() + 1}); 72 return Value2Index[V]; 73 } 74 auto I = Value2Index.find(V); 75 if (I == Value2Index.end()) 76 return None; 77 return I->second; 78 }; 79 80 if (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE) 81 return getConstraint(CmpInst::getSwappedPredicate(Pred), Op1, Op0, 82 Value2Index, ShouldAdd); 83 84 if (Pred == CmpInst::ICMP_ULE || Pred == CmpInst::ICMP_ULT) { 85 auto ADec = decompose(Op0); 86 auto BDec = decompose(Op1); 87 if (!ADec || !BDec) 88 return {}; 89 std::tie(Offset1, A) = *ADec; 90 std::tie(Offset2, B) = *BDec; 91 Offset1 *= -1; 92 93 if (!A && !B) 94 return {}; 95 96 auto AIdx = A ? TryToGetIndex(A) : None; 97 auto BIdx = B ? TryToGetIndex(B) : None; 98 if ((A && !AIdx) || (B && !BIdx)) 99 return {}; 100 101 SmallVector<int64_t, 8> R(Value2Index.size() + 1, 0); 102 if (AIdx) 103 R[*AIdx] = 1; 104 if (BIdx) 105 R[*BIdx] = -1; 106 R[0] = Offset1 + Offset2 + (Pred == CmpInst::ICMP_ULT ? -1 : 0); 107 return R; 108 } 109 110 return {}; 111 } 112 113 static SmallVector<int64_t, 8> 114 getConstraint(CmpInst *Cmp, DenseMap<Value *, unsigned> &Value2Index, 115 bool ShouldAdd) { 116 return getConstraint(Cmp->getPredicate(), Cmp->getOperand(0), 117 Cmp->getOperand(1), Value2Index, ShouldAdd); 118 } 119 120 namespace { 121 /// Represents either a condition that holds on entry to a block or a basic 122 /// block, with their respective Dominator DFS in and out numbers. 123 struct ConstraintOrBlock { 124 unsigned NumIn; 125 unsigned NumOut; 126 bool IsBlock; 127 bool Not; 128 union { 129 BasicBlock *BB; 130 CmpInst *Condition; 131 }; 132 133 ConstraintOrBlock(DomTreeNode *DTN) 134 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(true), 135 BB(DTN->getBlock()) {} 136 ConstraintOrBlock(DomTreeNode *DTN, CmpInst *Condition, bool Not) 137 : NumIn(DTN->getDFSNumIn()), NumOut(DTN->getDFSNumOut()), IsBlock(false), 138 Not(Not), Condition(Condition) {} 139 }; 140 141 struct StackEntry { 142 unsigned NumIn; 143 unsigned NumOut; 144 CmpInst *Condition; 145 bool IsNot; 146 147 StackEntry(unsigned NumIn, unsigned NumOut, CmpInst *Condition, bool IsNot) 148 : NumIn(NumIn), NumOut(NumOut), Condition(Condition), IsNot(IsNot) {} 149 }; 150 } // namespace 151 152 static bool eliminateConstraints(Function &F, DominatorTree &DT) { 153 bool Changed = false; 154 DT.updateDFSNumbers(); 155 ConstraintSystem CS; 156 157 SmallVector<ConstraintOrBlock, 64> WorkList; 158 159 // First, collect conditions implied by branches and blocks with their 160 // Dominator DFS in and out numbers. 161 for (BasicBlock &BB : F) { 162 if (!DT.getNode(&BB)) 163 continue; 164 WorkList.emplace_back(DT.getNode(&BB)); 165 166 auto *Br = dyn_cast<BranchInst>(BB.getTerminator()); 167 if (!Br || !Br->isConditional()) 168 continue; 169 auto *CmpI = dyn_cast<CmpInst>(Br->getCondition()); 170 if (!CmpI) 171 continue; 172 if (Br->getSuccessor(0)->getSinglePredecessor()) 173 WorkList.emplace_back(DT.getNode(Br->getSuccessor(0)), CmpI, false); 174 if (Br->getSuccessor(1)->getSinglePredecessor()) 175 WorkList.emplace_back(DT.getNode(Br->getSuccessor(1)), CmpI, true); 176 } 177 178 // Next, sort worklist by dominance, so that dominating blocks and conditions 179 // come before blocks and conditions dominated by them. If a block and a 180 // condition have the same numbers, the condition comes before the block, as 181 // it holds on entry to the block. 182 sort(WorkList.begin(), WorkList.end(), 183 [](const ConstraintOrBlock &A, const ConstraintOrBlock &B) { 184 return std::tie(A.NumIn, A.IsBlock) < std::tie(B.NumIn, B.IsBlock); 185 }); 186 187 // Finally, process ordered worklist and eliminate implied conditions. 188 SmallVector<StackEntry, 16> DFSInStack; 189 DenseMap<Value *, unsigned> Value2Index; 190 for (ConstraintOrBlock &CB : WorkList) { 191 // First, pop entries from the stack that are out-of-scope for CB. Remove 192 // the corresponding entry from the constraint system. 193 while (!DFSInStack.empty()) { 194 auto &E = DFSInStack.back(); 195 LLVM_DEBUG(dbgs() << "Top of stack : " << E.NumIn << " " << E.NumOut 196 << "\n"); 197 LLVM_DEBUG(dbgs() << "CB: " << CB.NumIn << " " << CB.NumOut << "\n"); 198 assert(E.NumIn <= CB.NumIn); 199 if (CB.NumOut <= E.NumOut) 200 break; 201 LLVM_DEBUG(dbgs() << "Removing " << *E.Condition << " " << E.IsNot 202 << "\n"); 203 DFSInStack.pop_back(); 204 CS.popLastConstraint(); 205 } 206 207 LLVM_DEBUG({ 208 dbgs() << "Processing "; 209 if (CB.IsBlock) 210 dbgs() << *CB.BB; 211 else 212 dbgs() << *CB.Condition; 213 dbgs() << "\n"; 214 }); 215 216 // For a block, check if any CmpInsts become known based on the current set 217 // of constraints. 218 if (CB.IsBlock) { 219 for (Instruction &I : *CB.BB) { 220 auto *Cmp = dyn_cast<CmpInst>(&I); 221 if (!Cmp) 222 continue; 223 auto R = getConstraint(Cmp, Value2Index, false); 224 if (R.empty()) 225 continue; 226 if (CS.isConditionImplied(R)) { 227 if (!DebugCounter::shouldExecute(EliminatedCounter)) 228 continue; 229 230 LLVM_DEBUG(dbgs() << "Condition " << *Cmp 231 << " implied by dominating constraints\n"); 232 LLVM_DEBUG({ 233 for (auto &E : reverse(DFSInStack)) 234 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 235 }); 236 Cmp->replaceAllUsesWith( 237 ConstantInt::getTrue(F.getParent()->getContext())); 238 NumCondsRemoved++; 239 Changed = true; 240 } 241 if (CS.isConditionImplied(ConstraintSystem::negate(R))) { 242 if (!DebugCounter::shouldExecute(EliminatedCounter)) 243 continue; 244 245 LLVM_DEBUG(dbgs() << "Condition !" << *Cmp 246 << " implied by dominating constraints\n"); 247 LLVM_DEBUG({ 248 for (auto &E : reverse(DFSInStack)) 249 dbgs() << " C " << *E.Condition << " " << E.IsNot << "\n"; 250 }); 251 Cmp->replaceAllUsesWith( 252 ConstantInt::getFalse(F.getParent()->getContext())); 253 NumCondsRemoved++; 254 Changed = true; 255 } 256 } 257 continue; 258 } 259 260 // Otherwise, add the condition to the system and stack, if we can transform 261 // it into a constraint. 262 auto R = getConstraint(CB.Condition, Value2Index, true); 263 if (R.empty()) 264 continue; 265 266 LLVM_DEBUG(dbgs() << "Adding " << *CB.Condition << " " << CB.Not << "\n"); 267 if (CB.Not) 268 R = ConstraintSystem::negate(R); 269 270 CS.addVariableRowFill(R); 271 DFSInStack.emplace_back(CB.NumIn, CB.NumOut, CB.Condition, CB.Not); 272 } 273 274 return Changed; 275 } 276 277 PreservedAnalyses ConstraintEliminationPass::run(Function &F, 278 FunctionAnalysisManager &AM) { 279 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 280 if (!eliminateConstraints(F, DT)) 281 return PreservedAnalyses::all(); 282 283 PreservedAnalyses PA; 284 PA.preserve<DominatorTreeAnalysis>(); 285 PA.preserve<GlobalsAA>(); 286 PA.preserveSet<CFGAnalyses>(); 287 return PA; 288 } 289 290 namespace { 291 292 class ConstraintElimination : public FunctionPass { 293 public: 294 static char ID; 295 296 ConstraintElimination() : FunctionPass(ID) { 297 initializeConstraintEliminationPass(*PassRegistry::getPassRegistry()); 298 } 299 300 bool runOnFunction(Function &F) override { 301 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 302 return eliminateConstraints(F, DT); 303 } 304 305 void getAnalysisUsage(AnalysisUsage &AU) const override { 306 AU.setPreservesCFG(); 307 AU.addRequired<DominatorTreeWrapperPass>(); 308 AU.addPreserved<GlobalsAAWrapperPass>(); 309 AU.addPreserved<DominatorTreeWrapperPass>(); 310 } 311 }; 312 313 } // end anonymous namespace 314 315 char ConstraintElimination::ID = 0; 316 317 INITIALIZE_PASS_BEGIN(ConstraintElimination, "constraint-elimination", 318 "Constraint Elimination", false, false) 319 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 320 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 321 INITIALIZE_PASS_END(ConstraintElimination, "constraint-elimination", 322 "Constraint Elimination", false, false) 323 324 FunctionPass *llvm::createConstraintEliminationPass() { 325 return new ConstraintElimination(); 326 } 327