IPConstantPropagation.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
  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 pass implements an _extremely_ simple interprocedural constant
  11. // propagation pass. It could certainly be improved in many different ways,
  12. // like using a worklist. This pass makes arguments dead, but does not remove
  13. // them. The existing dead argument elimination pass should be run after this
  14. // to clean up the mess.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Transforms/IPO.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/CallSite.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/Pass.h"
  26. using namespace llvm;
  27. #define DEBUG_TYPE "ipconstprop"
  28. STATISTIC(NumArgumentsProped, "Number of args turned into constants");
  29. STATISTIC(NumReturnValProped, "Number of return values turned into constants");
  30. namespace {
  31. /// IPCP - The interprocedural constant propagation pass
  32. ///
  33. struct IPCP : public ModulePass {
  34. static char ID; // Pass identification, replacement for typeid
  35. IPCP() : ModulePass(ID) {
  36. initializeIPCPPass(*PassRegistry::getPassRegistry());
  37. }
  38. bool runOnModule(Module &M) override;
  39. private:
  40. bool PropagateConstantsIntoArguments(Function &F);
  41. bool PropagateConstantReturn(Function &F);
  42. };
  43. }
  44. char IPCP::ID = 0;
  45. INITIALIZE_PASS(IPCP, "ipconstprop",
  46. "Interprocedural constant propagation", false, false)
  47. ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
  48. bool IPCP::runOnModule(Module &M) {
  49. bool Changed = false;
  50. bool LocalChange = true;
  51. // FIXME: instead of using smart algorithms, we just iterate until we stop
  52. // making changes.
  53. while (LocalChange) {
  54. LocalChange = false;
  55. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
  56. if (!I->isDeclaration()) {
  57. // Delete any klingons.
  58. I->removeDeadConstantUsers();
  59. if (I->hasLocalLinkage())
  60. LocalChange |= PropagateConstantsIntoArguments(*I);
  61. Changed |= PropagateConstantReturn(*I);
  62. }
  63. Changed |= LocalChange;
  64. }
  65. return Changed;
  66. }
  67. /// PropagateConstantsIntoArguments - Look at all uses of the specified
  68. /// function. If all uses are direct call sites, and all pass a particular
  69. /// constant in for an argument, propagate that constant in as the argument.
  70. ///
  71. bool IPCP::PropagateConstantsIntoArguments(Function &F) {
  72. if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
  73. // For each argument, keep track of its constant value and whether it is a
  74. // constant or not. The bool is driven to true when found to be non-constant.
  75. SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
  76. ArgumentConstants.resize(F.arg_size());
  77. unsigned NumNonconstant = 0;
  78. for (Use &U : F.uses()) {
  79. User *UR = U.getUser();
  80. // Ignore blockaddress uses.
  81. if (isa<BlockAddress>(UR)) continue;
  82. // Used by a non-instruction, or not the callee of a function, do not
  83. // transform.
  84. if (!isa<CallInst>(UR) && !isa<InvokeInst>(UR))
  85. return false;
  86. CallSite CS(cast<Instruction>(UR));
  87. if (!CS.isCallee(&U))
  88. return false;
  89. // Check out all of the potentially constant arguments. Note that we don't
  90. // inspect varargs here.
  91. CallSite::arg_iterator AI = CS.arg_begin();
  92. Function::arg_iterator Arg = F.arg_begin();
  93. for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
  94. ++i, ++AI, ++Arg) {
  95. // If this argument is known non-constant, ignore it.
  96. if (ArgumentConstants[i].second)
  97. continue;
  98. Constant *C = dyn_cast<Constant>(*AI);
  99. if (C && ArgumentConstants[i].first == nullptr) {
  100. ArgumentConstants[i].first = C; // First constant seen.
  101. } else if (C && ArgumentConstants[i].first == C) {
  102. // Still the constant value we think it is.
  103. } else if (*AI == &*Arg) {
  104. // Ignore recursive calls passing argument down.
  105. } else {
  106. // Argument became non-constant. If all arguments are non-constant now,
  107. // give up on this function.
  108. if (++NumNonconstant == ArgumentConstants.size())
  109. return false;
  110. ArgumentConstants[i].second = true;
  111. }
  112. }
  113. }
  114. // If we got to this point, there is a constant argument!
  115. assert(NumNonconstant != ArgumentConstants.size());
  116. bool MadeChange = false;
  117. Function::arg_iterator AI = F.arg_begin();
  118. for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
  119. // Do we have a constant argument?
  120. if (ArgumentConstants[i].second || AI->use_empty() ||
  121. AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
  122. continue;
  123. Value *V = ArgumentConstants[i].first;
  124. if (!V) V = UndefValue::get(AI->getType());
  125. AI->replaceAllUsesWith(V);
  126. ++NumArgumentsProped;
  127. MadeChange = true;
  128. }
  129. return MadeChange;
  130. }
  131. // Check to see if this function returns one or more constants. If so, replace
  132. // all callers that use those return values with the constant value. This will
  133. // leave in the actual return values and instructions, but deadargelim will
  134. // clean that up.
  135. //
  136. // Additionally if a function always returns one of its arguments directly,
  137. // callers will be updated to use the value they pass in directly instead of
  138. // using the return value.
  139. bool IPCP::PropagateConstantReturn(Function &F) {
  140. if (F.getReturnType()->isVoidTy())
  141. return false; // No return value.
  142. // If this function could be overridden later in the link stage, we can't
  143. // propagate information about its results into callers.
  144. if (F.mayBeOverridden())
  145. return false;
  146. // Check to see if this function returns a constant.
  147. SmallVector<Value *,4> RetVals;
  148. StructType *STy = dyn_cast<StructType>(F.getReturnType());
  149. if (STy)
  150. for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
  151. RetVals.push_back(UndefValue::get(STy->getElementType(i)));
  152. else
  153. RetVals.push_back(UndefValue::get(F.getReturnType()));
  154. unsigned NumNonConstant = 0;
  155. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  156. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  157. for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
  158. // Already found conflicting return values?
  159. Value *RV = RetVals[i];
  160. if (!RV)
  161. continue;
  162. // Find the returned value
  163. Value *V;
  164. if (!STy)
  165. V = RI->getOperand(0);
  166. else
  167. V = FindInsertedValue(RI->getOperand(0), i);
  168. if (V) {
  169. // Ignore undefs, we can change them into anything
  170. if (isa<UndefValue>(V))
  171. continue;
  172. // Try to see if all the rets return the same constant or argument.
  173. if (isa<Constant>(V) || isa<Argument>(V)) {
  174. if (isa<UndefValue>(RV)) {
  175. // No value found yet? Try the current one.
  176. RetVals[i] = V;
  177. continue;
  178. }
  179. // Returning the same value? Good.
  180. if (RV == V)
  181. continue;
  182. }
  183. }
  184. // Different or no known return value? Don't propagate this return
  185. // value.
  186. RetVals[i] = nullptr;
  187. // All values non-constant? Stop looking.
  188. if (++NumNonConstant == RetVals.size())
  189. return false;
  190. }
  191. }
  192. // If we got here, the function returns at least one constant value. Loop
  193. // over all users, replacing any uses of the return value with the returned
  194. // constant.
  195. bool MadeChange = false;
  196. for (Use &U : F.uses()) {
  197. CallSite CS(U.getUser());
  198. Instruction* Call = CS.getInstruction();
  199. // Not a call instruction or a call instruction that's not calling F
  200. // directly?
  201. if (!Call || !CS.isCallee(&U))
  202. continue;
  203. // Call result not used?
  204. if (Call->use_empty())
  205. continue;
  206. MadeChange = true;
  207. if (!STy) {
  208. Value* New = RetVals[0];
  209. if (Argument *A = dyn_cast<Argument>(New))
  210. // Was an argument returned? Then find the corresponding argument in
  211. // the call instruction and use that.
  212. New = CS.getArgument(A->getArgNo());
  213. Call->replaceAllUsesWith(New);
  214. continue;
  215. }
  216. for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
  217. Instruction *Ins = cast<Instruction>(*I);
  218. // Increment now, so we can remove the use
  219. ++I;
  220. // Find the index of the retval to replace with
  221. int index = -1;
  222. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
  223. if (EV->hasIndices())
  224. index = *EV->idx_begin();
  225. // If this use uses a specific return value, and we have a replacement,
  226. // replace it.
  227. if (index != -1) {
  228. Value *New = RetVals[index];
  229. if (New) {
  230. if (Argument *A = dyn_cast<Argument>(New))
  231. // Was an argument returned? Then find the corresponding argument in
  232. // the call instruction and use that.
  233. New = CS.getArgument(A->getArgNo());
  234. Ins->replaceAllUsesWith(New);
  235. Ins->eraseFromParent();
  236. }
  237. }
  238. }
  239. }
  240. if (MadeChange) ++NumReturnValProped;
  241. return MadeChange;
  242. }