1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Correlated Value Propagation pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/Analysis/GlobalsModRef.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/LazyValueInfo.h" 19 #include "llvm/IR/CFG.h" 20 #include "llvm/IR/Constants.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/Pass.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 using namespace llvm; 29 30 #define DEBUG_TYPE "correlated-value-propagation" 31 32 STATISTIC(NumPhis, "Number of phis propagated"); 33 STATISTIC(NumSelects, "Number of selects propagated"); 34 STATISTIC(NumMemAccess, "Number of memory access targets propagated"); 35 STATISTIC(NumCmps, "Number of comparisons propagated"); 36 STATISTIC(NumReturns, "Number of return values propagated"); 37 STATISTIC(NumDeadCases, "Number of switch cases removed"); 38 STATISTIC(NumSDivs, "Number of sdiv converted to udiv"); 39 40 namespace { 41 class CorrelatedValuePropagation : public FunctionPass { 42 LazyValueInfo *LVI; 43 public: 44 static char ID; 45 CorrelatedValuePropagation(): FunctionPass(ID) { 46 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry()); 47 } 48 49 bool runOnFunction(Function &F) override; 50 51 void getAnalysisUsage(AnalysisUsage &AU) const override { 52 AU.addRequired<LazyValueInfoWrapperPass>(); 53 AU.addPreserved<GlobalsAAWrapperPass>(); 54 } 55 }; 56 } 57 58 char CorrelatedValuePropagation::ID = 0; 59 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation", 60 "Value Propagation", false, false) 61 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass) 62 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation", 63 "Value Propagation", false, false) 64 65 // Public interface to the Value Propagation pass 66 Pass *llvm::createCorrelatedValuePropagationPass() { 67 return new CorrelatedValuePropagation(); 68 } 69 70 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) { 71 if (S->getType()->isVectorTy()) return false; 72 if (isa<Constant>(S->getOperand(0))) return false; 73 74 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S); 75 if (!C) return false; 76 77 ConstantInt *CI = dyn_cast<ConstantInt>(C); 78 if (!CI) return false; 79 80 Value *ReplaceWith = S->getOperand(1); 81 Value *Other = S->getOperand(2); 82 if (!CI->isOne()) std::swap(ReplaceWith, Other); 83 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType()); 84 85 S->replaceAllUsesWith(ReplaceWith); 86 S->eraseFromParent(); 87 88 ++NumSelects; 89 90 return true; 91 } 92 93 static bool processPHI(PHINode *P, LazyValueInfo *LVI) { 94 bool Changed = false; 95 96 BasicBlock *BB = P->getParent(); 97 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) { 98 Value *Incoming = P->getIncomingValue(i); 99 if (isa<Constant>(Incoming)) continue; 100 101 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P); 102 103 // Look if the incoming value is a select with a scalar condition for which 104 // LVI can tells us the value. In that case replace the incoming value with 105 // the appropriate value of the select. This often allows us to remove the 106 // select later. 107 if (!V) { 108 SelectInst *SI = dyn_cast<SelectInst>(Incoming); 109 if (!SI) continue; 110 111 Value *Condition = SI->getCondition(); 112 if (!Condition->getType()->isVectorTy()) { 113 if (Constant *C = LVI->getConstantOnEdge( 114 Condition, P->getIncomingBlock(i), BB, P)) { 115 if (C->isOneValue()) { 116 V = SI->getTrueValue(); 117 } else if (C->isZeroValue()) { 118 V = SI->getFalseValue(); 119 } 120 // Once LVI learns to handle vector types, we could also add support 121 // for vector type constants that are not all zeroes or all ones. 122 } 123 } 124 125 // Look if the select has a constant but LVI tells us that the incoming 126 // value can never be that constant. In that case replace the incoming 127 // value with the other value of the select. This often allows us to 128 // remove the select later. 129 if (!V) { 130 Constant *C = dyn_cast<Constant>(SI->getFalseValue()); 131 if (!C) continue; 132 133 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C, 134 P->getIncomingBlock(i), BB, P) != 135 LazyValueInfo::False) 136 continue; 137 V = SI->getTrueValue(); 138 } 139 140 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n'); 141 } 142 143 P->setIncomingValue(i, V); 144 Changed = true; 145 } 146 147 // FIXME: Provide TLI, DT, AT to SimplifyInstruction. 148 const DataLayout &DL = BB->getModule()->getDataLayout(); 149 if (Value *V = SimplifyInstruction(P, DL)) { 150 P->replaceAllUsesWith(V); 151 P->eraseFromParent(); 152 Changed = true; 153 } 154 155 if (Changed) 156 ++NumPhis; 157 158 return Changed; 159 } 160 161 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) { 162 Value *Pointer = nullptr; 163 if (LoadInst *L = dyn_cast<LoadInst>(I)) 164 Pointer = L->getPointerOperand(); 165 else 166 Pointer = cast<StoreInst>(I)->getPointerOperand(); 167 168 if (isa<Constant>(Pointer)) return false; 169 170 Constant *C = LVI->getConstant(Pointer, I->getParent(), I); 171 if (!C) return false; 172 173 ++NumMemAccess; 174 I->replaceUsesOfWith(Pointer, C); 175 return true; 176 } 177 178 /// processCmp - See if LazyValueInfo's ability to exploit edge conditions, 179 /// or range information is sufficient to prove this comparison. Even for 180 /// local conditions, this can sometimes prove conditions instcombine can't by 181 /// exploiting range information. 182 static bool processCmp(CmpInst *C, LazyValueInfo *LVI) { 183 Value *Op0 = C->getOperand(0); 184 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 185 if (!Op1) return false; 186 187 // As a policy choice, we choose not to waste compile time on anything where 188 // the comparison is testing local values. While LVI can sometimes reason 189 // about such cases, it's not its primary purpose. We do make sure to do 190 // the block local query for uses from terminator instructions, but that's 191 // handled in the code for each terminator. 192 auto *I = dyn_cast<Instruction>(Op0); 193 if (I && I->getParent() == C->getParent()) 194 return false; 195 196 LazyValueInfo::Tristate Result = 197 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C); 198 if (Result == LazyValueInfo::Unknown) return false; 199 200 ++NumCmps; 201 if (Result == LazyValueInfo::True) 202 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext())); 203 else 204 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext())); 205 C->eraseFromParent(); 206 207 return true; 208 } 209 210 /// processSwitch - Simplify a switch instruction by removing cases which can 211 /// never fire. If the uselessness of a case could be determined locally then 212 /// constant propagation would already have figured it out. Instead, walk the 213 /// predecessors and statically evaluate cases based on information available 214 /// on that edge. Cases that cannot fire no matter what the incoming edge can 215 /// safely be removed. If a case fires on every incoming edge then the entire 216 /// switch can be removed and replaced with a branch to the case destination. 217 static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) { 218 Value *Cond = SI->getCondition(); 219 BasicBlock *BB = SI->getParent(); 220 221 // If the condition was defined in same block as the switch then LazyValueInfo 222 // currently won't say anything useful about it, though in theory it could. 223 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB) 224 return false; 225 226 // If the switch is unreachable then trying to improve it is a waste of time. 227 pred_iterator PB = pred_begin(BB), PE = pred_end(BB); 228 if (PB == PE) return false; 229 230 // Analyse each switch case in turn. This is done in reverse order so that 231 // removing a case doesn't cause trouble for the iteration. 232 bool Changed = false; 233 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE; 234 ) { 235 ConstantInt *Case = CI.getCaseValue(); 236 237 // Check to see if the switch condition is equal to/not equal to the case 238 // value on every incoming edge, equal/not equal being the same each time. 239 LazyValueInfo::Tristate State = LazyValueInfo::Unknown; 240 for (pred_iterator PI = PB; PI != PE; ++PI) { 241 // Is the switch condition equal to the case value? 242 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ, 243 Cond, Case, *PI, 244 BB, SI); 245 // Give up on this case if nothing is known. 246 if (Value == LazyValueInfo::Unknown) { 247 State = LazyValueInfo::Unknown; 248 break; 249 } 250 251 // If this was the first edge to be visited, record that all other edges 252 // need to give the same result. 253 if (PI == PB) { 254 State = Value; 255 continue; 256 } 257 258 // If this case is known to fire for some edges and known not to fire for 259 // others then there is nothing we can do - give up. 260 if (Value != State) { 261 State = LazyValueInfo::Unknown; 262 break; 263 } 264 } 265 266 if (State == LazyValueInfo::False) { 267 // This case never fires - remove it. 268 CI.getCaseSuccessor()->removePredecessor(BB); 269 SI->removeCase(CI); // Does not invalidate the iterator. 270 271 // The condition can be modified by removePredecessor's PHI simplification 272 // logic. 273 Cond = SI->getCondition(); 274 275 ++NumDeadCases; 276 Changed = true; 277 } else if (State == LazyValueInfo::True) { 278 // This case always fires. Arrange for the switch to be turned into an 279 // unconditional branch by replacing the switch condition with the case 280 // value. 281 SI->setCondition(Case); 282 NumDeadCases += SI->getNumCases(); 283 Changed = true; 284 break; 285 } 286 } 287 288 if (Changed) 289 // If the switch has been simplified to the point where it can be replaced 290 // by a branch then do so now. 291 ConstantFoldTerminator(BB); 292 293 return Changed; 294 } 295 296 /// processCallSite - Infer nonnull attributes for the arguments at the 297 /// specified callsite. 298 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) { 299 SmallVector<unsigned, 4> Indices; 300 unsigned ArgNo = 0; 301 302 for (Value *V : CS.args()) { 303 PointerType *Type = dyn_cast<PointerType>(V->getType()); 304 // Try to mark pointer typed parameters as non-null. We skip the 305 // relatively expensive analysis for constants which are obviously either 306 // null or non-null to start with. 307 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) && 308 !isa<Constant>(V) && 309 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V, 310 ConstantPointerNull::get(Type), 311 CS.getInstruction()) == LazyValueInfo::False) 312 Indices.push_back(ArgNo + 1); 313 ArgNo++; 314 } 315 316 assert(ArgNo == CS.arg_size() && "sanity check"); 317 318 if (Indices.empty()) 319 return false; 320 321 AttributeSet AS = CS.getAttributes(); 322 LLVMContext &Ctx = CS.getInstruction()->getContext(); 323 AS = AS.addAttribute(Ctx, Indices, Attribute::get(Ctx, Attribute::NonNull)); 324 CS.setAttributes(AS); 325 326 return true; 327 } 328 329 /// See if LazyValueInfo's ability to exploit edge conditions, or range 330 /// information is sufficient to prove the both operands of this SDiv are 331 /// positive. If this is the case, replace the SDiv with a UDiv. Even for local 332 /// conditions, this can sometimes prove conditions instcombine can't by 333 /// exploiting range information. 334 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) { 335 if (SDI->getType()->isVectorTy()) 336 return false; 337 338 for (Value *O : SDI->operands()) { 339 // As a policy choice, we choose not to waste compile time on anything where 340 // the operands are local defs. While LVI can sometimes reason about such 341 // cases, it's not its primary purpose. 342 auto *I = dyn_cast<Instruction>(O); 343 if (I && I->getParent() == SDI->getParent()) 344 return false; 345 } 346 347 Constant *Zero = ConstantInt::get(SDI->getType(), 0); 348 for (Value *O : SDI->operands()) { 349 LazyValueInfo::Tristate Result = 350 LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI); 351 if (Result != LazyValueInfo::True) 352 return false; 353 } 354 355 ++NumSDivs; 356 auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1), 357 SDI->getName(), SDI); 358 BO->setIsExact(SDI->isExact()); 359 SDI->replaceAllUsesWith(BO); 360 SDI->eraseFromParent(); 361 362 return true; 363 } 364 365 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) { 366 if (Constant *C = LVI->getConstant(V, At->getParent(), At)) 367 return C; 368 369 // TODO: The following really should be sunk inside LVI's core algorithm, or 370 // at least the outer shims around such. 371 auto *C = dyn_cast<CmpInst>(V); 372 if (!C) return nullptr; 373 374 Value *Op0 = C->getOperand(0); 375 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1)); 376 if (!Op1) return nullptr; 377 378 LazyValueInfo::Tristate Result = 379 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At); 380 if (Result == LazyValueInfo::Unknown) 381 return nullptr; 382 383 return (Result == LazyValueInfo::True) ? 384 ConstantInt::getTrue(C->getContext()) : 385 ConstantInt::getFalse(C->getContext()); 386 } 387 388 bool CorrelatedValuePropagation::runOnFunction(Function &F) { 389 if (skipFunction(F)) 390 return false; 391 392 LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI(); 393 394 bool FnChanged = false; 395 396 for (BasicBlock &BB : F) { 397 bool BBChanged = false; 398 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { 399 Instruction *II = &*BI++; 400 switch (II->getOpcode()) { 401 case Instruction::Select: 402 BBChanged |= processSelect(cast<SelectInst>(II), LVI); 403 break; 404 case Instruction::PHI: 405 BBChanged |= processPHI(cast<PHINode>(II), LVI); 406 break; 407 case Instruction::ICmp: 408 case Instruction::FCmp: 409 BBChanged |= processCmp(cast<CmpInst>(II), LVI); 410 break; 411 case Instruction::Load: 412 case Instruction::Store: 413 BBChanged |= processMemAccess(II, LVI); 414 break; 415 case Instruction::Call: 416 case Instruction::Invoke: 417 BBChanged |= processCallSite(CallSite(II), LVI); 418 break; 419 case Instruction::SDiv: 420 BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI); 421 break; 422 } 423 } 424 425 Instruction *Term = BB.getTerminator(); 426 switch (Term->getOpcode()) { 427 case Instruction::Switch: 428 BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI); 429 break; 430 case Instruction::Ret: { 431 auto *RI = cast<ReturnInst>(Term); 432 // Try to determine the return value if we can. This is mainly here to 433 // simplify the writing of unit tests, but also helps to enable IPO by 434 // constant folding the return values of callees. 435 auto *RetVal = RI->getReturnValue(); 436 if (!RetVal) break; // handle "ret void" 437 if (isa<Constant>(RetVal)) break; // nothing to do 438 if (auto *C = getConstantAt(RetVal, RI, LVI)) { 439 ++NumReturns; 440 RI->replaceUsesOfWith(RetVal, C); 441 BBChanged = true; 442 } 443 } 444 }; 445 446 FnChanged |= BBChanged; 447 } 448 449 return FnChanged; 450 } 451