CorrelatedValuePropagation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/Analysis/InstructionSimplify.h"
  16. #include "llvm/Analysis/LazyValueInfo.h"
  17. #include "llvm/IR/CFG.h"
  18. #include "llvm/IR/Constants.h"
  19. #include "llvm/IR/Function.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "llvm/Transforms/Utils/Local.h"
  26. using namespace llvm;
  27. #define DEBUG_TYPE "correlated-value-propagation"
  28. STATISTIC(NumPhis, "Number of phis propagated");
  29. STATISTIC(NumSelects, "Number of selects propagated");
  30. STATISTIC(NumMemAccess, "Number of memory access targets propagated");
  31. STATISTIC(NumCmps, "Number of comparisons propagated");
  32. STATISTIC(NumDeadCases, "Number of switch cases removed");
  33. namespace {
  34. class CorrelatedValuePropagation : public FunctionPass {
  35. LazyValueInfo *LVI;
  36. bool processSelect(SelectInst *SI);
  37. bool processPHI(PHINode *P);
  38. bool processMemAccess(Instruction *I);
  39. bool processCmp(CmpInst *C);
  40. bool processSwitch(SwitchInst *SI);
  41. public:
  42. static char ID;
  43. CorrelatedValuePropagation(): FunctionPass(ID) {
  44. initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
  45. }
  46. bool runOnFunction(Function &F) override;
  47. void getAnalysisUsage(AnalysisUsage &AU) const override {
  48. AU.addRequired<LazyValueInfo>();
  49. }
  50. };
  51. }
  52. char CorrelatedValuePropagation::ID = 0;
  53. INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
  54. "Value Propagation", false, false)
  55. INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
  56. INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
  57. "Value Propagation", false, false)
  58. // Public interface to the Value Propagation pass
  59. Pass *llvm::createCorrelatedValuePropagationPass() {
  60. return new CorrelatedValuePropagation();
  61. }
  62. bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
  63. if (S->getType()->isVectorTy()) return false;
  64. if (isa<Constant>(S->getOperand(0))) return false;
  65. Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
  66. if (!C) return false;
  67. ConstantInt *CI = dyn_cast<ConstantInt>(C);
  68. if (!CI) return false;
  69. Value *ReplaceWith = S->getOperand(1);
  70. Value *Other = S->getOperand(2);
  71. if (!CI->isOne()) std::swap(ReplaceWith, Other);
  72. if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
  73. S->replaceAllUsesWith(ReplaceWith);
  74. S->eraseFromParent();
  75. ++NumSelects;
  76. return true;
  77. }
  78. bool CorrelatedValuePropagation::processPHI(PHINode *P) {
  79. bool Changed = false;
  80. BasicBlock *BB = P->getParent();
  81. for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
  82. Value *Incoming = P->getIncomingValue(i);
  83. if (isa<Constant>(Incoming)) continue;
  84. Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
  85. // Look if the incoming value is a select with a scalar condition for which
  86. // LVI can tells us the value. In that case replace the incoming value with
  87. // the appropriate value of the select. This often allows us to remove the
  88. // select later.
  89. if (!V) {
  90. SelectInst *SI = dyn_cast<SelectInst>(Incoming);
  91. if (!SI) continue;
  92. Value *Condition = SI->getCondition();
  93. if (!Condition->getType()->isVectorTy()) {
  94. if (Constant *C = LVI->getConstantOnEdge(
  95. Condition, P->getIncomingBlock(i), BB, P)) {
  96. if (C->isOneValue()) {
  97. V = SI->getTrueValue();
  98. } else if (C->isZeroValue()) {
  99. V = SI->getFalseValue();
  100. }
  101. // Once LVI learns to handle vector types, we could also add support
  102. // for vector type constants that are not all zeroes or all ones.
  103. }
  104. }
  105. // Look if the select has a constant but LVI tells us that the incoming
  106. // value can never be that constant. In that case replace the incoming
  107. // value with the other value of the select. This often allows us to
  108. // remove the select later.
  109. if (!V) {
  110. Constant *C = dyn_cast<Constant>(SI->getFalseValue());
  111. if (!C) continue;
  112. if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
  113. P->getIncomingBlock(i), BB, P) !=
  114. LazyValueInfo::False)
  115. continue;
  116. V = SI->getTrueValue();
  117. }
  118. DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
  119. }
  120. P->setIncomingValue(i, V);
  121. Changed = true;
  122. }
  123. // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
  124. const DataLayout &DL = BB->getModule()->getDataLayout();
  125. if (Value *V = SimplifyInstruction(P, DL)) {
  126. P->replaceAllUsesWith(V);
  127. P->eraseFromParent();
  128. Changed = true;
  129. }
  130. if (Changed)
  131. ++NumPhis;
  132. return Changed;
  133. }
  134. bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
  135. Value *Pointer = nullptr;
  136. if (LoadInst *L = dyn_cast<LoadInst>(I))
  137. Pointer = L->getPointerOperand();
  138. else
  139. Pointer = cast<StoreInst>(I)->getPointerOperand();
  140. if (isa<Constant>(Pointer)) return false;
  141. Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
  142. if (!C) return false;
  143. ++NumMemAccess;
  144. I->replaceUsesOfWith(Pointer, C);
  145. return true;
  146. }
  147. /// processCmp - If the value of this comparison could be determined locally,
  148. /// constant propagation would already have figured it out. Instead, walk
  149. /// the predecessors and statically evaluate the comparison based on information
  150. /// available on that edge. If a given static evaluation is true on ALL
  151. /// incoming edges, then it's true universally and we can simplify the compare.
  152. bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
  153. Value *Op0 = C->getOperand(0);
  154. if (isa<Instruction>(Op0) &&
  155. cast<Instruction>(Op0)->getParent() == C->getParent())
  156. return false;
  157. Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
  158. if (!Op1) return false;
  159. pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
  160. if (PI == PE) return false;
  161. LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
  162. C->getOperand(0), Op1, *PI,
  163. C->getParent(), C);
  164. if (Result == LazyValueInfo::Unknown) return false;
  165. ++PI;
  166. while (PI != PE) {
  167. LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
  168. C->getOperand(0), Op1, *PI,
  169. C->getParent(), C);
  170. if (Res != Result) return false;
  171. ++PI;
  172. }
  173. ++NumCmps;
  174. if (Result == LazyValueInfo::True)
  175. C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
  176. else
  177. C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
  178. C->eraseFromParent();
  179. return true;
  180. }
  181. /// processSwitch - Simplify a switch instruction by removing cases which can
  182. /// never fire. If the uselessness of a case could be determined locally then
  183. /// constant propagation would already have figured it out. Instead, walk the
  184. /// predecessors and statically evaluate cases based on information available
  185. /// on that edge. Cases that cannot fire no matter what the incoming edge can
  186. /// safely be removed. If a case fires on every incoming edge then the entire
  187. /// switch can be removed and replaced with a branch to the case destination.
  188. bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
  189. Value *Cond = SI->getCondition();
  190. BasicBlock *BB = SI->getParent();
  191. // If the condition was defined in same block as the switch then LazyValueInfo
  192. // currently won't say anything useful about it, though in theory it could.
  193. if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
  194. return false;
  195. // If the switch is unreachable then trying to improve it is a waste of time.
  196. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  197. if (PB == PE) return false;
  198. // Analyse each switch case in turn. This is done in reverse order so that
  199. // removing a case doesn't cause trouble for the iteration.
  200. bool Changed = false;
  201. for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
  202. ) {
  203. ConstantInt *Case = CI.getCaseValue();
  204. // Check to see if the switch condition is equal to/not equal to the case
  205. // value on every incoming edge, equal/not equal being the same each time.
  206. LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
  207. for (pred_iterator PI = PB; PI != PE; ++PI) {
  208. // Is the switch condition equal to the case value?
  209. LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
  210. Cond, Case, *PI,
  211. BB, SI);
  212. // Give up on this case if nothing is known.
  213. if (Value == LazyValueInfo::Unknown) {
  214. State = LazyValueInfo::Unknown;
  215. break;
  216. }
  217. // If this was the first edge to be visited, record that all other edges
  218. // need to give the same result.
  219. if (PI == PB) {
  220. State = Value;
  221. continue;
  222. }
  223. // If this case is known to fire for some edges and known not to fire for
  224. // others then there is nothing we can do - give up.
  225. if (Value != State) {
  226. State = LazyValueInfo::Unknown;
  227. break;
  228. }
  229. }
  230. if (State == LazyValueInfo::False) {
  231. // This case never fires - remove it.
  232. CI.getCaseSuccessor()->removePredecessor(BB);
  233. SI->removeCase(CI); // Does not invalidate the iterator.
  234. // The condition can be modified by removePredecessor's PHI simplification
  235. // logic.
  236. Cond = SI->getCondition();
  237. ++NumDeadCases;
  238. Changed = true;
  239. } else if (State == LazyValueInfo::True) {
  240. // This case always fires. Arrange for the switch to be turned into an
  241. // unconditional branch by replacing the switch condition with the case
  242. // value.
  243. SI->setCondition(Case);
  244. NumDeadCases += SI->getNumCases();
  245. Changed = true;
  246. break;
  247. }
  248. }
  249. if (Changed)
  250. // If the switch has been simplified to the point where it can be replaced
  251. // by a branch then do so now.
  252. ConstantFoldTerminator(BB);
  253. return Changed;
  254. }
  255. bool CorrelatedValuePropagation::runOnFunction(Function &F) {
  256. if (skipOptnoneFunction(F))
  257. return false;
  258. LVI = &getAnalysis<LazyValueInfo>();
  259. bool FnChanged = false;
  260. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
  261. bool BBChanged = false;
  262. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
  263. Instruction *II = BI++;
  264. switch (II->getOpcode()) {
  265. case Instruction::Select:
  266. BBChanged |= processSelect(cast<SelectInst>(II));
  267. break;
  268. case Instruction::PHI:
  269. BBChanged |= processPHI(cast<PHINode>(II));
  270. break;
  271. case Instruction::ICmp:
  272. case Instruction::FCmp:
  273. BBChanged |= processCmp(cast<CmpInst>(II));
  274. break;
  275. case Instruction::Load:
  276. case Instruction::Store:
  277. BBChanged |= processMemAccess(II);
  278. break;
  279. }
  280. }
  281. Instruction *Term = FI->getTerminator();
  282. switch (Term->getOpcode()) {
  283. case Instruction::Switch:
  284. BBChanged |= processSwitch(cast<SwitchInst>(Term));
  285. break;
  286. }
  287. FnChanged |= BBChanged;
  288. }
  289. return FnChanged;
  290. }