]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304460, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Scalar / CorrelatedValuePropagation.cpp
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/CorrelatedValuePropagation.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/AssumptionCache.h"
17 #include "llvm/Analysis/GlobalsModRef.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 using namespace llvm;
32
33 #define DEBUG_TYPE "correlated-value-propagation"
34
35 STATISTIC(NumPhis,      "Number of phis propagated");
36 STATISTIC(NumSelects,   "Number of selects propagated");
37 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
38 STATISTIC(NumCmps,      "Number of comparisons propagated");
39 STATISTIC(NumReturns,   "Number of return values propagated");
40 STATISTIC(NumDeadCases, "Number of switch cases removed");
41 STATISTIC(NumSDivs,     "Number of sdiv converted to udiv");
42 STATISTIC(NumAShrs,     "Number of ashr converted to lshr");
43 STATISTIC(NumSRems,     "Number of srem converted to urem");
44
45 static cl::opt<bool> DontProcessAdds("cvp-dont-process-adds", cl::init(true));
46
47 namespace {
48   class CorrelatedValuePropagation : public FunctionPass {
49   public:
50     static char ID;
51     CorrelatedValuePropagation(): FunctionPass(ID) {
52      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
53     }
54
55     bool runOnFunction(Function &F) override;
56
57     void getAnalysisUsage(AnalysisUsage &AU) const override {
58       AU.addRequired<LazyValueInfoWrapperPass>();
59       AU.addPreserved<GlobalsAAWrapperPass>();
60     }
61   };
62 }
63
64 char CorrelatedValuePropagation::ID = 0;
65 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
66                 "Value Propagation", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
68 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
69                 "Value Propagation", false, false)
70
71 // Public interface to the Value Propagation pass
72 Pass *llvm::createCorrelatedValuePropagationPass() {
73   return new CorrelatedValuePropagation();
74 }
75
76 static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
77   if (S->getType()->isVectorTy()) return false;
78   if (isa<Constant>(S->getOperand(0))) return false;
79
80   Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
81   if (!C) return false;
82
83   ConstantInt *CI = dyn_cast<ConstantInt>(C);
84   if (!CI) return false;
85
86   Value *ReplaceWith = S->getOperand(1);
87   Value *Other = S->getOperand(2);
88   if (!CI->isOne()) std::swap(ReplaceWith, Other);
89   if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
90
91   S->replaceAllUsesWith(ReplaceWith);
92   S->eraseFromParent();
93
94   ++NumSelects;
95
96   return true;
97 }
98
99 static bool processPHI(PHINode *P, LazyValueInfo *LVI,
100                        const SimplifyQuery &SQ) {
101   bool Changed = false;
102
103   BasicBlock *BB = P->getParent();
104   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
105     Value *Incoming = P->getIncomingValue(i);
106     if (isa<Constant>(Incoming)) continue;
107
108     Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
109
110     // Look if the incoming value is a select with a scalar condition for which
111     // LVI can tells us the value. In that case replace the incoming value with
112     // the appropriate value of the select. This often allows us to remove the
113     // select later.
114     if (!V) {
115       SelectInst *SI = dyn_cast<SelectInst>(Incoming);
116       if (!SI) continue;
117
118       Value *Condition = SI->getCondition();
119       if (!Condition->getType()->isVectorTy()) {
120         if (Constant *C = LVI->getConstantOnEdge(
121                 Condition, P->getIncomingBlock(i), BB, P)) {
122           if (C->isOneValue()) {
123             V = SI->getTrueValue();
124           } else if (C->isZeroValue()) {
125             V = SI->getFalseValue();
126           }
127           // Once LVI learns to handle vector types, we could also add support
128           // for vector type constants that are not all zeroes or all ones.
129         }
130       }
131
132       // Look if the select has a constant but LVI tells us that the incoming
133       // value can never be that constant. In that case replace the incoming
134       // value with the other value of the select. This often allows us to
135       // remove the select later.
136       if (!V) {
137         Constant *C = dyn_cast<Constant>(SI->getFalseValue());
138         if (!C) continue;
139
140         if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
141               P->getIncomingBlock(i), BB, P) !=
142             LazyValueInfo::False)
143           continue;
144         V = SI->getTrueValue();
145       }
146
147       DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
148     }
149
150     P->setIncomingValue(i, V);
151     Changed = true;
152   }
153
154   if (Value *V = SimplifyInstruction(P, SQ)) {
155     P->replaceAllUsesWith(V);
156     P->eraseFromParent();
157     Changed = true;
158   }
159
160   if (Changed)
161     ++NumPhis;
162
163   return Changed;
164 }
165
166 static bool processMemAccess(Instruction *I, LazyValueInfo *LVI) {
167   Value *Pointer = nullptr;
168   if (LoadInst *L = dyn_cast<LoadInst>(I))
169     Pointer = L->getPointerOperand();
170   else
171     Pointer = cast<StoreInst>(I)->getPointerOperand();
172
173   if (isa<Constant>(Pointer)) return false;
174
175   Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
176   if (!C) return false;
177
178   ++NumMemAccess;
179   I->replaceUsesOfWith(Pointer, C);
180   return true;
181 }
182
183 /// See if LazyValueInfo's ability to exploit edge conditions or range
184 /// information is sufficient to prove this comparison. Even for local
185 /// conditions, this can sometimes prove conditions instcombine can't by
186 /// exploiting range information.
187 static bool processCmp(CmpInst *C, LazyValueInfo *LVI) {
188   Value *Op0 = C->getOperand(0);
189   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
190   if (!Op1) return false;
191
192   // As a policy choice, we choose not to waste compile time on anything where
193   // the comparison is testing local values.  While LVI can sometimes reason
194   // about such cases, it's not its primary purpose.  We do make sure to do
195   // the block local query for uses from terminator instructions, but that's
196   // handled in the code for each terminator.
197   auto *I = dyn_cast<Instruction>(Op0);
198   if (I && I->getParent() == C->getParent())
199     return false;
200
201   LazyValueInfo::Tristate Result =
202     LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
203   if (Result == LazyValueInfo::Unknown) return false;
204
205   ++NumCmps;
206   if (Result == LazyValueInfo::True)
207     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
208   else
209     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
210   C->eraseFromParent();
211
212   return true;
213 }
214
215 /// Simplify a switch instruction by removing cases which can never fire. If the
216 /// uselessness of a case could be determined locally then constant propagation
217 /// would already have figured it out. Instead, walk the predecessors and
218 /// statically evaluate cases based on information available on that edge. Cases
219 /// that cannot fire no matter what the incoming edge can safely be removed. If
220 /// a case fires on every incoming edge then the entire switch can be removed
221 /// and replaced with a branch to the case destination.
222 static bool processSwitch(SwitchInst *SI, LazyValueInfo *LVI) {
223   Value *Cond = SI->getCondition();
224   BasicBlock *BB = SI->getParent();
225
226   // If the condition was defined in same block as the switch then LazyValueInfo
227   // currently won't say anything useful about it, though in theory it could.
228   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
229     return false;
230
231   // If the switch is unreachable then trying to improve it is a waste of time.
232   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
233   if (PB == PE) return false;
234
235   // Analyse each switch case in turn.  This is done in reverse order so that
236   // removing a case doesn't cause trouble for the iteration.
237   bool Changed = false;
238   for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
239     ConstantInt *Case = CI->getCaseValue();
240
241     // Check to see if the switch condition is equal to/not equal to the case
242     // value on every incoming edge, equal/not equal being the same each time.
243     LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
244     for (pred_iterator PI = PB; PI != PE; ++PI) {
245       // Is the switch condition equal to the case value?
246       LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
247                                                               Cond, Case, *PI,
248                                                               BB, SI);
249       // Give up on this case if nothing is known.
250       if (Value == LazyValueInfo::Unknown) {
251         State = LazyValueInfo::Unknown;
252         break;
253       }
254
255       // If this was the first edge to be visited, record that all other edges
256       // need to give the same result.
257       if (PI == PB) {
258         State = Value;
259         continue;
260       }
261
262       // If this case is known to fire for some edges and known not to fire for
263       // others then there is nothing we can do - give up.
264       if (Value != State) {
265         State = LazyValueInfo::Unknown;
266         break;
267       }
268     }
269
270     if (State == LazyValueInfo::False) {
271       // This case never fires - remove it.
272       CI->getCaseSuccessor()->removePredecessor(BB);
273       CI = SI->removeCase(CI);
274       CE = SI->case_end();
275
276       // The condition can be modified by removePredecessor's PHI simplification
277       // logic.
278       Cond = SI->getCondition();
279
280       ++NumDeadCases;
281       Changed = true;
282       continue;
283     }
284     if (State == LazyValueInfo::True) {
285       // This case always fires.  Arrange for the switch to be turned into an
286       // unconditional branch by replacing the switch condition with the case
287       // value.
288       SI->setCondition(Case);
289       NumDeadCases += SI->getNumCases();
290       Changed = true;
291       break;
292     }
293
294     // Increment the case iterator sense we didn't delete it.
295     ++CI;
296   }
297
298   if (Changed)
299     // If the switch has been simplified to the point where it can be replaced
300     // by a branch then do so now.
301     ConstantFoldTerminator(BB);
302
303   return Changed;
304 }
305
306 /// Infer nonnull attributes for the arguments at the specified callsite.
307 static bool processCallSite(CallSite CS, LazyValueInfo *LVI) {
308   SmallVector<unsigned, 4> ArgNos;
309   unsigned ArgNo = 0;
310
311   for (Value *V : CS.args()) {
312     PointerType *Type = dyn_cast<PointerType>(V->getType());
313     // Try to mark pointer typed parameters as non-null.  We skip the
314     // relatively expensive analysis for constants which are obviously either
315     // null or non-null to start with.
316     if (Type && !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
317         !isa<Constant>(V) && 
318         LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
319                             ConstantPointerNull::get(Type),
320                             CS.getInstruction()) == LazyValueInfo::False)
321       ArgNos.push_back(ArgNo);
322     ArgNo++;
323   }
324
325   assert(ArgNo == CS.arg_size() && "sanity check");
326
327   if (ArgNos.empty())
328     return false;
329
330   AttributeList AS = CS.getAttributes();
331   LLVMContext &Ctx = CS.getInstruction()->getContext();
332   AS = AS.addParamAttribute(Ctx, ArgNos,
333                             Attribute::get(Ctx, Attribute::NonNull));
334   CS.setAttributes(AS);
335
336   return true;
337 }
338
339 // Helper function to rewrite srem and sdiv. As a policy choice, we choose not
340 // to waste compile time on anything where the operands are local defs.  While
341 // LVI can sometimes reason about such cases, it's not its primary purpose.
342 static bool hasLocalDefs(BinaryOperator *SDI) {
343   for (Value *O : SDI->operands()) {
344     auto *I = dyn_cast<Instruction>(O);
345     if (I && I->getParent() == SDI->getParent())
346       return true;
347   }
348   return false;
349 }
350
351 static bool hasPositiveOperands(BinaryOperator *SDI, LazyValueInfo *LVI) {
352   Constant *Zero = ConstantInt::get(SDI->getType(), 0);
353   for (Value *O : SDI->operands()) {
354     auto Result = LVI->getPredicateAt(ICmpInst::ICMP_SGE, O, Zero, SDI);
355     if (Result != LazyValueInfo::True)
356       return false;
357   }
358   return true;
359 }
360
361 static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
362   if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
363       !hasPositiveOperands(SDI, LVI))
364     return false;
365
366   ++NumSRems;
367   auto *BO = BinaryOperator::CreateURem(SDI->getOperand(0), SDI->getOperand(1),
368                                         SDI->getName(), SDI);
369   SDI->replaceAllUsesWith(BO);
370   SDI->eraseFromParent();
371   return true;
372 }
373
374 /// See if LazyValueInfo's ability to exploit edge conditions or range
375 /// information is sufficient to prove the both operands of this SDiv are
376 /// positive.  If this is the case, replace the SDiv with a UDiv. Even for local
377 /// conditions, this can sometimes prove conditions instcombine can't by
378 /// exploiting range information.
379 static bool processSDiv(BinaryOperator *SDI, LazyValueInfo *LVI) {
380   if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI) ||
381       !hasPositiveOperands(SDI, LVI))
382     return false;
383
384   ++NumSDivs;
385   auto *BO = BinaryOperator::CreateUDiv(SDI->getOperand(0), SDI->getOperand(1),
386                                         SDI->getName(), SDI);
387   BO->setIsExact(SDI->isExact());
388   SDI->replaceAllUsesWith(BO);
389   SDI->eraseFromParent();
390
391   return true;
392 }
393
394 static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
395   if (SDI->getType()->isVectorTy() || hasLocalDefs(SDI))
396     return false;
397
398   Constant *Zero = ConstantInt::get(SDI->getType(), 0);
399   if (LVI->getPredicateAt(ICmpInst::ICMP_SGE, SDI->getOperand(0), Zero, SDI) !=
400       LazyValueInfo::True)
401     return false;
402
403   ++NumAShrs;
404   auto *BO = BinaryOperator::CreateLShr(SDI->getOperand(0), SDI->getOperand(1),
405                                         SDI->getName(), SDI);
406   BO->setIsExact(SDI->isExact());
407   SDI->replaceAllUsesWith(BO);
408   SDI->eraseFromParent();
409
410   return true;
411 }
412
413 static bool processAdd(BinaryOperator *AddOp, LazyValueInfo *LVI) {
414   typedef OverflowingBinaryOperator OBO;
415
416   if (DontProcessAdds)
417     return false;
418
419   if (AddOp->getType()->isVectorTy() || hasLocalDefs(AddOp))
420     return false;
421
422   bool NSW = AddOp->hasNoSignedWrap();
423   bool NUW = AddOp->hasNoUnsignedWrap();
424   if (NSW && NUW)
425     return false;
426
427   BasicBlock *BB = AddOp->getParent();
428
429   Value *LHS = AddOp->getOperand(0);
430   Value *RHS = AddOp->getOperand(1);
431
432   ConstantRange LRange = LVI->getConstantRange(LHS, BB, AddOp);
433
434   // Initialize RRange only if we need it. If we know that guaranteed no wrap
435   // range for the given LHS range is empty don't spend time calculating the
436   // range for the RHS.
437   Optional<ConstantRange> RRange;
438   auto LazyRRange = [&] () {
439       if (!RRange)
440         RRange = LVI->getConstantRange(RHS, BB, AddOp);
441       return RRange.getValue();
442   };
443
444   bool Changed = false;
445   if (!NUW) {
446     ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
447         BinaryOperator::Add, LRange, OBO::NoUnsignedWrap);
448     if (!NUWRange.isEmptySet()) {
449       bool NewNUW = NUWRange.contains(LazyRRange());
450       AddOp->setHasNoUnsignedWrap(NewNUW);
451       Changed |= NewNUW;
452     }
453   }
454   if (!NSW) {
455     ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
456         BinaryOperator::Add, LRange, OBO::NoSignedWrap);
457     if (!NSWRange.isEmptySet()) {
458       bool NewNSW = NSWRange.contains(LazyRRange());
459       AddOp->setHasNoSignedWrap(NewNSW);
460       Changed |= NewNSW;
461     }
462   }
463
464   return Changed;
465 }
466
467 static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
468   if (Constant *C = LVI->getConstant(V, At->getParent(), At))
469     return C;
470
471   // TODO: The following really should be sunk inside LVI's core algorithm, or
472   // at least the outer shims around such.
473   auto *C = dyn_cast<CmpInst>(V);
474   if (!C) return nullptr;
475
476   Value *Op0 = C->getOperand(0);
477   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
478   if (!Op1) return nullptr;
479   
480   LazyValueInfo::Tristate Result =
481     LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
482   if (Result == LazyValueInfo::Unknown)
483     return nullptr;
484   
485   return (Result == LazyValueInfo::True) ?
486     ConstantInt::getTrue(C->getContext()) :
487     ConstantInt::getFalse(C->getContext());
488 }
489
490 static bool runImpl(Function &F, LazyValueInfo *LVI, const SimplifyQuery &SQ) {
491   bool FnChanged = false;
492   // Visiting in a pre-order depth-first traversal causes us to simplify early
493   // blocks before querying later blocks (which require us to analyze early
494   // blocks).  Eagerly simplifying shallow blocks means there is strictly less
495   // work to do for deep blocks.  This also means we don't visit unreachable
496   // blocks. 
497   for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
498     bool BBChanged = false;
499     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
500       Instruction *II = &*BI++;
501       switch (II->getOpcode()) {
502       case Instruction::Select:
503         BBChanged |= processSelect(cast<SelectInst>(II), LVI);
504         break;
505       case Instruction::PHI:
506         BBChanged |= processPHI(cast<PHINode>(II), LVI, SQ);
507         break;
508       case Instruction::ICmp:
509       case Instruction::FCmp:
510         BBChanged |= processCmp(cast<CmpInst>(II), LVI);
511         break;
512       case Instruction::Load:
513       case Instruction::Store:
514         BBChanged |= processMemAccess(II, LVI);
515         break;
516       case Instruction::Call:
517       case Instruction::Invoke:
518         BBChanged |= processCallSite(CallSite(II), LVI);
519         break;
520       case Instruction::SRem:
521         BBChanged |= processSRem(cast<BinaryOperator>(II), LVI);
522         break;
523       case Instruction::SDiv:
524         BBChanged |= processSDiv(cast<BinaryOperator>(II), LVI);
525         break;
526       case Instruction::AShr:
527         BBChanged |= processAShr(cast<BinaryOperator>(II), LVI);
528         break;
529       case Instruction::Add:
530         BBChanged |= processAdd(cast<BinaryOperator>(II), LVI);
531         break;
532       }
533     }
534
535     Instruction *Term = BB->getTerminator();
536     switch (Term->getOpcode()) {
537     case Instruction::Switch:
538       BBChanged |= processSwitch(cast<SwitchInst>(Term), LVI);
539       break;
540     case Instruction::Ret: {
541       auto *RI = cast<ReturnInst>(Term);
542       // Try to determine the return value if we can.  This is mainly here to
543       // simplify the writing of unit tests, but also helps to enable IPO by
544       // constant folding the return values of callees.
545       auto *RetVal = RI->getReturnValue();
546       if (!RetVal) break; // handle "ret void"
547       if (isa<Constant>(RetVal)) break; // nothing to do
548       if (auto *C = getConstantAt(RetVal, RI, LVI)) {
549         ++NumReturns;
550         RI->replaceUsesOfWith(RetVal, C);
551         BBChanged = true;        
552       }
553     }
554     };
555
556     FnChanged |= BBChanged;
557   }
558
559   return FnChanged;
560 }
561
562 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
563   if (skipFunction(F))
564     return false;
565
566   LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
567   return runImpl(F, LVI, getBestSimplifyQuery(*this, F));
568 }
569
570 PreservedAnalyses
571 CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
572
573   LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(F);
574   bool Changed = runImpl(F, LVI, getBestSimplifyQuery(AM, F));
575
576   if (!Changed)
577     return PreservedAnalyses::all();
578   PreservedAnalyses PA;
579   PA.preserve<GlobalsAA>();
580   return PA;
581 }